c++: Allow constexpr decltype(auto) [PR102229]
[official-gcc.git] / gcc / cp / decl.c
blob2e0339858c33c35bfbb18f1f04b033cb55413aec
1 /* Process declarations and variables for -*- C++ -*- compiler.
2 Copyright (C) 1988-2021 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 #include "system.h"
31 #include "coretypes.h"
32 #include "target.h"
33 #include "c-family/c-target.h"
34 #include "cp-tree.h"
35 #include "timevar.h"
36 #include "stringpool.h"
37 #include "cgraph.h"
38 #include "stor-layout.h"
39 #include "varasm.h"
40 #include "attribs.h"
41 #include "flags.h"
42 #include "tree-iterator.h"
43 #include "decl.h"
44 #include "intl.h"
45 #include "toplev.h"
46 #include "c-family/c-objc.h"
47 #include "c-family/c-pragma.h"
48 #include "c-family/c-ubsan.h"
49 #include "debug.h"
50 #include "plugin.h"
51 #include "builtins.h"
52 #include "gimplify.h"
53 #include "asan.h"
54 #include "gcc-rich-location.h"
55 #include "langhooks.h"
56 #include "context.h" /* For 'g'. */
57 #include "omp-general.h"
58 #include "omp-offload.h" /* For offload_vars. */
59 #include "opts.h"
60 #include "langhooks-def.h" /* For lhd_simulate_record_decl */
62 /* Possible cases of bad specifiers type used by bad_specifiers. */
63 enum bad_spec_place {
64 BSP_VAR, /* variable */
65 BSP_PARM, /* parameter */
66 BSP_TYPE, /* type */
67 BSP_FIELD /* field */
70 static const char *redeclaration_error_message (tree, tree);
72 static int decl_jump_unsafe (tree);
73 static void require_complete_types_for_parms (tree);
74 static tree grok_reference_init (tree, tree, tree, int);
75 static tree grokvardecl (tree, tree, tree, const cp_decl_specifier_seq *,
76 int, int, int, bool, int, tree, location_t);
77 static void check_static_variable_definition (tree, tree);
78 static void record_unknown_type (tree, const char *);
79 static int member_function_or_else (tree, tree, enum overload_flags);
80 static tree local_variable_p_walkfn (tree *, int *, void *);
81 static const char *tag_name (enum tag_types);
82 static tree lookup_and_check_tag (enum tag_types, tree, TAG_how, bool);
83 static void maybe_deduce_size_from_array_init (tree, tree);
84 static void layout_var_decl (tree);
85 static tree check_initializer (tree, tree, int, vec<tree, va_gc> **);
86 static void make_rtl_for_nonlocal_decl (tree, tree, const char *);
87 static void copy_type_enum (tree , tree);
88 static void check_function_type (tree, tree);
89 static void finish_constructor_body (void);
90 static void begin_destructor_body (void);
91 static void finish_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;
230 #define named_labels cp_function_chain->x_named_labels
232 /* The number of function bodies which we are currently processing.
233 (Zero if we are at namespace scope, one inside the body of a
234 function, two inside the body of a function in a local class, etc.) */
235 int function_depth;
237 /* Whether the exception-specifier is part of a function type (i.e. C++17). */
238 bool flag_noexcept_type;
240 /* States indicating how grokdeclarator() should handle declspecs marked
241 with __attribute__((deprecated)). An object declared as
242 __attribute__((deprecated)) suppresses warnings of uses of other
243 deprecated items. */
244 enum deprecated_states deprecated_state = DEPRECATED_NORMAL;
247 /* A list of VAR_DECLs whose type was incomplete at the time the
248 variable was declared. */
250 struct GTY(()) incomplete_var {
251 tree decl;
252 tree incomplete_type;
256 static GTY(()) vec<incomplete_var, va_gc> *incomplete_vars;
258 /* Returns the kind of template specialization we are currently
259 processing, given that it's declaration contained N_CLASS_SCOPES
260 explicit scope qualifications. */
262 tmpl_spec_kind
263 current_tmpl_spec_kind (int n_class_scopes)
265 int n_template_parm_scopes = 0;
266 int seen_specialization_p = 0;
267 int innermost_specialization_p = 0;
268 cp_binding_level *b;
270 /* Scan through the template parameter scopes. */
271 for (b = current_binding_level;
272 b->kind == sk_template_parms;
273 b = b->level_chain)
275 /* If we see a specialization scope inside a parameter scope,
276 then something is wrong. That corresponds to a declaration
277 like:
279 template <class T> template <> ...
281 which is always invalid since [temp.expl.spec] forbids the
282 specialization of a class member template if the enclosing
283 class templates are not explicitly specialized as well. */
284 if (b->explicit_spec_p)
286 if (n_template_parm_scopes == 0)
287 innermost_specialization_p = 1;
288 else
289 seen_specialization_p = 1;
291 else if (seen_specialization_p == 1)
292 return tsk_invalid_member_spec;
294 ++n_template_parm_scopes;
297 /* Handle explicit instantiations. */
298 if (processing_explicit_instantiation)
300 if (n_template_parm_scopes != 0)
301 /* We've seen a template parameter list during an explicit
302 instantiation. For example:
304 template <class T> template void f(int);
306 This is erroneous. */
307 return tsk_invalid_expl_inst;
308 else
309 return tsk_expl_inst;
312 if (n_template_parm_scopes < n_class_scopes)
313 /* We've not seen enough template headers to match all the
314 specialized classes present. For example:
316 template <class T> void R<T>::S<T>::f(int);
318 This is invalid; there needs to be one set of template
319 parameters for each class. */
320 return tsk_insufficient_parms;
321 else if (n_template_parm_scopes == n_class_scopes)
322 /* We're processing a non-template declaration (even though it may
323 be a member of a template class.) For example:
325 template <class T> void S<T>::f(int);
327 The `class T' matches the `S<T>', leaving no template headers
328 corresponding to the `f'. */
329 return tsk_none;
330 else if (n_template_parm_scopes > n_class_scopes + 1)
331 /* We've got too many template headers. For example:
333 template <> template <class T> void f (T);
335 There need to be more enclosing classes. */
336 return tsk_excessive_parms;
337 else
338 /* This must be a template. It's of the form:
340 template <class T> template <class U> void S<T>::f(U);
342 This is a specialization if the innermost level was a
343 specialization; otherwise it's just a definition of the
344 template. */
345 return innermost_specialization_p ? tsk_expl_spec : tsk_template;
348 /* Exit the current scope. */
350 void
351 finish_scope (void)
353 poplevel (0, 0, 0);
356 /* When a label goes out of scope, check to see if that label was used
357 in a valid manner, and issue any appropriate warnings or errors. */
359 static void
360 check_label_used (tree label)
362 if (!processing_template_decl)
364 if (DECL_INITIAL (label) == NULL_TREE)
366 location_t location;
368 error ("label %q+D used but not defined", label);
369 location = input_location;
370 /* FIXME want (LOCATION_FILE (input_location), (line)0) */
371 /* Avoid crashing later. */
372 define_label (location, DECL_NAME (label));
374 else
375 warn_for_unused_label (label);
379 /* Helper function to sort named label entries in a vector by DECL_UID. */
381 static int
382 sort_labels (const void *a, const void *b)
384 tree label1 = *(tree const *) a;
385 tree label2 = *(tree const *) b;
387 /* DECL_UIDs can never be equal. */
388 return DECL_UID (label1) > DECL_UID (label2) ? -1 : +1;
391 /* At the end of a function, all labels declared within the function
392 go out of scope. BLOCK is the top-level block for the
393 function. */
395 static void
396 pop_labels (tree block)
398 if (!named_labels)
399 return;
401 /* We need to add the labels to the block chain, so debug
402 information is emitted. But, we want the order to be stable so
403 need to sort them first. Otherwise the debug output could be
404 randomly ordered. I guess it's mostly stable, unless the hash
405 table implementation changes. */
406 auto_vec<tree, 32> labels (named_labels->elements ());
407 hash_table<named_label_hash>::iterator end (named_labels->end ());
408 for (hash_table<named_label_hash>::iterator iter
409 (named_labels->begin ()); iter != end; ++iter)
411 named_label_entry *ent = *iter;
413 gcc_checking_assert (!ent->outer);
414 if (ent->label_decl)
415 labels.quick_push (ent->label_decl);
416 ggc_free (ent);
418 named_labels = NULL;
419 labels.qsort (sort_labels);
421 while (labels.length ())
423 tree label = labels.pop ();
425 DECL_CHAIN (label) = BLOCK_VARS (block);
426 BLOCK_VARS (block) = label;
428 check_label_used (label);
432 /* At the end of a block with local labels, restore the outer definition. */
434 static void
435 pop_local_label (tree id, tree label)
437 check_label_used (label);
438 named_label_entry **slot = named_labels->find_slot_with_hash
439 (id, IDENTIFIER_HASH_VALUE (id), NO_INSERT);
440 named_label_entry *ent = *slot;
442 if (ent->outer)
443 ent = ent->outer;
444 else
446 ent = ggc_cleared_alloc<named_label_entry> ();
447 ent->name = id;
449 *slot = ent;
452 /* The following two routines are used to interface to Objective-C++.
453 The binding level is purposely treated as an opaque type. */
455 void *
456 objc_get_current_scope (void)
458 return current_binding_level;
461 /* The following routine is used by the NeXT-style SJLJ exceptions;
462 variables get marked 'volatile' so as to not be clobbered by
463 _setjmp()/_longjmp() calls. All variables in the current scope,
464 as well as parent scopes up to (but not including) ENCLOSING_BLK
465 shall be thusly marked. */
467 void
468 objc_mark_locals_volatile (void *enclosing_blk)
470 cp_binding_level *scope;
472 for (scope = current_binding_level;
473 scope && scope != enclosing_blk;
474 scope = scope->level_chain)
476 tree decl;
478 for (decl = scope->names; decl; decl = TREE_CHAIN (decl))
479 objc_volatilize_decl (decl);
481 /* Do not climb up past the current function. */
482 if (scope->kind == sk_function_parms)
483 break;
487 /* True if B is the level for the condition of a constexpr if. */
489 static bool
490 level_for_constexpr_if (cp_binding_level *b)
492 return (b->kind == sk_cond && b->this_entity
493 && TREE_CODE (b->this_entity) == IF_STMT
494 && IF_STMT_CONSTEXPR_P (b->this_entity));
497 /* True if B is the level for the condition of a consteval if. */
499 static bool
500 level_for_consteval_if (cp_binding_level *b)
502 return (b->kind == sk_cond && b->this_entity
503 && TREE_CODE (b->this_entity) == IF_STMT
504 && IF_STMT_CONSTEVAL_P (b->this_entity));
507 /* Update data for defined and undefined labels when leaving a scope. */
510 poplevel_named_label_1 (named_label_entry **slot, cp_binding_level *bl)
512 named_label_entry *ent = *slot;
513 cp_binding_level *obl = bl->level_chain;
515 if (ent->binding_level == bl)
517 tree decl;
519 /* ENT->NAMES_IN_SCOPE may contain a mixture of DECLs and
520 TREE_LISTs representing OVERLOADs, so be careful. */
521 for (decl = ent->names_in_scope; decl; decl = (DECL_P (decl)
522 ? DECL_CHAIN (decl)
523 : TREE_CHAIN (decl)))
524 if (decl_jump_unsafe (decl))
525 vec_safe_push (ent->bad_decls, decl);
527 ent->binding_level = obl;
528 ent->names_in_scope = obl->names;
529 switch (bl->kind)
531 case sk_try:
532 ent->in_try_scope = true;
533 break;
534 case sk_catch:
535 ent->in_catch_scope = true;
536 break;
537 case sk_omp:
538 ent->in_omp_scope = true;
539 break;
540 case sk_transaction:
541 ent->in_transaction_scope = true;
542 break;
543 case sk_block:
544 if (level_for_constexpr_if (bl->level_chain))
545 ent->in_constexpr_if = true;
546 else if (level_for_consteval_if (bl->level_chain))
547 ent->in_consteval_if = true;
548 break;
549 default:
550 break;
553 else if (ent->uses)
555 struct named_label_use_entry *use;
557 for (use = ent->uses; use ; use = use->next)
558 if (use->binding_level == bl)
560 use->binding_level = obl;
561 use->names_in_scope = obl->names;
562 if (bl->kind == sk_omp)
563 use->in_omp_scope = true;
567 return 1;
570 /* Saved errorcount to avoid -Wunused-but-set-{parameter,variable} warnings
571 when errors were reported, except for -Werror-unused-but-set-*. */
572 static int unused_but_set_errorcount;
574 /* Exit a binding level.
575 Pop the level off, and restore the state of the identifier-decl mappings
576 that were in effect when this level was entered.
578 If KEEP == 1, this level had explicit declarations, so
579 and create a "block" (a BLOCK node) for the level
580 to record its declarations and subblocks for symbol table output.
582 If FUNCTIONBODY is nonzero, this level is the body of a function,
583 so create a block as if KEEP were set and also clear out all
584 label names.
586 If REVERSE is nonzero, reverse the order of decls before putting
587 them into the BLOCK. */
589 tree
590 poplevel (int keep, int reverse, int functionbody)
592 tree link;
593 /* The chain of decls was accumulated in reverse order.
594 Put it into forward order, just for cleanliness. */
595 tree decls;
596 tree subblocks;
597 tree block;
598 tree decl;
599 scope_kind kind;
601 auto_cond_timevar tv (TV_NAME_LOOKUP);
602 restart:
604 block = NULL_TREE;
606 gcc_assert (current_binding_level->kind != sk_class
607 && current_binding_level->kind != sk_namespace);
609 if (current_binding_level->kind == sk_cleanup)
610 functionbody = 0;
611 subblocks = functionbody >= 0 ? current_binding_level->blocks : 0;
613 gcc_assert (!vec_safe_length (current_binding_level->class_shadowed));
615 /* We used to use KEEP == 2 to indicate that the new block should go
616 at the beginning of the list of blocks at this binding level,
617 rather than the end. This hack is no longer used. */
618 gcc_assert (keep == 0 || keep == 1);
620 if (current_binding_level->keep)
621 keep = 1;
623 /* Any uses of undefined labels, and any defined labels, now operate
624 under constraints of next binding contour. */
625 if (cfun && !functionbody && named_labels)
626 named_labels->traverse<cp_binding_level *, poplevel_named_label_1>
627 (current_binding_level);
629 /* Get the decls in the order they were written.
630 Usually current_binding_level->names is in reverse order.
631 But parameter decls were previously put in forward order. */
633 decls = current_binding_level->names;
634 if (reverse)
636 decls = nreverse (decls);
637 current_binding_level->names = decls;
640 /* If there were any declarations or structure tags in that level,
641 or if this level is a function body,
642 create a BLOCK to record them for the life of this function. */
643 block = NULL_TREE;
644 /* Avoid function body block if possible. */
645 if (functionbody && subblocks && BLOCK_CHAIN (subblocks) == NULL_TREE)
646 keep = 0;
647 else if (keep == 1 || functionbody)
648 block = make_node (BLOCK);
649 if (block != NULL_TREE)
651 BLOCK_VARS (block) = decls;
652 BLOCK_SUBBLOCKS (block) = subblocks;
655 /* In each subblock, record that this is its superior. */
656 if (keep >= 0)
657 for (link = subblocks; link; link = BLOCK_CHAIN (link))
658 BLOCK_SUPERCONTEXT (link) = block;
660 /* Before we remove the declarations first check for unused variables. */
661 if ((warn_unused_variable || warn_unused_but_set_variable)
662 && current_binding_level->kind != sk_template_parms
663 && !processing_template_decl)
664 for (tree d = get_local_decls (); d; d = TREE_CHAIN (d))
666 /* There are cases where D itself is a TREE_LIST. See in
667 push_local_binding where the list of decls returned by
668 getdecls is built. */
669 decl = TREE_CODE (d) == TREE_LIST ? TREE_VALUE (d) : d;
671 tree type = TREE_TYPE (decl);
672 if (VAR_P (decl)
673 && (! TREE_USED (decl) || !DECL_READ_P (decl))
674 && ! DECL_IN_SYSTEM_HEADER (decl)
675 /* For structured bindings, consider only real variables, not
676 subobjects. */
677 && (DECL_DECOMPOSITION_P (decl) ? !DECL_DECOMP_BASE (decl)
678 : (DECL_NAME (decl) && !DECL_ARTIFICIAL (decl)))
679 && type != error_mark_node
680 && (!CLASS_TYPE_P (type)
681 || !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
682 || lookup_attribute ("warn_unused",
683 TYPE_ATTRIBUTES (TREE_TYPE (decl)))))
685 if (! TREE_USED (decl))
687 if (!DECL_NAME (decl) && DECL_DECOMPOSITION_P (decl))
688 warning_at (DECL_SOURCE_LOCATION (decl),
689 OPT_Wunused_variable,
690 "unused structured binding declaration");
691 else
692 warning_at (DECL_SOURCE_LOCATION (decl),
693 OPT_Wunused_variable, "unused variable %qD", decl);
695 else if (DECL_CONTEXT (decl) == current_function_decl
696 // For -Wunused-but-set-variable leave references alone.
697 && !TYPE_REF_P (TREE_TYPE (decl))
698 && errorcount == unused_but_set_errorcount)
700 if (!DECL_NAME (decl) && DECL_DECOMPOSITION_P (decl))
701 warning_at (DECL_SOURCE_LOCATION (decl),
702 OPT_Wunused_but_set_variable, "structured "
703 "binding declaration set but not used");
704 else
705 warning_at (DECL_SOURCE_LOCATION (decl),
706 OPT_Wunused_but_set_variable,
707 "variable %qD set but not used", decl);
708 unused_but_set_errorcount = errorcount;
713 /* Remove declarations for all the DECLs in this level. */
714 for (link = decls; link; link = TREE_CHAIN (link))
716 tree name;
717 if (TREE_CODE (link) == TREE_LIST)
719 decl = TREE_VALUE (link);
720 name = TREE_PURPOSE (link);
721 gcc_checking_assert (name);
723 else
725 decl = link;
726 name = DECL_NAME (decl);
729 /* Remove the binding. */
730 if (TREE_CODE (decl) == LABEL_DECL)
731 pop_local_label (name, decl);
732 else
733 pop_local_binding (name, decl);
736 /* Restore the IDENTIFIER_TYPE_VALUEs. */
737 for (link = current_binding_level->type_shadowed;
738 link; link = TREE_CHAIN (link))
739 SET_IDENTIFIER_TYPE_VALUE (TREE_PURPOSE (link), TREE_VALUE (link));
741 /* There may be OVERLOADs (wrapped in TREE_LISTs) on the BLOCK_VARs
742 list if a `using' declaration put them there. The debugging
743 back ends won't understand OVERLOAD, so we remove them here.
744 Because the BLOCK_VARS are (temporarily) shared with
745 CURRENT_BINDING_LEVEL->NAMES we must do this fixup after we have
746 popped all the bindings. Also remove undeduced 'auto' decls,
747 which LTO doesn't understand, and can't have been used by anything. */
748 if (block)
750 tree* d;
752 for (d = &BLOCK_VARS (block); *d; )
754 if (TREE_CODE (*d) == TREE_LIST
755 || (!processing_template_decl
756 && undeduced_auto_decl (*d)))
757 *d = TREE_CHAIN (*d);
758 else
759 d = &DECL_CHAIN (*d);
763 /* If the level being exited is the top level of a function,
764 check over all the labels. */
765 if (functionbody)
767 if (block)
769 /* Since this is the top level block of a function, the vars are
770 the function's parameters. Don't leave them in the BLOCK
771 because they are found in the FUNCTION_DECL instead. */
772 BLOCK_VARS (block) = 0;
773 pop_labels (block);
775 else
776 pop_labels (subblocks);
779 kind = current_binding_level->kind;
780 if (kind == sk_cleanup)
782 tree stmt;
784 /* If this is a temporary binding created for a cleanup, then we'll
785 have pushed a statement list level. Pop that, create a new
786 BIND_EXPR for the block, and insert it into the stream. */
787 stmt = pop_stmt_list (current_binding_level->statement_list);
788 stmt = c_build_bind_expr (input_location, block, stmt);
789 add_stmt (stmt);
792 leave_scope ();
793 if (functionbody)
795 /* The current function is being defined, so its DECL_INITIAL
796 should be error_mark_node. */
797 gcc_assert (DECL_INITIAL (current_function_decl) == error_mark_node);
798 DECL_INITIAL (current_function_decl) = block ? block : subblocks;
799 if (subblocks)
801 if (FUNCTION_NEEDS_BODY_BLOCK (current_function_decl))
803 if (BLOCK_SUBBLOCKS (subblocks))
804 BLOCK_OUTER_CURLY_BRACE_P (BLOCK_SUBBLOCKS (subblocks)) = 1;
806 else
807 BLOCK_OUTER_CURLY_BRACE_P (subblocks) = 1;
810 else if (block)
811 current_binding_level->blocks
812 = block_chainon (current_binding_level->blocks, block);
814 /* If we did not make a block for the level just exited,
815 any blocks made for inner levels
816 (since they cannot be recorded as subblocks in that level)
817 must be carried forward so they will later become subblocks
818 of something else. */
819 else if (subblocks)
820 current_binding_level->blocks
821 = block_chainon (current_binding_level->blocks, subblocks);
823 /* Each and every BLOCK node created here in `poplevel' is important
824 (e.g. for proper debugging information) so if we created one
825 earlier, mark it as "used". */
826 if (block)
827 TREE_USED (block) = 1;
829 /* All temporary bindings created for cleanups are popped silently. */
830 if (kind == sk_cleanup)
831 goto restart;
833 return block;
836 /* Call wrapup_globals_declarations for the globals in NAMESPACE. */
837 /* Diagnose odr-used extern inline variables without definitions
838 in the current TU. */
841 wrapup_namespace_globals ()
843 if (vec<tree, va_gc> *statics = static_decls)
845 for (tree decl : *statics)
847 if (warn_unused_function
848 && TREE_CODE (decl) == FUNCTION_DECL
849 && DECL_INITIAL (decl) == 0
850 && DECL_EXTERNAL (decl)
851 && !TREE_PUBLIC (decl)
852 && !DECL_ARTIFICIAL (decl)
853 && !DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl)
854 && !warning_suppressed_p (decl, OPT_Wunused_function))
855 warning_at (DECL_SOURCE_LOCATION (decl),
856 OPT_Wunused_function,
857 "%qF declared %<static%> but never defined", decl);
859 if (VAR_P (decl)
860 && DECL_EXTERNAL (decl)
861 && DECL_INLINE_VAR_P (decl)
862 && DECL_ODR_USED (decl))
863 error_at (DECL_SOURCE_LOCATION (decl),
864 "odr-used inline variable %qD is not defined", decl);
867 /* Clear out the list, so we don't rescan next time. */
868 static_decls = NULL;
870 /* Write out any globals that need to be output. */
871 return wrapup_global_declarations (statics->address (),
872 statics->length ());
874 return 0;
877 /* In C++, you don't have to write `struct S' to refer to `S'; you
878 can just use `S'. We accomplish this by creating a TYPE_DECL as
879 if the user had written `typedef struct S S'. Create and return
880 the TYPE_DECL for TYPE. */
882 tree
883 create_implicit_typedef (tree name, tree type)
885 tree decl;
887 decl = build_decl (input_location, TYPE_DECL, name, type);
888 DECL_ARTIFICIAL (decl) = 1;
889 /* There are other implicit type declarations, like the one *within*
890 a class that allows you to write `S::S'. We must distinguish
891 amongst these. */
892 SET_DECL_IMPLICIT_TYPEDEF_P (decl);
893 TYPE_NAME (type) = decl;
894 TYPE_STUB_DECL (type) = decl;
896 return decl;
899 /* Function-scope local entities that need discriminators. Each entry
900 is a {decl,name} pair. VAR_DECLs for anon unions get their name
901 smashed, so we cannot rely on DECL_NAME. */
903 static GTY((deletable)) vec<tree, va_gc> *local_entities;
905 /* Determine the mangling discriminator of local DECL. There are
906 generally very few of these in any particular function. */
908 void
909 determine_local_discriminator (tree decl)
911 auto_cond_timevar tv (TV_NAME_LOOKUP);
912 retrofit_lang_decl (decl);
913 tree ctx = DECL_CONTEXT (decl);
914 tree name = (TREE_CODE (decl) == TYPE_DECL
915 && TYPE_UNNAMED_P (TREE_TYPE (decl))
916 ? NULL_TREE : DECL_NAME (decl));
917 size_t nelts = vec_safe_length (local_entities);
918 for (size_t i = 0; i < nelts; i += 2)
920 tree *pair = &(*local_entities)[i];
921 tree d = pair[0];
922 tree n = pair[1];
923 gcc_checking_assert (d != decl);
924 if (name == n
925 && TREE_CODE (decl) == TREE_CODE (d)
926 && ctx == DECL_CONTEXT (d))
928 tree disc = integer_one_node;
929 if (DECL_DISCRIMINATOR (d))
930 disc = build_int_cst (TREE_TYPE (disc),
931 TREE_INT_CST_LOW (DECL_DISCRIMINATOR (d)) + 1);
932 DECL_DISCRIMINATOR (decl) = disc;
933 /* Replace the saved decl. */
934 pair[0] = decl;
935 decl = NULL_TREE;
936 break;
940 if (decl)
942 vec_safe_reserve (local_entities, 2);
943 local_entities->quick_push (decl);
944 local_entities->quick_push (name);
950 /* Returns true if functions FN1 and FN2 have equivalent trailing
951 requires clauses. */
953 static bool
954 function_requirements_equivalent_p (tree newfn, tree oldfn)
956 /* In the concepts TS, the combined constraints are compared. */
957 if (cxx_dialect < cxx20
958 && (DECL_TEMPLATE_SPECIALIZATION (newfn)
959 <= DECL_TEMPLATE_SPECIALIZATION (oldfn)))
961 tree ci1 = get_constraints (oldfn);
962 tree ci2 = get_constraints (newfn);
963 tree req1 = ci1 ? CI_ASSOCIATED_CONSTRAINTS (ci1) : NULL_TREE;
964 tree req2 = ci2 ? CI_ASSOCIATED_CONSTRAINTS (ci2) : NULL_TREE;
965 return cp_tree_equal (req1, req2);
968 /* Compare only trailing requirements. */
969 tree reqs1 = get_trailing_function_requirements (newfn);
970 tree reqs2 = get_trailing_function_requirements (oldfn);
971 if ((reqs1 != NULL_TREE) != (reqs2 != NULL_TREE))
972 return false;
974 /* Substitution is needed when friends are involved. */
975 reqs1 = maybe_substitute_reqs_for (reqs1, newfn);
976 reqs2 = maybe_substitute_reqs_for (reqs2, oldfn);
978 return cp_tree_equal (reqs1, reqs2);
981 /* Subroutine of duplicate_decls: return truthvalue of whether
982 or not types of these decls match.
984 For C++, we must compare the parameter list so that `int' can match
985 `int&' in a parameter position, but `int&' is not confused with
986 `const int&'. */
989 decls_match (tree newdecl, tree olddecl, bool record_versions /* = true */)
991 int types_match;
993 if (newdecl == olddecl)
994 return 1;
996 if (TREE_CODE (newdecl) != TREE_CODE (olddecl))
997 /* If the two DECLs are not even the same kind of thing, we're not
998 interested in their types. */
999 return 0;
1001 gcc_assert (DECL_P (newdecl));
1003 if (TREE_CODE (newdecl) == FUNCTION_DECL)
1005 /* Specializations of different templates are different functions
1006 even if they have the same type. */
1007 tree t1 = (DECL_USE_TEMPLATE (newdecl)
1008 ? DECL_TI_TEMPLATE (newdecl)
1009 : NULL_TREE);
1010 tree t2 = (DECL_USE_TEMPLATE (olddecl)
1011 ? DECL_TI_TEMPLATE (olddecl)
1012 : NULL_TREE);
1013 if (t1 != t2)
1014 return 0;
1016 if (CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl)
1017 && ! (DECL_EXTERN_C_P (newdecl)
1018 && DECL_EXTERN_C_P (olddecl)))
1019 return 0;
1021 /* A new declaration doesn't match a built-in one unless it
1022 is also extern "C". */
1023 if (DECL_IS_UNDECLARED_BUILTIN (olddecl)
1024 && DECL_EXTERN_C_P (olddecl) && !DECL_EXTERN_C_P (newdecl))
1025 return 0;
1027 tree f1 = TREE_TYPE (newdecl);
1028 tree f2 = TREE_TYPE (olddecl);
1029 if (TREE_CODE (f1) != TREE_CODE (f2))
1030 return 0;
1032 /* A declaration with deduced return type should use its pre-deduction
1033 type for declaration matching. */
1034 tree r2 = fndecl_declared_return_type (olddecl);
1035 tree r1 = fndecl_declared_return_type (newdecl);
1037 tree p1 = TYPE_ARG_TYPES (f1);
1038 tree p2 = TYPE_ARG_TYPES (f2);
1040 if (same_type_p (r1, r2))
1042 if (!prototype_p (f2) && DECL_EXTERN_C_P (olddecl)
1043 && fndecl_built_in_p (olddecl))
1045 types_match = self_promoting_args_p (p1);
1046 if (p1 == void_list_node)
1047 TREE_TYPE (newdecl) = TREE_TYPE (olddecl);
1049 else
1050 types_match =
1051 compparms (p1, p2)
1052 && type_memfn_rqual (f1) == type_memfn_rqual (f2)
1053 && (TYPE_ATTRIBUTES (TREE_TYPE (newdecl)) == NULL_TREE
1054 || comp_type_attributes (TREE_TYPE (newdecl),
1055 TREE_TYPE (olddecl)) != 0);
1057 else
1058 types_match = 0;
1060 /* Two function declarations match if either has a requires-clause
1061 then both have a requires-clause and their constraints-expressions
1062 are equivalent. */
1063 if (types_match && flag_concepts)
1064 types_match = function_requirements_equivalent_p (newdecl, olddecl);
1066 /* The decls dont match if they correspond to two different versions
1067 of the same function. Disallow extern "C" functions to be
1068 versions for now. */
1069 if (types_match
1070 && !DECL_EXTERN_C_P (newdecl)
1071 && !DECL_EXTERN_C_P (olddecl)
1072 && record_versions
1073 && maybe_version_functions (newdecl, olddecl,
1074 (!DECL_FUNCTION_VERSIONED (newdecl)
1075 || !DECL_FUNCTION_VERSIONED (olddecl))))
1076 return 0;
1078 else if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1080 if (!template_heads_equivalent_p (newdecl, olddecl))
1081 return 0;
1083 tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1084 tree newres = DECL_TEMPLATE_RESULT (newdecl);
1086 if (TREE_CODE (newres) != TREE_CODE (oldres))
1087 return 0;
1089 /* Two template types match if they are the same. Otherwise, compare
1090 the underlying declarations. */
1091 if (TREE_CODE (newres) == TYPE_DECL)
1092 types_match = same_type_p (TREE_TYPE (newres), TREE_TYPE (oldres));
1093 else
1094 types_match = decls_match (newres, oldres);
1096 else
1098 /* Need to check scope for variable declaration (VAR_DECL).
1099 For typedef (TYPE_DECL), scope is ignored. */
1100 if (VAR_P (newdecl)
1101 && CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl)
1102 /* [dcl.link]
1103 Two declarations for an object with C language linkage
1104 with the same name (ignoring the namespace that qualify
1105 it) that appear in different namespace scopes refer to
1106 the same object. */
1107 && !(DECL_EXTERN_C_P (olddecl) && DECL_EXTERN_C_P (newdecl)))
1108 return 0;
1110 if (TREE_TYPE (newdecl) == error_mark_node)
1111 types_match = TREE_TYPE (olddecl) == error_mark_node;
1112 else if (TREE_TYPE (olddecl) == NULL_TREE)
1113 types_match = TREE_TYPE (newdecl) == NULL_TREE;
1114 else if (TREE_TYPE (newdecl) == NULL_TREE)
1115 types_match = 0;
1116 else
1117 types_match = comptypes (TREE_TYPE (newdecl),
1118 TREE_TYPE (olddecl),
1119 COMPARE_REDECLARATION);
1122 return types_match;
1125 /* Mark DECL as versioned if it isn't already. */
1127 static void
1128 maybe_mark_function_versioned (tree decl)
1130 if (!DECL_FUNCTION_VERSIONED (decl))
1132 DECL_FUNCTION_VERSIONED (decl) = 1;
1133 /* If DECL_ASSEMBLER_NAME has already been set, re-mangle
1134 to include the version marker. */
1135 if (DECL_ASSEMBLER_NAME_SET_P (decl))
1136 mangle_decl (decl);
1140 /* NEWDECL and OLDDECL have identical signatures. If they are
1141 different versions adjust them and return true.
1142 If RECORD is set to true, record function versions. */
1144 bool
1145 maybe_version_functions (tree newdecl, tree olddecl, bool record)
1147 if (!targetm.target_option.function_versions (newdecl, olddecl))
1148 return false;
1150 maybe_mark_function_versioned (olddecl);
1151 if (DECL_LOCAL_DECL_P (olddecl))
1153 olddecl = DECL_LOCAL_DECL_ALIAS (olddecl);
1154 maybe_mark_function_versioned (olddecl);
1157 maybe_mark_function_versioned (newdecl);
1158 if (DECL_LOCAL_DECL_P (newdecl))
1160 /* Unfortunately, we can get here before pushdecl naturally calls
1161 push_local_extern_decl_alias, so we need to call it directly. */
1162 if (!DECL_LOCAL_DECL_ALIAS (newdecl))
1163 push_local_extern_decl_alias (newdecl);
1164 newdecl = DECL_LOCAL_DECL_ALIAS (newdecl);
1165 maybe_mark_function_versioned (newdecl);
1168 if (record)
1169 cgraph_node::record_function_versions (olddecl, newdecl);
1171 return true;
1174 /* If NEWDECL is `static' and an `extern' was seen previously,
1175 warn about it. OLDDECL is the previous declaration.
1177 Note that this does not apply to the C++ case of declaring
1178 a variable `extern const' and then later `const'.
1180 Don't complain about built-in functions, since they are beyond
1181 the user's control. */
1183 void
1184 warn_extern_redeclared_static (tree newdecl, tree olddecl)
1186 if (TREE_CODE (newdecl) == TYPE_DECL
1187 || TREE_CODE (newdecl) == TEMPLATE_DECL
1188 || TREE_CODE (newdecl) == CONST_DECL
1189 || TREE_CODE (newdecl) == NAMESPACE_DECL)
1190 return;
1192 /* Don't get confused by static member functions; that's a different
1193 use of `static'. */
1194 if (TREE_CODE (newdecl) == FUNCTION_DECL
1195 && DECL_STATIC_FUNCTION_P (newdecl))
1196 return;
1198 /* If the old declaration was `static', or the new one isn't, then
1199 everything is OK. */
1200 if (DECL_THIS_STATIC (olddecl) || !DECL_THIS_STATIC (newdecl))
1201 return;
1203 /* It's OK to declare a builtin function as `static'. */
1204 if (TREE_CODE (olddecl) == FUNCTION_DECL
1205 && DECL_ARTIFICIAL (olddecl))
1206 return;
1208 auto_diagnostic_group d;
1209 if (permerror (DECL_SOURCE_LOCATION (newdecl),
1210 "%qD was declared %<extern%> and later %<static%>", newdecl))
1211 inform (DECL_SOURCE_LOCATION (olddecl),
1212 "previous declaration of %qD", olddecl);
1215 /* NEW_DECL is a redeclaration of OLD_DECL; both are functions or
1216 function templates. If their exception specifications do not
1217 match, issue a diagnostic. */
1219 static void
1220 check_redeclaration_exception_specification (tree new_decl,
1221 tree old_decl)
1223 tree new_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (new_decl));
1224 tree old_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (old_decl));
1226 /* Two default specs are equivalent, don't force evaluation. */
1227 if (UNEVALUATED_NOEXCEPT_SPEC_P (new_exceptions)
1228 && UNEVALUATED_NOEXCEPT_SPEC_P (old_exceptions))
1229 return;
1231 if (!type_dependent_expression_p (old_decl))
1233 maybe_instantiate_noexcept (new_decl);
1234 maybe_instantiate_noexcept (old_decl);
1236 new_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (new_decl));
1237 old_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (old_decl));
1239 /* [except.spec]
1241 If any declaration of a function has an exception-specification,
1242 all declarations, including the definition and an explicit
1243 specialization, of that function shall have an
1244 exception-specification with the same set of type-ids. */
1245 if (!DECL_IS_UNDECLARED_BUILTIN (old_decl)
1246 && !DECL_IS_UNDECLARED_BUILTIN (new_decl)
1247 && !comp_except_specs (new_exceptions, old_exceptions, ce_normal))
1249 const char *const msg
1250 = G_("declaration of %qF has a different exception specifier");
1251 bool complained = true;
1252 location_t new_loc = DECL_SOURCE_LOCATION (new_decl);
1253 auto_diagnostic_group d;
1254 if (DECL_IN_SYSTEM_HEADER (old_decl))
1255 complained = pedwarn (new_loc, OPT_Wsystem_headers, msg, new_decl);
1256 else if (!flag_exceptions)
1257 /* We used to silently permit mismatched eh specs with
1258 -fno-exceptions, so make them a pedwarn now. */
1259 complained = pedwarn (new_loc, OPT_Wpedantic, msg, new_decl);
1260 else
1261 error_at (new_loc, msg, new_decl);
1262 if (complained)
1263 inform (DECL_SOURCE_LOCATION (old_decl),
1264 "from previous declaration %qF", old_decl);
1268 /* Return true if OLD_DECL and NEW_DECL agree on constexprness.
1269 Otherwise issue diagnostics. */
1271 static bool
1272 validate_constexpr_redeclaration (tree old_decl, tree new_decl)
1274 old_decl = STRIP_TEMPLATE (old_decl);
1275 new_decl = STRIP_TEMPLATE (new_decl);
1276 if (!VAR_OR_FUNCTION_DECL_P (old_decl)
1277 || !VAR_OR_FUNCTION_DECL_P (new_decl))
1278 return true;
1279 if (DECL_DECLARED_CONSTEXPR_P (old_decl)
1280 == DECL_DECLARED_CONSTEXPR_P (new_decl))
1282 if (TREE_CODE (old_decl) != FUNCTION_DECL)
1283 return true;
1284 if (DECL_IMMEDIATE_FUNCTION_P (old_decl)
1285 == DECL_IMMEDIATE_FUNCTION_P (new_decl))
1286 return true;
1288 if (TREE_CODE (old_decl) == FUNCTION_DECL)
1290 /* With -fimplicit-constexpr, ignore changes in the constexpr
1291 keyword. */
1292 if (flag_implicit_constexpr
1293 && (DECL_IMMEDIATE_FUNCTION_P (new_decl)
1294 == DECL_IMMEDIATE_FUNCTION_P (old_decl)))
1295 return true;
1296 if (fndecl_built_in_p (old_decl))
1298 /* Hide a built-in declaration. */
1299 DECL_DECLARED_CONSTEXPR_P (old_decl)
1300 = DECL_DECLARED_CONSTEXPR_P (new_decl);
1301 if (DECL_IMMEDIATE_FUNCTION_P (new_decl))
1302 SET_DECL_IMMEDIATE_FUNCTION_P (old_decl);
1303 return true;
1305 /* 7.1.5 [dcl.constexpr]
1306 Note: An explicit specialization can differ from the template
1307 declaration with respect to the constexpr specifier. */
1308 if (! DECL_TEMPLATE_SPECIALIZATION (old_decl)
1309 && DECL_TEMPLATE_SPECIALIZATION (new_decl))
1310 return true;
1312 const char *kind = "constexpr";
1313 if (DECL_IMMEDIATE_FUNCTION_P (old_decl)
1314 || DECL_IMMEDIATE_FUNCTION_P (new_decl))
1315 kind = "consteval";
1316 error_at (DECL_SOURCE_LOCATION (new_decl),
1317 "redeclaration %qD differs in %qs "
1318 "from previous declaration", new_decl,
1319 kind);
1320 inform (DECL_SOURCE_LOCATION (old_decl),
1321 "previous declaration %qD", old_decl);
1322 return false;
1324 return true;
1327 // If OLDDECL and NEWDECL are concept declarations with the same type
1328 // (i.e., and template parameters), but different requirements,
1329 // emit diagnostics and return true. Otherwise, return false.
1330 static inline bool
1331 check_concept_refinement (tree olddecl, tree newdecl)
1333 if (!DECL_DECLARED_CONCEPT_P (olddecl) || !DECL_DECLARED_CONCEPT_P (newdecl))
1334 return false;
1336 tree d1 = DECL_TEMPLATE_RESULT (olddecl);
1337 tree d2 = DECL_TEMPLATE_RESULT (newdecl);
1338 if (TREE_CODE (d1) != TREE_CODE (d2))
1339 return false;
1341 tree t1 = TREE_TYPE (d1);
1342 tree t2 = TREE_TYPE (d2);
1343 if (TREE_CODE (d1) == FUNCTION_DECL)
1345 if (compparms (TYPE_ARG_TYPES (t1), TYPE_ARG_TYPES (t2))
1346 && comp_template_parms (DECL_TEMPLATE_PARMS (olddecl),
1347 DECL_TEMPLATE_PARMS (newdecl))
1348 && !equivalently_constrained (olddecl, newdecl))
1350 error ("cannot specialize concept %q#D", olddecl);
1351 return true;
1354 return false;
1357 /* DECL is a redeclaration of a function or function template. If
1358 it does have default arguments issue a diagnostic. Note: this
1359 function is used to enforce the requirements in C++11 8.3.6 about
1360 no default arguments in redeclarations. */
1362 static void
1363 check_redeclaration_no_default_args (tree decl)
1365 gcc_assert (DECL_DECLARES_FUNCTION_P (decl));
1367 for (tree t = FUNCTION_FIRST_USER_PARMTYPE (decl);
1368 t && t != void_list_node; t = TREE_CHAIN (t))
1369 if (TREE_PURPOSE (t))
1371 permerror (DECL_SOURCE_LOCATION (decl),
1372 "redeclaration of %q#D may not have default "
1373 "arguments", decl);
1374 return;
1378 /* NEWDECL is a redeclaration of a function or function template OLDDECL,
1379 in any case represented as FUNCTION_DECLs (the DECL_TEMPLATE_RESULTs of
1380 the TEMPLATE_DECLs in case of function templates). This function is used
1381 to enforce the final part of C++17 11.3.6/4, about a single declaration:
1382 "If a friend declaration specifies a default argument expression, that
1383 declaration shall be a definition and shall be the only declaration of
1384 the function or function template in the translation unit." */
1386 static void
1387 check_no_redeclaration_friend_default_args (tree olddecl, tree newdecl)
1389 if (!DECL_UNIQUE_FRIEND_P (olddecl) && !DECL_UNIQUE_FRIEND_P (newdecl))
1390 return;
1392 for (tree t1 = FUNCTION_FIRST_USER_PARMTYPE (olddecl),
1393 t2 = FUNCTION_FIRST_USER_PARMTYPE (newdecl);
1394 t1 && t1 != void_list_node;
1395 t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2))
1396 if ((DECL_UNIQUE_FRIEND_P (olddecl) && TREE_PURPOSE (t1))
1397 || (DECL_UNIQUE_FRIEND_P (newdecl) && TREE_PURPOSE (t2)))
1399 auto_diagnostic_group d;
1400 if (permerror (DECL_SOURCE_LOCATION (newdecl),
1401 "friend declaration of %q#D specifies default "
1402 "arguments and isn%'t the only declaration", newdecl))
1403 inform (DECL_SOURCE_LOCATION (olddecl),
1404 "previous declaration of %q#D", olddecl);
1405 return;
1409 /* Merge tree bits that correspond to attributes noreturn, nothrow,
1410 const, malloc, and pure from NEWDECL with those of OLDDECL. */
1412 static void
1413 merge_attribute_bits (tree newdecl, tree olddecl)
1415 TREE_THIS_VOLATILE (newdecl) |= TREE_THIS_VOLATILE (olddecl);
1416 TREE_THIS_VOLATILE (olddecl) |= TREE_THIS_VOLATILE (newdecl);
1417 TREE_NOTHROW (newdecl) |= TREE_NOTHROW (olddecl);
1418 TREE_NOTHROW (olddecl) |= TREE_NOTHROW (newdecl);
1419 TREE_READONLY (newdecl) |= TREE_READONLY (olddecl);
1420 TREE_READONLY (olddecl) |= TREE_READONLY (newdecl);
1421 DECL_IS_MALLOC (newdecl) |= DECL_IS_MALLOC (olddecl);
1422 DECL_IS_MALLOC (olddecl) |= DECL_IS_MALLOC (newdecl);
1423 DECL_PURE_P (newdecl) |= DECL_PURE_P (olddecl);
1424 DECL_PURE_P (olddecl) |= DECL_PURE_P (newdecl);
1425 DECL_UNINLINABLE (newdecl) |= DECL_UNINLINABLE (olddecl);
1426 DECL_UNINLINABLE (olddecl) |= DECL_UNINLINABLE (newdecl);
1429 #define GNU_INLINE_P(fn) (DECL_DECLARED_INLINE_P (fn) \
1430 && lookup_attribute ("gnu_inline", \
1431 DECL_ATTRIBUTES (fn)))
1433 /* A subroutine of duplicate_decls. Emits a diagnostic when newdecl
1434 ambiguates olddecl. Returns true if an error occurs. */
1436 static bool
1437 duplicate_function_template_decls (tree newdecl, tree olddecl)
1440 tree newres = DECL_TEMPLATE_RESULT (newdecl);
1441 tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1442 /* Function template declarations can be differentiated by parameter
1443 and return type. */
1444 if (compparms (TYPE_ARG_TYPES (TREE_TYPE (oldres)),
1445 TYPE_ARG_TYPES (TREE_TYPE (newres)))
1446 && same_type_p (TREE_TYPE (TREE_TYPE (newdecl)),
1447 TREE_TYPE (TREE_TYPE (olddecl))))
1449 /* ... and also by their template-heads and requires-clauses. */
1450 if (template_heads_equivalent_p (newdecl, olddecl)
1451 && function_requirements_equivalent_p (newres, oldres))
1453 error ("ambiguating new declaration %q+#D", newdecl);
1454 inform (DECL_SOURCE_LOCATION (olddecl),
1455 "old declaration %q#D", olddecl);
1456 return true;
1459 /* FIXME: The types are the same but the are differences
1460 in either the template heads or function requirements.
1461 We should be able to diagnose a set of common errors
1462 stemming from these declarations. For example:
1464 template<typename T> requires C void f(...);
1465 template<typename T> void f(...) requires C;
1467 These are functionally equivalent but not equivalent. */
1470 return false;
1473 /* If NEWDECL is a redeclaration of OLDDECL, merge the declarations.
1474 If the redeclaration is invalid, a diagnostic is issued, and the
1475 error_mark_node is returned. Otherwise, OLDDECL is returned.
1477 If NEWDECL is not a redeclaration of OLDDECL, NULL_TREE is
1478 returned.
1480 HIDING is true if the new decl is being hidden. WAS_HIDDEN is true
1481 if the old decl was hidden.
1483 Hidden decls can be anticipated builtins, injected friends, or
1484 (coming soon) injected from a local-extern decl. */
1486 tree
1487 duplicate_decls (tree newdecl, tree olddecl, bool hiding, bool was_hidden)
1489 unsigned olddecl_uid = DECL_UID (olddecl);
1490 int types_match = 0;
1491 int new_defines_function = 0;
1492 tree new_template_info;
1493 location_t olddecl_loc = DECL_SOURCE_LOCATION (olddecl);
1494 location_t newdecl_loc = DECL_SOURCE_LOCATION (newdecl);
1496 if (newdecl == olddecl)
1497 return olddecl;
1499 types_match = decls_match (newdecl, olddecl);
1501 /* If either the type of the new decl or the type of the old decl is an
1502 error_mark_node, then that implies that we have already issued an
1503 error (earlier) for some bogus type specification, and in that case,
1504 it is rather pointless to harass the user with yet more error message
1505 about the same declaration, so just pretend the types match here. */
1506 if (TREE_TYPE (newdecl) == error_mark_node
1507 || TREE_TYPE (olddecl) == error_mark_node)
1508 return error_mark_node;
1510 /* Check for redeclaration and other discrepancies. */
1511 if (TREE_CODE (olddecl) == FUNCTION_DECL
1512 && DECL_IS_UNDECLARED_BUILTIN (olddecl))
1514 if (TREE_CODE (newdecl) != FUNCTION_DECL)
1516 /* Avoid warnings redeclaring built-ins which have not been
1517 explicitly declared. */
1518 if (was_hidden)
1520 if (TREE_PUBLIC (newdecl)
1521 && CP_DECL_CONTEXT (newdecl) == global_namespace)
1522 warning_at (newdecl_loc,
1523 OPT_Wbuiltin_declaration_mismatch,
1524 "built-in function %qD declared as non-function",
1525 newdecl);
1526 return NULL_TREE;
1529 /* If you declare a built-in or predefined function name as static,
1530 the old definition is overridden, but optionally warn this was a
1531 bad choice of name. */
1532 if (! TREE_PUBLIC (newdecl))
1534 warning_at (newdecl_loc,
1535 OPT_Wshadow,
1536 fndecl_built_in_p (olddecl)
1537 ? G_("shadowing built-in function %q#D")
1538 : G_("shadowing library function %q#D"), olddecl);
1539 /* Discard the old built-in function. */
1540 return NULL_TREE;
1542 /* If the built-in is not ansi, then programs can override
1543 it even globally without an error. */
1544 else if (! fndecl_built_in_p (olddecl))
1545 warning_at (newdecl_loc, 0,
1546 "library function %q#D redeclared as non-function %q#D",
1547 olddecl, newdecl);
1548 else
1549 error_at (newdecl_loc,
1550 "declaration of %q#D conflicts with built-in "
1551 "declaration %q#D", newdecl, olddecl);
1552 return NULL_TREE;
1554 else if (!types_match)
1556 /* Avoid warnings redeclaring built-ins which have not been
1557 explicitly declared. */
1558 if (was_hidden)
1560 tree t1, t2;
1562 /* A new declaration doesn't match a built-in one unless it
1563 is also extern "C". */
1564 gcc_assert (DECL_IS_UNDECLARED_BUILTIN (olddecl));
1565 gcc_assert (DECL_EXTERN_C_P (olddecl));
1566 if (!DECL_EXTERN_C_P (newdecl))
1567 return NULL_TREE;
1569 for (t1 = TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1570 t2 = TYPE_ARG_TYPES (TREE_TYPE (olddecl));
1571 t1 || t2;
1572 t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2))
1574 if (!t1 || !t2)
1575 break;
1576 /* FILE, tm types are not known at the time
1577 we create the builtins. */
1578 for (unsigned i = 0;
1579 i < sizeof (builtin_structptr_types)
1580 / sizeof (builtin_structptr_type);
1581 ++i)
1582 if (TREE_VALUE (t2) == builtin_structptr_types[i].node)
1584 tree t = TREE_VALUE (t1);
1586 if (TYPE_PTR_P (t)
1587 && TYPE_IDENTIFIER (TREE_TYPE (t))
1588 == get_identifier (builtin_structptr_types[i].str)
1589 && compparms (TREE_CHAIN (t1), TREE_CHAIN (t2)))
1591 tree oldargs = TYPE_ARG_TYPES (TREE_TYPE (olddecl));
1593 TYPE_ARG_TYPES (TREE_TYPE (olddecl))
1594 = TYPE_ARG_TYPES (TREE_TYPE (newdecl));
1595 types_match = decls_match (newdecl, olddecl);
1596 if (types_match)
1597 return duplicate_decls (newdecl, olddecl,
1598 hiding, was_hidden);
1599 TYPE_ARG_TYPES (TREE_TYPE (olddecl)) = oldargs;
1601 goto next_arg;
1604 if (! same_type_p (TREE_VALUE (t1), TREE_VALUE (t2)))
1605 break;
1606 next_arg:;
1609 warning_at (newdecl_loc,
1610 OPT_Wbuiltin_declaration_mismatch,
1611 "declaration of %q#D conflicts with built-in "
1612 "declaration %q#D", newdecl, olddecl);
1614 else if ((DECL_EXTERN_C_P (newdecl)
1615 && DECL_EXTERN_C_P (olddecl))
1616 || compparms (TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1617 TYPE_ARG_TYPES (TREE_TYPE (olddecl))))
1619 /* Don't really override olddecl for __* prefixed builtins
1620 except for __[^b]*_chk, the compiler might be using those
1621 explicitly. */
1622 if (fndecl_built_in_p (olddecl))
1624 tree id = DECL_NAME (olddecl);
1625 const char *name = IDENTIFIER_POINTER (id);
1626 size_t len;
1628 if (name[0] == '_'
1629 && name[1] == '_'
1630 && (startswith (name + 2, "builtin_")
1631 || (len = strlen (name)) <= strlen ("___chk")
1632 || memcmp (name + len - strlen ("_chk"),
1633 "_chk", strlen ("_chk") + 1) != 0))
1635 if (DECL_INITIAL (newdecl))
1637 error_at (newdecl_loc,
1638 "definition of %q#D ambiguates built-in "
1639 "declaration %q#D", newdecl, olddecl);
1640 return error_mark_node;
1642 auto_diagnostic_group d;
1643 if (permerror (newdecl_loc,
1644 "new declaration %q#D ambiguates built-in"
1645 " declaration %q#D", newdecl, olddecl)
1646 && flag_permissive)
1647 inform (newdecl_loc,
1648 "ignoring the %q#D declaration", newdecl);
1649 return flag_permissive ? olddecl : error_mark_node;
1653 /* A near match; override the builtin. */
1655 if (TREE_PUBLIC (newdecl))
1656 warning_at (newdecl_loc,
1657 OPT_Wbuiltin_declaration_mismatch,
1658 "new declaration %q#D ambiguates built-in "
1659 "declaration %q#D", newdecl, olddecl);
1660 else
1661 warning (OPT_Wshadow,
1662 fndecl_built_in_p (olddecl)
1663 ? G_("shadowing built-in function %q#D")
1664 : G_("shadowing library function %q#D"), olddecl);
1666 else
1667 /* Discard the old built-in function. */
1668 return NULL_TREE;
1670 /* Replace the old RTL to avoid problems with inlining. */
1671 COPY_DECL_RTL (newdecl, olddecl);
1673 else
1675 /* Even if the types match, prefer the new declarations type
1676 for built-ins which have not been explicitly declared,
1677 for exception lists, etc... */
1678 tree type = TREE_TYPE (newdecl);
1679 tree attribs = (*targetm.merge_type_attributes)
1680 (TREE_TYPE (olddecl), type);
1682 type = cp_build_type_attribute_variant (type, attribs);
1683 TREE_TYPE (newdecl) = TREE_TYPE (olddecl) = type;
1686 /* If a function is explicitly declared "throw ()", propagate that to
1687 the corresponding builtin. */
1688 if (DECL_BUILT_IN_CLASS (olddecl) == BUILT_IN_NORMAL
1689 && was_hidden
1690 && TREE_NOTHROW (newdecl)
1691 && !TREE_NOTHROW (olddecl))
1693 enum built_in_function fncode = DECL_FUNCTION_CODE (olddecl);
1694 tree tmpdecl = builtin_decl_explicit (fncode);
1695 if (tmpdecl && tmpdecl != olddecl && types_match)
1696 TREE_NOTHROW (tmpdecl) = 1;
1699 /* Whether or not the builtin can throw exceptions has no
1700 bearing on this declarator. */
1701 TREE_NOTHROW (olddecl) = 0;
1703 if (DECL_THIS_STATIC (newdecl) && !DECL_THIS_STATIC (olddecl))
1705 /* If a builtin function is redeclared as `static', merge
1706 the declarations, but make the original one static. */
1707 DECL_THIS_STATIC (olddecl) = 1;
1708 TREE_PUBLIC (olddecl) = 0;
1710 /* Make the old declaration consistent with the new one so
1711 that all remnants of the builtin-ness of this function
1712 will be banished. */
1713 SET_DECL_LANGUAGE (olddecl, DECL_LANGUAGE (newdecl));
1714 COPY_DECL_RTL (newdecl, olddecl);
1717 else if (TREE_CODE (olddecl) != TREE_CODE (newdecl))
1719 /* C++ Standard, 3.3, clause 4:
1720 "[Note: a namespace name or a class template name must be unique
1721 in its declarative region (7.3.2, clause 14). ]" */
1722 if (TREE_CODE (olddecl) == NAMESPACE_DECL
1723 || TREE_CODE (newdecl) == NAMESPACE_DECL)
1724 /* Namespace conflicts with not namespace. */;
1725 else if (DECL_TYPE_TEMPLATE_P (olddecl)
1726 || DECL_TYPE_TEMPLATE_P (newdecl))
1727 /* Class template conflicts. */;
1728 else if ((TREE_CODE (olddecl) == TEMPLATE_DECL
1729 && DECL_TEMPLATE_RESULT (olddecl)
1730 && TREE_CODE (DECL_TEMPLATE_RESULT (olddecl)) == VAR_DECL)
1731 || (TREE_CODE (newdecl) == TEMPLATE_DECL
1732 && DECL_TEMPLATE_RESULT (newdecl)
1733 && TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == VAR_DECL))
1734 /* Variable template conflicts. */;
1735 else if (concept_definition_p (olddecl)
1736 || concept_definition_p (newdecl))
1737 /* Concept conflicts. */;
1738 else if ((TREE_CODE (newdecl) == FUNCTION_DECL
1739 && DECL_FUNCTION_TEMPLATE_P (olddecl))
1740 || (TREE_CODE (olddecl) == FUNCTION_DECL
1741 && DECL_FUNCTION_TEMPLATE_P (newdecl)))
1743 /* One is a function and the other is a template
1744 function. */
1745 if (!UDLIT_OPER_P (DECL_NAME (newdecl)))
1746 return NULL_TREE;
1748 /* There can only be one! */
1749 if (TREE_CODE (newdecl) == TEMPLATE_DECL
1750 && check_raw_literal_operator (olddecl))
1751 error_at (newdecl_loc,
1752 "literal operator %q#D conflicts with"
1753 " raw literal operator", newdecl);
1754 else if (check_raw_literal_operator (newdecl))
1755 error_at (newdecl_loc,
1756 "raw literal operator %q#D conflicts with"
1757 " literal operator template", newdecl);
1758 else
1759 return NULL_TREE;
1761 inform (olddecl_loc, "previous declaration %q#D", olddecl);
1762 return error_mark_node;
1764 else if ((VAR_P (olddecl) && DECL_DECOMPOSITION_P (olddecl))
1765 || (VAR_P (newdecl) && DECL_DECOMPOSITION_P (newdecl)))
1766 /* A structured binding must be unique in its declarative region. */;
1767 else if (DECL_IMPLICIT_TYPEDEF_P (olddecl)
1768 || DECL_IMPLICIT_TYPEDEF_P (newdecl))
1769 /* One is an implicit typedef, that's ok. */
1770 return NULL_TREE;
1772 error ("%q#D redeclared as different kind of entity", newdecl);
1773 inform (olddecl_loc, "previous declaration %q#D", olddecl);
1775 return error_mark_node;
1777 else if (!types_match)
1779 if (CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl))
1780 /* These are certainly not duplicate declarations; they're
1781 from different scopes. */
1782 return NULL_TREE;
1784 if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1786 tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1787 tree newres = DECL_TEMPLATE_RESULT (newdecl);
1789 /* The name of a class template may not be declared to refer to
1790 any other template, class, function, object, namespace, value,
1791 or type in the same scope. */
1792 if (TREE_CODE (oldres) == TYPE_DECL
1793 || TREE_CODE (newres) == TYPE_DECL)
1795 error_at (newdecl_loc,
1796 "conflicting declaration of template %q#D", newdecl);
1797 inform (olddecl_loc,
1798 "previous declaration %q#D", olddecl);
1799 return error_mark_node;
1802 else if (TREE_CODE (oldres) == FUNCTION_DECL
1803 && TREE_CODE (newres) == FUNCTION_DECL)
1805 if (duplicate_function_template_decls (newdecl, olddecl))
1806 return error_mark_node;
1807 return NULL_TREE;
1809 else if (check_concept_refinement (olddecl, newdecl))
1810 return error_mark_node;
1811 return NULL_TREE;
1813 if (TREE_CODE (newdecl) == FUNCTION_DECL)
1815 if (DECL_EXTERN_C_P (newdecl) && DECL_EXTERN_C_P (olddecl))
1817 error_at (newdecl_loc,
1818 "conflicting declaration of C function %q#D",
1819 newdecl);
1820 inform (olddecl_loc,
1821 "previous declaration %q#D", olddecl);
1822 return error_mark_node;
1824 /* For function versions, params and types match, but they
1825 are not ambiguous. */
1826 else if ((!DECL_FUNCTION_VERSIONED (newdecl)
1827 && !DECL_FUNCTION_VERSIONED (olddecl))
1828 // The functions have the same parameter types.
1829 && compparms (TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1830 TYPE_ARG_TYPES (TREE_TYPE (olddecl)))
1831 // And the same constraints.
1832 && equivalently_constrained (newdecl, olddecl))
1834 error_at (newdecl_loc,
1835 "ambiguating new declaration of %q#D", newdecl);
1836 inform (olddecl_loc,
1837 "old declaration %q#D", olddecl);
1838 return error_mark_node;
1840 else
1841 return NULL_TREE;
1843 else
1845 error_at (newdecl_loc, "conflicting declaration %q#D", newdecl);
1846 inform (olddecl_loc,
1847 "previous declaration as %q#D", olddecl);
1848 return error_mark_node;
1851 else if (TREE_CODE (newdecl) == FUNCTION_DECL
1852 && DECL_OMP_DECLARE_REDUCTION_P (newdecl))
1854 /* OMP UDRs are never duplicates. */
1855 gcc_assert (DECL_OMP_DECLARE_REDUCTION_P (olddecl));
1856 error_at (newdecl_loc,
1857 "redeclaration of %<pragma omp declare reduction%>");
1858 inform (olddecl_loc,
1859 "previous %<pragma omp declare reduction%> declaration");
1860 return error_mark_node;
1862 else if (TREE_CODE (newdecl) == FUNCTION_DECL
1863 && ((DECL_TEMPLATE_SPECIALIZATION (olddecl)
1864 && (!DECL_TEMPLATE_INFO (newdecl)
1865 || (DECL_TI_TEMPLATE (newdecl)
1866 != DECL_TI_TEMPLATE (olddecl))))
1867 || (DECL_TEMPLATE_SPECIALIZATION (newdecl)
1868 && (!DECL_TEMPLATE_INFO (olddecl)
1869 || (DECL_TI_TEMPLATE (olddecl)
1870 != DECL_TI_TEMPLATE (newdecl))))))
1871 /* It's OK to have a template specialization and a non-template
1872 with the same type, or to have specializations of two
1873 different templates with the same type. Note that if one is a
1874 specialization, and the other is an instantiation of the same
1875 template, that we do not exit at this point. That situation
1876 can occur if we instantiate a template class, and then
1877 specialize one of its methods. This situation is valid, but
1878 the declarations must be merged in the usual way. */
1879 return NULL_TREE;
1880 else if (TREE_CODE (newdecl) == FUNCTION_DECL
1881 && ((DECL_TEMPLATE_INSTANTIATION (olddecl)
1882 && !DECL_USE_TEMPLATE (newdecl))
1883 || (DECL_TEMPLATE_INSTANTIATION (newdecl)
1884 && !DECL_USE_TEMPLATE (olddecl))))
1885 /* One of the declarations is a template instantiation, and the
1886 other is not a template at all. That's OK. */
1887 return NULL_TREE;
1888 else if (TREE_CODE (newdecl) == NAMESPACE_DECL)
1890 /* In [namespace.alias] we have:
1892 In a declarative region, a namespace-alias-definition can be
1893 used to redefine a namespace-alias declared in that declarative
1894 region to refer only to the namespace to which it already
1895 refers.
1897 Therefore, if we encounter a second alias directive for the same
1898 alias, we can just ignore the second directive. */
1899 if (DECL_NAMESPACE_ALIAS (newdecl)
1900 && (DECL_NAMESPACE_ALIAS (newdecl)
1901 == DECL_NAMESPACE_ALIAS (olddecl)))
1902 return olddecl;
1904 /* Leave it to update_binding to merge or report error. */
1905 return NULL_TREE;
1907 else
1909 const char *errmsg = redeclaration_error_message (newdecl, olddecl);
1910 if (errmsg)
1912 auto_diagnostic_group d;
1913 error_at (newdecl_loc, errmsg, newdecl);
1914 if (DECL_NAME (olddecl) != NULL_TREE)
1915 inform (olddecl_loc,
1916 (DECL_INITIAL (olddecl) && namespace_bindings_p ())
1917 ? G_("%q#D previously defined here")
1918 : G_("%q#D previously declared here"), olddecl);
1919 return error_mark_node;
1921 else if (TREE_CODE (olddecl) == FUNCTION_DECL
1922 && DECL_INITIAL (olddecl) != NULL_TREE
1923 && !prototype_p (TREE_TYPE (olddecl))
1924 && prototype_p (TREE_TYPE (newdecl)))
1926 /* Prototype decl follows defn w/o prototype. */
1927 auto_diagnostic_group d;
1928 if (warning_at (newdecl_loc, 0,
1929 "prototype specified for %q#D", newdecl))
1930 inform (olddecl_loc,
1931 "previous non-prototype definition here");
1933 else if (VAR_OR_FUNCTION_DECL_P (olddecl)
1934 && DECL_LANGUAGE (newdecl) != DECL_LANGUAGE (olddecl))
1936 /* [dcl.link]
1937 If two declarations of the same function or object
1938 specify different linkage-specifications ..., the program
1939 is ill-formed.... Except for functions with C++ linkage,
1940 a function declaration without a linkage specification
1941 shall not precede the first linkage specification for
1942 that function. A function can be declared without a
1943 linkage specification after an explicit linkage
1944 specification has been seen; the linkage explicitly
1945 specified in the earlier declaration is not affected by
1946 such a function declaration.
1948 DR 563 raises the question why the restrictions on
1949 functions should not also apply to objects. Older
1950 versions of G++ silently ignore the linkage-specification
1951 for this example:
1953 namespace N {
1954 extern int i;
1955 extern "C" int i;
1958 which is clearly wrong. Therefore, we now treat objects
1959 like functions. */
1960 if (current_lang_depth () == 0)
1962 /* There is no explicit linkage-specification, so we use
1963 the linkage from the previous declaration. */
1964 retrofit_lang_decl (newdecl);
1965 SET_DECL_LANGUAGE (newdecl, DECL_LANGUAGE (olddecl));
1967 else
1969 auto_diagnostic_group d;
1970 error_at (newdecl_loc,
1971 "conflicting declaration of %q#D with %qL linkage",
1972 newdecl, DECL_LANGUAGE (newdecl));
1973 inform (olddecl_loc,
1974 "previous declaration with %qL linkage",
1975 DECL_LANGUAGE (olddecl));
1979 if (DECL_LANG_SPECIFIC (olddecl) && DECL_USE_TEMPLATE (olddecl))
1981 else if (TREE_CODE (olddecl) == FUNCTION_DECL)
1983 /* Note: free functions, as TEMPLATE_DECLs, are handled below. */
1984 if (DECL_FUNCTION_MEMBER_P (olddecl)
1985 && (/* grokfndecl passes member function templates too
1986 as FUNCTION_DECLs. */
1987 DECL_TEMPLATE_INFO (olddecl)
1988 /* C++11 8.3.6/6.
1989 Default arguments for a member function of a class
1990 template shall be specified on the initial declaration
1991 of the member function within the class template. */
1992 || CLASSTYPE_TEMPLATE_INFO (CP_DECL_CONTEXT (olddecl))))
1993 check_redeclaration_no_default_args (newdecl);
1994 else
1996 tree t1 = FUNCTION_FIRST_USER_PARMTYPE (olddecl);
1997 tree t2 = FUNCTION_FIRST_USER_PARMTYPE (newdecl);
1998 int i = 1;
2000 for (; t1 && t1 != void_list_node;
2001 t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2), i++)
2002 if (TREE_PURPOSE (t1) && TREE_PURPOSE (t2))
2004 if (simple_cst_equal (TREE_PURPOSE (t1),
2005 TREE_PURPOSE (t2)) == 1)
2007 auto_diagnostic_group d;
2008 if (permerror (newdecl_loc,
2009 "default argument given for parameter "
2010 "%d of %q#D", i, newdecl))
2011 inform (olddecl_loc,
2012 "previous specification in %q#D here",
2013 olddecl);
2015 else
2017 auto_diagnostic_group d;
2018 error_at (newdecl_loc,
2019 "default argument given for parameter %d "
2020 "of %q#D", i, newdecl);
2021 inform (olddecl_loc,
2022 "previous specification in %q#D here",
2023 olddecl);
2027 /* C++17 11.3.6/4: "If a friend declaration specifies a default
2028 argument expression, that declaration... shall be the only
2029 declaration of the function or function template in the
2030 translation unit." */
2031 check_no_redeclaration_friend_default_args (olddecl, newdecl);
2036 /* Do not merge an implicit typedef with an explicit one. In:
2038 class A;
2040 typedef class A A __attribute__ ((foo));
2042 the attribute should apply only to the typedef. */
2043 if (TREE_CODE (olddecl) == TYPE_DECL
2044 && (DECL_IMPLICIT_TYPEDEF_P (olddecl)
2045 || DECL_IMPLICIT_TYPEDEF_P (newdecl)))
2046 return NULL_TREE;
2048 if (DECL_TEMPLATE_PARM_P (olddecl) != DECL_TEMPLATE_PARM_P (newdecl))
2049 return NULL_TREE;
2051 if (!validate_constexpr_redeclaration (olddecl, newdecl))
2052 return error_mark_node;
2054 if (modules_p ()
2055 && TREE_CODE (CP_DECL_CONTEXT (olddecl)) == NAMESPACE_DECL
2056 && TREE_CODE (olddecl) != NAMESPACE_DECL
2057 && !hiding)
2059 if (DECL_ARTIFICIAL (olddecl))
2061 if (!(global_purview_p () || not_module_p ()))
2062 error ("declaration %qD conflicts with builtin", newdecl);
2063 else
2064 DECL_MODULE_EXPORT_P (olddecl) = DECL_MODULE_EXPORT_P (newdecl);
2066 else
2068 if (!module_may_redeclare (olddecl))
2070 error ("declaration %qD conflicts with import", newdecl);
2071 inform (olddecl_loc, "import declared %q#D here", olddecl);
2073 return error_mark_node;
2076 if (DECL_MODULE_EXPORT_P (newdecl)
2077 && !DECL_MODULE_EXPORT_P (olddecl))
2079 error ("conflicting exporting declaration %qD", newdecl);
2080 inform (olddecl_loc, "previous declaration %q#D here", olddecl);
2085 /* We have committed to returning OLDDECL at this point. */
2087 /* If new decl is `static' and an `extern' was seen previously,
2088 warn about it. */
2089 warn_extern_redeclared_static (newdecl, olddecl);
2091 /* True to merge attributes between the declarations, false to
2092 set OLDDECL's attributes to those of NEWDECL (for template
2093 explicit specializations that specify their own attributes
2094 independent of those specified for the primary template). */
2095 const bool merge_attr = (TREE_CODE (newdecl) != FUNCTION_DECL
2096 || !DECL_TEMPLATE_SPECIALIZATION (newdecl)
2097 || DECL_TEMPLATE_SPECIALIZATION (olddecl));
2099 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2101 if (merge_attr)
2103 if (diagnose_mismatched_attributes (olddecl, newdecl))
2104 inform (olddecl_loc, DECL_INITIAL (olddecl)
2105 ? G_("previous definition of %qD here")
2106 : G_("previous declaration of %qD here"), olddecl);
2108 /* [dcl.attr.noreturn]: The first declaration of a function shall
2109 specify the noreturn attribute if any declaration of that function
2110 specifies the noreturn attribute. */
2111 tree a;
2112 if (TREE_THIS_VOLATILE (newdecl)
2113 && !TREE_THIS_VOLATILE (olddecl)
2114 /* This applies to [[noreturn]] only, not its GNU variants. */
2115 && (a = lookup_attribute ("noreturn", DECL_ATTRIBUTES (newdecl)))
2116 && cxx11_attribute_p (a)
2117 && get_attribute_namespace (a) == NULL_TREE)
2119 error_at (newdecl_loc, "function %qD declared %<[[noreturn]]%> "
2120 "but its first declaration was not", newdecl);
2121 inform (olddecl_loc, "previous declaration of %qD", olddecl);
2125 /* Now that functions must hold information normally held
2126 by field decls, there is extra work to do so that
2127 declaration information does not get destroyed during
2128 definition. */
2129 if (DECL_VINDEX (olddecl))
2130 DECL_VINDEX (newdecl) = DECL_VINDEX (olddecl);
2131 if (DECL_CONTEXT (olddecl))
2132 DECL_CONTEXT (newdecl) = DECL_CONTEXT (olddecl);
2133 DECL_STATIC_CONSTRUCTOR (newdecl) |= DECL_STATIC_CONSTRUCTOR (olddecl);
2134 DECL_STATIC_DESTRUCTOR (newdecl) |= DECL_STATIC_DESTRUCTOR (olddecl);
2135 DECL_PURE_VIRTUAL_P (newdecl) |= DECL_PURE_VIRTUAL_P (olddecl);
2136 DECL_VIRTUAL_P (newdecl) |= DECL_VIRTUAL_P (olddecl);
2137 DECL_INVALID_OVERRIDER_P (newdecl) |= DECL_INVALID_OVERRIDER_P (olddecl);
2138 DECL_FINAL_P (newdecl) |= DECL_FINAL_P (olddecl);
2139 DECL_OVERRIDE_P (newdecl) |= DECL_OVERRIDE_P (olddecl);
2140 DECL_THIS_STATIC (newdecl) |= DECL_THIS_STATIC (olddecl);
2141 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (newdecl)
2142 |= DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (olddecl);
2143 if (DECL_OVERLOADED_OPERATOR_P (olddecl))
2144 DECL_OVERLOADED_OPERATOR_CODE_RAW (newdecl)
2145 = DECL_OVERLOADED_OPERATOR_CODE_RAW (olddecl);
2146 new_defines_function = DECL_INITIAL (newdecl) != NULL_TREE;
2148 /* Optionally warn about more than one declaration for the same
2149 name, but don't warn about a function declaration followed by a
2150 definition. */
2151 if (warn_redundant_decls && ! DECL_ARTIFICIAL (olddecl)
2152 && !(new_defines_function && DECL_INITIAL (olddecl) == NULL_TREE)
2153 /* Don't warn about extern decl followed by definition. */
2154 && !(DECL_EXTERNAL (olddecl) && ! DECL_EXTERNAL (newdecl))
2155 /* Don't warn if at least one is/was hidden. */
2156 && !(hiding || was_hidden)
2157 /* Don't warn about declaration followed by specialization. */
2158 && (! DECL_TEMPLATE_SPECIALIZATION (newdecl)
2159 || DECL_TEMPLATE_SPECIALIZATION (olddecl)))
2161 auto_diagnostic_group d;
2162 if (warning_at (newdecl_loc,
2163 OPT_Wredundant_decls,
2164 "redundant redeclaration of %qD in same scope",
2165 newdecl))
2166 inform (olddecl_loc,
2167 "previous declaration of %qD", olddecl);
2170 /* [dcl.fct.def.delete] A deleted definition of a function shall be the
2171 first declaration of the function or, for an explicit specialization
2172 of a function template, the first declaration of that
2173 specialization. */
2174 if (!(DECL_TEMPLATE_INSTANTIATION (olddecl)
2175 && DECL_TEMPLATE_SPECIALIZATION (newdecl)))
2177 if (DECL_DELETED_FN (newdecl))
2179 auto_diagnostic_group d;
2180 if (pedwarn (newdecl_loc, 0, "deleted definition of %qD "
2181 "is not first declaration", newdecl))
2182 inform (olddecl_loc,
2183 "previous declaration of %qD", olddecl);
2185 DECL_DELETED_FN (newdecl) |= DECL_DELETED_FN (olddecl);
2189 /* Deal with C++: must preserve virtual function table size. */
2190 if (TREE_CODE (olddecl) == TYPE_DECL)
2192 tree newtype = TREE_TYPE (newdecl);
2193 tree oldtype = TREE_TYPE (olddecl);
2195 if (newtype != error_mark_node && oldtype != error_mark_node
2196 && TYPE_LANG_SPECIFIC (newtype) && TYPE_LANG_SPECIFIC (oldtype))
2197 CLASSTYPE_FRIEND_CLASSES (newtype)
2198 = CLASSTYPE_FRIEND_CLASSES (oldtype);
2200 DECL_ORIGINAL_TYPE (newdecl) = DECL_ORIGINAL_TYPE (olddecl);
2203 /* Copy all the DECL_... slots specified in the new decl except for
2204 any that we copy here from the old type. */
2205 if (merge_attr)
2206 DECL_ATTRIBUTES (newdecl)
2207 = (*targetm.merge_decl_attributes) (olddecl, newdecl);
2208 else
2209 DECL_ATTRIBUTES (olddecl) = DECL_ATTRIBUTES (newdecl);
2211 if (TREE_CODE (newdecl) == TEMPLATE_DECL)
2213 tree old_result = DECL_TEMPLATE_RESULT (olddecl);
2214 tree new_result = DECL_TEMPLATE_RESULT (newdecl);
2215 TREE_TYPE (olddecl) = TREE_TYPE (old_result);
2217 /* The new decl should not already have gathered any
2218 specializations. */
2219 gcc_assert (!DECL_TEMPLATE_SPECIALIZATIONS (newdecl));
2221 DECL_ATTRIBUTES (old_result)
2222 = (*targetm.merge_decl_attributes) (old_result, new_result);
2224 if (DECL_FUNCTION_TEMPLATE_P (newdecl))
2226 if (DECL_SOURCE_LOCATION (newdecl)
2227 != DECL_SOURCE_LOCATION (olddecl))
2229 /* Per C++11 8.3.6/4, default arguments cannot be added in
2230 later declarations of a function template. */
2231 check_redeclaration_no_default_args (newdecl);
2232 /* C++17 11.3.6/4: "If a friend declaration specifies a default
2233 argument expression, that declaration... shall be the only
2234 declaration of the function or function template in the
2235 translation unit." */
2236 check_no_redeclaration_friend_default_args
2237 (old_result, new_result);
2239 if (!DECL_UNIQUE_FRIEND_P (old_result))
2240 DECL_UNIQUE_FRIEND_P (new_result) = false;
2242 check_default_args (newdecl);
2244 if (GNU_INLINE_P (old_result) != GNU_INLINE_P (new_result)
2245 && DECL_INITIAL (new_result))
2247 if (DECL_INITIAL (old_result))
2248 DECL_UNINLINABLE (old_result) = 1;
2249 else
2250 DECL_UNINLINABLE (old_result) = DECL_UNINLINABLE (new_result);
2251 DECL_EXTERNAL (old_result) = DECL_EXTERNAL (new_result);
2252 DECL_NOT_REALLY_EXTERN (old_result)
2253 = DECL_NOT_REALLY_EXTERN (new_result);
2254 DECL_INTERFACE_KNOWN (old_result)
2255 = DECL_INTERFACE_KNOWN (new_result);
2256 DECL_DECLARED_INLINE_P (old_result)
2257 = DECL_DECLARED_INLINE_P (new_result);
2258 DECL_DISREGARD_INLINE_LIMITS (old_result)
2259 |= DECL_DISREGARD_INLINE_LIMITS (new_result);
2262 else
2264 DECL_DECLARED_INLINE_P (old_result)
2265 |= DECL_DECLARED_INLINE_P (new_result);
2266 DECL_DISREGARD_INLINE_LIMITS (old_result)
2267 |= DECL_DISREGARD_INLINE_LIMITS (new_result);
2268 check_redeclaration_exception_specification (newdecl, olddecl);
2270 merge_attribute_bits (new_result, old_result);
2274 /* If the new declaration is a definition, update the file and
2275 line information on the declaration, and also make
2276 the old declaration the same definition. */
2277 if (DECL_INITIAL (new_result) != NULL_TREE)
2279 DECL_SOURCE_LOCATION (olddecl)
2280 = DECL_SOURCE_LOCATION (old_result)
2281 = DECL_SOURCE_LOCATION (newdecl);
2282 DECL_INITIAL (old_result) = DECL_INITIAL (new_result);
2283 if (DECL_FUNCTION_TEMPLATE_P (newdecl))
2285 tree parm;
2286 DECL_ARGUMENTS (old_result)
2287 = DECL_ARGUMENTS (new_result);
2288 for (parm = DECL_ARGUMENTS (old_result); parm;
2289 parm = DECL_CHAIN (parm))
2290 DECL_CONTEXT (parm) = old_result;
2294 return olddecl;
2297 if (types_match)
2299 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2300 check_redeclaration_exception_specification (newdecl, olddecl);
2302 /* Automatically handles default parameters. */
2303 tree oldtype = TREE_TYPE (olddecl);
2304 tree newtype;
2306 /* For typedefs use the old type, as the new type's DECL_NAME points
2307 at newdecl, which will be ggc_freed. */
2308 if (TREE_CODE (newdecl) == TYPE_DECL)
2310 /* But NEWTYPE might have an attribute, honor that. */
2311 tree tem = TREE_TYPE (newdecl);
2312 newtype = oldtype;
2314 if (TYPE_USER_ALIGN (tem))
2316 if (TYPE_ALIGN (tem) > TYPE_ALIGN (newtype))
2317 SET_TYPE_ALIGN (newtype, TYPE_ALIGN (tem));
2318 TYPE_USER_ALIGN (newtype) = true;
2321 /* And remove the new type from the variants list. */
2322 if (TYPE_NAME (TREE_TYPE (newdecl)) == newdecl)
2324 tree remove = TREE_TYPE (newdecl);
2325 if (TYPE_MAIN_VARIANT (remove) == remove)
2327 gcc_assert (TYPE_NEXT_VARIANT (remove) == NULL_TREE);
2328 /* If remove is the main variant, no need to remove that
2329 from the list. One of the DECL_ORIGINAL_TYPE
2330 variants, e.g. created for aligned attribute, might still
2331 refer to the newdecl TYPE_DECL though, so remove that one
2332 in that case. */
2333 if (tree orig = DECL_ORIGINAL_TYPE (newdecl))
2334 if (orig != remove)
2335 for (tree t = TYPE_MAIN_VARIANT (orig); t;
2336 t = TYPE_MAIN_VARIANT (t))
2337 if (TYPE_NAME (TYPE_NEXT_VARIANT (t)) == newdecl)
2339 TYPE_NEXT_VARIANT (t)
2340 = TYPE_NEXT_VARIANT (TYPE_NEXT_VARIANT (t));
2341 break;
2344 else
2345 for (tree t = TYPE_MAIN_VARIANT (remove); ;
2346 t = TYPE_NEXT_VARIANT (t))
2347 if (TYPE_NEXT_VARIANT (t) == remove)
2349 TYPE_NEXT_VARIANT (t) = TYPE_NEXT_VARIANT (remove);
2350 break;
2354 else if (merge_attr)
2355 newtype = merge_types (TREE_TYPE (newdecl), TREE_TYPE (olddecl));
2356 else
2357 newtype = TREE_TYPE (newdecl);
2359 if (VAR_P (newdecl))
2361 DECL_THIS_EXTERN (newdecl) |= DECL_THIS_EXTERN (olddecl);
2362 /* For already initialized vars, TREE_READONLY could have been
2363 cleared in cp_finish_decl, because the var needs runtime
2364 initialization or destruction. Make sure not to set
2365 TREE_READONLY on it again. */
2366 if (DECL_INITIALIZED_P (olddecl)
2367 && !DECL_EXTERNAL (olddecl)
2368 && !TREE_READONLY (olddecl))
2369 TREE_READONLY (newdecl) = 0;
2370 DECL_INITIALIZED_P (newdecl) |= DECL_INITIALIZED_P (olddecl);
2371 DECL_NONTRIVIALLY_INITIALIZED_P (newdecl)
2372 |= DECL_NONTRIVIALLY_INITIALIZED_P (olddecl);
2373 if (DECL_DEPENDENT_INIT_P (olddecl))
2374 SET_DECL_DEPENDENT_INIT_P (newdecl, true);
2375 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (newdecl)
2376 |= DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (olddecl);
2377 DECL_DECLARED_CONSTEXPR_P (newdecl)
2378 |= DECL_DECLARED_CONSTEXPR_P (olddecl);
2379 DECL_DECLARED_CONSTINIT_P (newdecl)
2380 |= DECL_DECLARED_CONSTINIT_P (olddecl);
2382 /* Merge the threadprivate attribute from OLDDECL into NEWDECL. */
2383 if (DECL_LANG_SPECIFIC (olddecl)
2384 && CP_DECL_THREADPRIVATE_P (olddecl))
2386 /* Allocate a LANG_SPECIFIC structure for NEWDECL, if needed. */
2387 retrofit_lang_decl (newdecl);
2388 CP_DECL_THREADPRIVATE_P (newdecl) = 1;
2392 /* An explicit specialization of a function template or of a member
2393 function of a class template can be declared transaction_safe
2394 independently of whether the corresponding template entity is declared
2395 transaction_safe. */
2396 if (flag_tm && TREE_CODE (newdecl) == FUNCTION_DECL
2397 && DECL_TEMPLATE_INSTANTIATION (olddecl)
2398 && DECL_TEMPLATE_SPECIALIZATION (newdecl)
2399 && tx_safe_fn_type_p (newtype)
2400 && !tx_safe_fn_type_p (TREE_TYPE (newdecl)))
2401 newtype = tx_unsafe_fn_variant (newtype);
2403 TREE_TYPE (newdecl) = TREE_TYPE (olddecl) = newtype;
2405 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2406 check_default_args (newdecl);
2408 /* Lay the type out, unless already done. */
2409 if (! same_type_p (newtype, oldtype)
2410 && TREE_TYPE (newdecl) != error_mark_node
2411 && !(processing_template_decl && uses_template_parms (newdecl)))
2412 layout_type (TREE_TYPE (newdecl));
2414 if ((VAR_P (newdecl)
2415 || TREE_CODE (newdecl) == PARM_DECL
2416 || TREE_CODE (newdecl) == RESULT_DECL
2417 || TREE_CODE (newdecl) == FIELD_DECL
2418 || TREE_CODE (newdecl) == TYPE_DECL)
2419 && !(processing_template_decl && uses_template_parms (newdecl)))
2420 layout_decl (newdecl, 0);
2422 /* Merge deprecatedness. */
2423 if (TREE_DEPRECATED (newdecl))
2424 TREE_DEPRECATED (olddecl) = 1;
2426 /* Merge unavailability. */
2427 if (TREE_UNAVAILABLE (newdecl))
2428 TREE_UNAVAILABLE (olddecl) = 1;
2430 /* Preserve function specific target and optimization options */
2431 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2433 if (DECL_FUNCTION_SPECIFIC_TARGET (olddecl)
2434 && !DECL_FUNCTION_SPECIFIC_TARGET (newdecl))
2435 DECL_FUNCTION_SPECIFIC_TARGET (newdecl)
2436 = DECL_FUNCTION_SPECIFIC_TARGET (olddecl);
2438 if (DECL_FUNCTION_SPECIFIC_OPTIMIZATION (olddecl)
2439 && !DECL_FUNCTION_SPECIFIC_OPTIMIZATION (newdecl))
2440 DECL_FUNCTION_SPECIFIC_OPTIMIZATION (newdecl)
2441 = DECL_FUNCTION_SPECIFIC_OPTIMIZATION (olddecl);
2443 if (!DECL_UNIQUE_FRIEND_P (olddecl))
2444 DECL_UNIQUE_FRIEND_P (newdecl) = false;
2446 else
2448 /* Merge the const type qualifier. */
2449 if (TREE_READONLY (newdecl))
2450 TREE_READONLY (olddecl) = 1;
2451 /* Merge the volatile type qualifier. */
2452 if (TREE_THIS_VOLATILE (newdecl))
2453 TREE_THIS_VOLATILE (olddecl) = 1;
2456 /* Merge the initialization information. */
2457 if (DECL_INITIAL (newdecl) == NULL_TREE
2458 && DECL_INITIAL (olddecl) != NULL_TREE)
2460 DECL_INITIAL (newdecl) = DECL_INITIAL (olddecl);
2461 DECL_SOURCE_LOCATION (newdecl) = DECL_SOURCE_LOCATION (olddecl);
2462 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2464 DECL_SAVED_TREE (newdecl) = DECL_SAVED_TREE (olddecl);
2465 DECL_STRUCT_FUNCTION (newdecl) = DECL_STRUCT_FUNCTION (olddecl);
2469 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2471 DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (newdecl)
2472 |= DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (olddecl);
2473 DECL_NO_LIMIT_STACK (newdecl) |= DECL_NO_LIMIT_STACK (olddecl);
2474 if (DECL_IS_OPERATOR_NEW_P (olddecl))
2475 DECL_SET_IS_OPERATOR_NEW (newdecl, true);
2476 DECL_LOOPING_CONST_OR_PURE_P (newdecl)
2477 |= DECL_LOOPING_CONST_OR_PURE_P (olddecl);
2478 DECL_IS_REPLACEABLE_OPERATOR (newdecl)
2479 |= DECL_IS_REPLACEABLE_OPERATOR (olddecl);
2481 if (merge_attr)
2482 merge_attribute_bits (newdecl, olddecl);
2483 else
2485 /* Merge the noreturn bit. */
2486 TREE_THIS_VOLATILE (olddecl) = TREE_THIS_VOLATILE (newdecl);
2487 TREE_READONLY (olddecl) = TREE_READONLY (newdecl);
2488 TREE_NOTHROW (olddecl) = TREE_NOTHROW (newdecl);
2489 DECL_IS_MALLOC (olddecl) = DECL_IS_MALLOC (newdecl);
2490 DECL_PURE_P (olddecl) = DECL_PURE_P (newdecl);
2492 /* Keep the old RTL. */
2493 COPY_DECL_RTL (olddecl, newdecl);
2495 else if (VAR_P (newdecl)
2496 && (DECL_SIZE (olddecl) || !DECL_SIZE (newdecl)))
2498 /* Keep the old RTL. We cannot keep the old RTL if the old
2499 declaration was for an incomplete object and the new
2500 declaration is not since many attributes of the RTL will
2501 change. */
2502 COPY_DECL_RTL (olddecl, newdecl);
2505 /* If cannot merge, then use the new type and qualifiers,
2506 and don't preserve the old rtl. */
2507 else
2509 /* Clean out any memory we had of the old declaration. */
2510 tree oldstatic = value_member (olddecl, static_aggregates);
2511 if (oldstatic)
2512 TREE_VALUE (oldstatic) = error_mark_node;
2514 TREE_TYPE (olddecl) = TREE_TYPE (newdecl);
2515 TREE_READONLY (olddecl) = TREE_READONLY (newdecl);
2516 TREE_THIS_VOLATILE (olddecl) = TREE_THIS_VOLATILE (newdecl);
2517 TREE_NOTHROW (olddecl) = TREE_NOTHROW (newdecl);
2518 TREE_SIDE_EFFECTS (olddecl) = TREE_SIDE_EFFECTS (newdecl);
2521 /* Merge the storage class information. */
2522 merge_weak (newdecl, olddecl);
2524 DECL_DEFER_OUTPUT (newdecl) |= DECL_DEFER_OUTPUT (olddecl);
2525 TREE_PUBLIC (newdecl) = TREE_PUBLIC (olddecl);
2526 TREE_STATIC (olddecl) = TREE_STATIC (newdecl) |= TREE_STATIC (olddecl);
2527 if (! DECL_EXTERNAL (olddecl))
2528 DECL_EXTERNAL (newdecl) = 0;
2529 if (! DECL_COMDAT (olddecl))
2530 DECL_COMDAT (newdecl) = 0;
2532 if (VAR_OR_FUNCTION_DECL_P (newdecl) && DECL_LOCAL_DECL_P (newdecl))
2534 if (!DECL_LOCAL_DECL_P (olddecl))
2535 /* This can happen if olddecl was brought in from the
2536 enclosing namespace via a using-decl. The new decl is
2537 then not a block-scope extern at all. */
2538 DECL_LOCAL_DECL_P (newdecl) = false;
2539 else
2541 retrofit_lang_decl (newdecl);
2542 DECL_LOCAL_DECL_ALIAS (newdecl) = DECL_LOCAL_DECL_ALIAS (olddecl);
2546 new_template_info = NULL_TREE;
2547 if (DECL_LANG_SPECIFIC (newdecl) && DECL_LANG_SPECIFIC (olddecl))
2549 bool new_redefines_gnu_inline = false;
2551 if (new_defines_function
2552 && ((DECL_INTERFACE_KNOWN (olddecl)
2553 && TREE_CODE (olddecl) == FUNCTION_DECL)
2554 || (TREE_CODE (olddecl) == TEMPLATE_DECL
2555 && (TREE_CODE (DECL_TEMPLATE_RESULT (olddecl))
2556 == FUNCTION_DECL))))
2557 new_redefines_gnu_inline = GNU_INLINE_P (STRIP_TEMPLATE (olddecl));
2559 if (!new_redefines_gnu_inline)
2561 DECL_INTERFACE_KNOWN (newdecl) |= DECL_INTERFACE_KNOWN (olddecl);
2562 DECL_NOT_REALLY_EXTERN (newdecl) |= DECL_NOT_REALLY_EXTERN (olddecl);
2563 DECL_COMDAT (newdecl) |= DECL_COMDAT (olddecl);
2566 if (TREE_CODE (newdecl) != TYPE_DECL)
2568 DECL_TEMPLATE_INSTANTIATED (newdecl)
2569 |= DECL_TEMPLATE_INSTANTIATED (olddecl);
2570 DECL_ODR_USED (newdecl) |= DECL_ODR_USED (olddecl);
2572 /* If the OLDDECL is an instantiation and/or specialization,
2573 then the NEWDECL must be too. But, it may not yet be marked
2574 as such if the caller has created NEWDECL, but has not yet
2575 figured out that it is a redeclaration. */
2576 if (!DECL_USE_TEMPLATE (newdecl))
2577 DECL_USE_TEMPLATE (newdecl) = DECL_USE_TEMPLATE (olddecl);
2579 if (!DECL_TEMPLATE_SPECIALIZATION (newdecl))
2580 DECL_INITIALIZED_IN_CLASS_P (newdecl)
2581 |= DECL_INITIALIZED_IN_CLASS_P (olddecl);
2584 /* Don't really know how much of the language-specific
2585 values we should copy from old to new. */
2586 DECL_IN_AGGR_P (newdecl) = DECL_IN_AGGR_P (olddecl);
2588 if (LANG_DECL_HAS_MIN (newdecl))
2590 DECL_ACCESS (newdecl) = DECL_ACCESS (olddecl);
2591 if (DECL_TEMPLATE_INFO (newdecl))
2593 new_template_info = DECL_TEMPLATE_INFO (newdecl);
2594 if (DECL_TEMPLATE_INSTANTIATION (olddecl)
2595 && DECL_TEMPLATE_SPECIALIZATION (newdecl))
2596 /* Remember the presence of explicit specialization args. */
2597 TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (olddecl))
2598 = TINFO_USED_TEMPLATE_ID (new_template_info);
2600 DECL_TEMPLATE_INFO (newdecl) = DECL_TEMPLATE_INFO (olddecl);
2603 if (DECL_DECLARES_FUNCTION_P (newdecl))
2605 /* Only functions have these fields. */
2606 DECL_NONCONVERTING_P (newdecl) = DECL_NONCONVERTING_P (olddecl);
2607 DECL_BEFRIENDING_CLASSES (newdecl)
2608 = chainon (DECL_BEFRIENDING_CLASSES (newdecl),
2609 DECL_BEFRIENDING_CLASSES (olddecl));
2610 /* DECL_THUNKS is only valid for virtual functions,
2611 otherwise it is a DECL_FRIEND_CONTEXT. */
2612 if (DECL_VIRTUAL_P (newdecl))
2613 SET_DECL_THUNKS (newdecl, DECL_THUNKS (olddecl));
2615 else if (VAR_P (newdecl))
2617 /* Only variables have this field. */
2618 if (VAR_HAD_UNKNOWN_BOUND (olddecl))
2619 SET_VAR_HAD_UNKNOWN_BOUND (newdecl);
2623 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2625 tree parm;
2627 /* Merge parameter attributes. */
2628 tree oldarg, newarg;
2629 for (oldarg = DECL_ARGUMENTS(olddecl), newarg = DECL_ARGUMENTS(newdecl);
2630 oldarg && newarg;
2631 oldarg = DECL_CHAIN(oldarg), newarg = DECL_CHAIN(newarg))
2633 DECL_ATTRIBUTES (newarg)
2634 = (*targetm.merge_decl_attributes) (oldarg, newarg);
2635 DECL_ATTRIBUTES (oldarg) = DECL_ATTRIBUTES (newarg);
2638 if (DECL_TEMPLATE_INSTANTIATION (olddecl)
2639 && !DECL_TEMPLATE_INSTANTIATION (newdecl))
2641 /* If newdecl is not a specialization, then it is not a
2642 template-related function at all. And that means that we
2643 should have exited above, returning 0. */
2644 gcc_assert (DECL_TEMPLATE_SPECIALIZATION (newdecl));
2646 if (DECL_ODR_USED (olddecl))
2647 /* From [temp.expl.spec]:
2649 If a template, a member template or the member of a class
2650 template is explicitly specialized then that
2651 specialization shall be declared before the first use of
2652 that specialization that would cause an implicit
2653 instantiation to take place, in every translation unit in
2654 which such a use occurs. */
2655 error ("explicit specialization of %qD after first use",
2656 olddecl);
2658 SET_DECL_TEMPLATE_SPECIALIZATION (olddecl);
2659 DECL_COMDAT (newdecl) = (TREE_PUBLIC (newdecl)
2660 && DECL_DECLARED_INLINE_P (newdecl));
2662 /* Don't propagate visibility from the template to the
2663 specialization here. We'll do that in determine_visibility if
2664 appropriate. */
2665 DECL_VISIBILITY_SPECIFIED (olddecl) = 0;
2667 /* [temp.expl.spec/14] We don't inline explicit specialization
2668 just because the primary template says so. */
2669 gcc_assert (!merge_attr);
2671 DECL_DECLARED_INLINE_P (olddecl)
2672 = DECL_DECLARED_INLINE_P (newdecl);
2674 DECL_DISREGARD_INLINE_LIMITS (olddecl)
2675 = DECL_DISREGARD_INLINE_LIMITS (newdecl);
2677 DECL_UNINLINABLE (olddecl) = DECL_UNINLINABLE (newdecl);
2679 else if (new_defines_function && DECL_INITIAL (olddecl))
2681 /* Never inline re-defined extern inline functions.
2682 FIXME: this could be better handled by keeping both
2683 function as separate declarations. */
2684 DECL_UNINLINABLE (newdecl) = 1;
2686 else
2688 if (DECL_PENDING_INLINE_P (olddecl))
2690 DECL_PENDING_INLINE_P (newdecl) = 1;
2691 DECL_PENDING_INLINE_INFO (newdecl)
2692 = DECL_PENDING_INLINE_INFO (olddecl);
2694 else if (DECL_PENDING_INLINE_P (newdecl))
2696 else if (DECL_SAVED_AUTO_RETURN_TYPE (newdecl) == NULL)
2697 DECL_SAVED_AUTO_RETURN_TYPE (newdecl)
2698 = DECL_SAVED_AUTO_RETURN_TYPE (olddecl);
2700 DECL_DECLARED_INLINE_P (newdecl) |= DECL_DECLARED_INLINE_P (olddecl);
2702 DECL_UNINLINABLE (newdecl) = DECL_UNINLINABLE (olddecl)
2703 = (DECL_UNINLINABLE (newdecl) || DECL_UNINLINABLE (olddecl));
2705 DECL_DISREGARD_INLINE_LIMITS (newdecl)
2706 = DECL_DISREGARD_INLINE_LIMITS (olddecl)
2707 = (DECL_DISREGARD_INLINE_LIMITS (newdecl)
2708 || DECL_DISREGARD_INLINE_LIMITS (olddecl));
2711 /* Preserve abstractness on cloned [cd]tors. */
2712 DECL_ABSTRACT_P (newdecl) = DECL_ABSTRACT_P (olddecl);
2714 /* Update newdecl's parms to point at olddecl. */
2715 for (parm = DECL_ARGUMENTS (newdecl); parm;
2716 parm = DECL_CHAIN (parm))
2717 DECL_CONTEXT (parm) = olddecl;
2719 if (! types_match)
2721 SET_DECL_LANGUAGE (olddecl, DECL_LANGUAGE (newdecl));
2722 COPY_DECL_ASSEMBLER_NAME (newdecl, olddecl);
2723 COPY_DECL_RTL (newdecl, olddecl);
2725 if (! types_match || new_defines_function)
2727 /* These need to be copied so that the names are available.
2728 Note that if the types do match, we'll preserve inline
2729 info and other bits, but if not, we won't. */
2730 DECL_ARGUMENTS (olddecl) = DECL_ARGUMENTS (newdecl);
2731 DECL_RESULT (olddecl) = DECL_RESULT (newdecl);
2733 /* If redeclaring a builtin function, it stays built in
2734 if newdecl is a gnu_inline definition, or if newdecl is just
2735 a declaration. */
2736 if (fndecl_built_in_p (olddecl)
2737 && (new_defines_function ? GNU_INLINE_P (newdecl) : types_match))
2739 copy_decl_built_in_function (newdecl, olddecl);
2740 /* If we're keeping the built-in definition, keep the rtl,
2741 regardless of declaration matches. */
2742 COPY_DECL_RTL (olddecl, newdecl);
2743 if (DECL_BUILT_IN_CLASS (newdecl) == BUILT_IN_NORMAL)
2745 enum built_in_function fncode = DECL_FUNCTION_CODE (newdecl);
2746 if (builtin_decl_explicit_p (fncode))
2748 /* A compatible prototype of these builtin functions
2749 is seen, assume the runtime implements it with
2750 the expected semantics. */
2751 switch (fncode)
2753 case BUILT_IN_STPCPY:
2754 set_builtin_decl_implicit_p (fncode, true);
2755 break;
2756 default:
2757 set_builtin_decl_declared_p (fncode, true);
2758 break;
2762 copy_attributes_to_builtin (newdecl);
2765 if (new_defines_function)
2766 /* If defining a function declared with other language
2767 linkage, use the previously declared language linkage. */
2768 SET_DECL_LANGUAGE (newdecl, DECL_LANGUAGE (olddecl));
2769 else if (types_match)
2771 DECL_RESULT (newdecl) = DECL_RESULT (olddecl);
2772 /* Don't clear out the arguments if we're just redeclaring a
2773 function. */
2774 if (DECL_ARGUMENTS (olddecl))
2775 DECL_ARGUMENTS (newdecl) = DECL_ARGUMENTS (olddecl);
2778 else if (TREE_CODE (newdecl) == NAMESPACE_DECL)
2779 NAMESPACE_LEVEL (newdecl) = NAMESPACE_LEVEL (olddecl);
2781 /* Now preserve various other info from the definition. */
2782 TREE_ADDRESSABLE (newdecl) = TREE_ADDRESSABLE (olddecl);
2783 TREE_ASM_WRITTEN (newdecl) = TREE_ASM_WRITTEN (olddecl);
2784 DECL_COMMON (newdecl) = DECL_COMMON (olddecl);
2785 COPY_DECL_ASSEMBLER_NAME (olddecl, newdecl);
2787 /* Warn about conflicting visibility specifications. */
2788 if (DECL_VISIBILITY_SPECIFIED (olddecl)
2789 && DECL_VISIBILITY_SPECIFIED (newdecl)
2790 && DECL_VISIBILITY (newdecl) != DECL_VISIBILITY (olddecl))
2792 auto_diagnostic_group d;
2793 if (warning_at (newdecl_loc, OPT_Wattributes,
2794 "%qD: visibility attribute ignored because it "
2795 "conflicts with previous declaration", newdecl))
2796 inform (olddecl_loc,
2797 "previous declaration of %qD", olddecl);
2799 /* Choose the declaration which specified visibility. */
2800 if (DECL_VISIBILITY_SPECIFIED (olddecl))
2802 DECL_VISIBILITY (newdecl) = DECL_VISIBILITY (olddecl);
2803 DECL_VISIBILITY_SPECIFIED (newdecl) = 1;
2805 /* Init priority used to be merged from newdecl to olddecl by the memcpy,
2806 so keep this behavior. */
2807 if (VAR_P (newdecl) && DECL_HAS_INIT_PRIORITY_P (newdecl))
2809 SET_DECL_INIT_PRIORITY (olddecl, DECL_INIT_PRIORITY (newdecl));
2810 DECL_HAS_INIT_PRIORITY_P (olddecl) = 1;
2812 /* Likewise for DECL_ALIGN, DECL_USER_ALIGN and DECL_PACKED. */
2813 if (DECL_ALIGN (olddecl) > DECL_ALIGN (newdecl))
2815 SET_DECL_ALIGN (newdecl, DECL_ALIGN (olddecl));
2816 DECL_USER_ALIGN (newdecl) |= DECL_USER_ALIGN (olddecl);
2818 else if (DECL_ALIGN (olddecl) == DECL_ALIGN (newdecl)
2819 && DECL_USER_ALIGN (olddecl) != DECL_USER_ALIGN (newdecl))
2820 DECL_USER_ALIGN (newdecl) = 1;
2822 DECL_USER_ALIGN (olddecl) = DECL_USER_ALIGN (newdecl);
2823 if (DECL_WARN_IF_NOT_ALIGN (olddecl)
2824 > DECL_WARN_IF_NOT_ALIGN (newdecl))
2825 SET_DECL_WARN_IF_NOT_ALIGN (newdecl,
2826 DECL_WARN_IF_NOT_ALIGN (olddecl));
2827 if (TREE_CODE (newdecl) == FIELD_DECL)
2828 DECL_PACKED (olddecl) = DECL_PACKED (newdecl);
2830 /* The DECL_LANG_SPECIFIC information in OLDDECL will be replaced
2831 with that from NEWDECL below. */
2832 if (DECL_LANG_SPECIFIC (olddecl))
2834 gcc_checking_assert (DECL_LANG_SPECIFIC (olddecl)
2835 != DECL_LANG_SPECIFIC (newdecl));
2836 ggc_free (DECL_LANG_SPECIFIC (olddecl));
2839 /* Merge the USED information. */
2840 if (TREE_USED (olddecl))
2841 TREE_USED (newdecl) = 1;
2842 else if (TREE_USED (newdecl))
2843 TREE_USED (olddecl) = 1;
2845 if (VAR_P (newdecl))
2847 if (DECL_READ_P (olddecl))
2848 DECL_READ_P (newdecl) = 1;
2849 else if (DECL_READ_P (newdecl))
2850 DECL_READ_P (olddecl) = 1;
2853 if (DECL_PRESERVE_P (olddecl))
2854 DECL_PRESERVE_P (newdecl) = 1;
2855 else if (DECL_PRESERVE_P (newdecl))
2856 DECL_PRESERVE_P (olddecl) = 1;
2858 /* Merge the DECL_FUNCTION_VERSIONED information. newdecl will be copied
2859 to olddecl and deleted. */
2860 if (TREE_CODE (newdecl) == FUNCTION_DECL
2861 && DECL_FUNCTION_VERSIONED (olddecl))
2863 /* Set the flag for newdecl so that it gets copied to olddecl. */
2864 DECL_FUNCTION_VERSIONED (newdecl) = 1;
2865 /* newdecl will be purged after copying to olddecl and is no longer
2866 a version. */
2867 cgraph_node::delete_function_version_by_decl (newdecl);
2870 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2872 int function_size;
2873 struct symtab_node *snode = symtab_node::get (olddecl);
2875 function_size = sizeof (struct tree_decl_common);
2877 memcpy ((char *) olddecl + sizeof (struct tree_common),
2878 (char *) newdecl + sizeof (struct tree_common),
2879 function_size - sizeof (struct tree_common));
2881 memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
2882 (char *) newdecl + sizeof (struct tree_decl_common),
2883 sizeof (struct tree_function_decl) - sizeof (struct tree_decl_common));
2885 /* Preserve symtab node mapping. */
2886 olddecl->decl_with_vis.symtab_node = snode;
2888 if (new_template_info)
2889 /* If newdecl is a template instantiation, it is possible that
2890 the following sequence of events has occurred:
2892 o A friend function was declared in a class template. The
2893 class template was instantiated.
2895 o The instantiation of the friend declaration was
2896 recorded on the instantiation list, and is newdecl.
2898 o Later, however, instantiate_class_template called pushdecl
2899 on the newdecl to perform name injection. But, pushdecl in
2900 turn called duplicate_decls when it discovered that another
2901 declaration of a global function with the same name already
2902 existed.
2904 o Here, in duplicate_decls, we decided to clobber newdecl.
2906 If we're going to do that, we'd better make sure that
2907 olddecl, and not newdecl, is on the list of
2908 instantiations so that if we try to do the instantiation
2909 again we won't get the clobbered declaration. */
2910 reregister_specialization (newdecl,
2911 new_template_info,
2912 olddecl);
2914 else
2916 size_t size = tree_code_size (TREE_CODE (newdecl));
2918 memcpy ((char *) olddecl + sizeof (struct tree_common),
2919 (char *) newdecl + sizeof (struct tree_common),
2920 sizeof (struct tree_decl_common) - sizeof (struct tree_common));
2922 switch (TREE_CODE (newdecl))
2924 case LABEL_DECL:
2925 case VAR_DECL:
2926 case RESULT_DECL:
2927 case PARM_DECL:
2928 case FIELD_DECL:
2929 case TYPE_DECL:
2930 case CONST_DECL:
2932 struct symtab_node *snode = NULL;
2934 if (VAR_P (newdecl)
2935 && (TREE_STATIC (olddecl) || TREE_PUBLIC (olddecl)
2936 || DECL_EXTERNAL (olddecl)))
2937 snode = symtab_node::get (olddecl);
2938 memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
2939 (char *) newdecl + sizeof (struct tree_decl_common),
2940 size - sizeof (struct tree_decl_common)
2941 + TREE_CODE_LENGTH (TREE_CODE (newdecl)) * sizeof (char *));
2942 if (VAR_P (newdecl))
2943 olddecl->decl_with_vis.symtab_node = snode;
2945 break;
2946 default:
2947 memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
2948 (char *) newdecl + sizeof (struct tree_decl_common),
2949 sizeof (struct tree_decl_non_common) - sizeof (struct tree_decl_common)
2950 + TREE_CODE_LENGTH (TREE_CODE (newdecl)) * sizeof (char *));
2951 break;
2955 if (VAR_OR_FUNCTION_DECL_P (newdecl))
2957 if (DECL_EXTERNAL (olddecl)
2958 || TREE_PUBLIC (olddecl)
2959 || TREE_STATIC (olddecl))
2961 /* Merge the section attribute.
2962 We want to issue an error if the sections conflict but that must be
2963 done later in decl_attributes since we are called before attributes
2964 are assigned. */
2965 if (DECL_SECTION_NAME (newdecl) != NULL)
2966 set_decl_section_name (olddecl, newdecl);
2968 if (DECL_ONE_ONLY (newdecl))
2970 struct symtab_node *oldsym, *newsym;
2971 if (TREE_CODE (olddecl) == FUNCTION_DECL)
2972 oldsym = cgraph_node::get_create (olddecl);
2973 else
2974 oldsym = varpool_node::get_create (olddecl);
2975 newsym = symtab_node::get (newdecl);
2976 oldsym->set_comdat_group (newsym->get_comdat_group ());
2980 if (VAR_P (newdecl)
2981 && CP_DECL_THREAD_LOCAL_P (newdecl))
2983 CP_DECL_THREAD_LOCAL_P (olddecl) = true;
2984 if (!processing_template_decl)
2985 set_decl_tls_model (olddecl, DECL_TLS_MODEL (newdecl));
2989 DECL_UID (olddecl) = olddecl_uid;
2991 /* NEWDECL contains the merged attribute lists.
2992 Update OLDDECL to be the same. */
2993 DECL_ATTRIBUTES (olddecl) = DECL_ATTRIBUTES (newdecl);
2995 /* If OLDDECL had its DECL_RTL instantiated, re-invoke make_decl_rtl
2996 so that encode_section_info has a chance to look at the new decl
2997 flags and attributes. */
2998 if (DECL_RTL_SET_P (olddecl)
2999 && (TREE_CODE (olddecl) == FUNCTION_DECL
3000 || (VAR_P (olddecl)
3001 && TREE_STATIC (olddecl))))
3002 make_decl_rtl (olddecl);
3004 /* The NEWDECL will no longer be needed. Because every out-of-class
3005 declaration of a member results in a call to duplicate_decls,
3006 freeing these nodes represents in a significant savings.
3008 Before releasing the node, be sore to remove function from symbol
3009 table that might have been inserted there to record comdat group.
3010 Be sure to however do not free DECL_STRUCT_FUNCTION because this
3011 structure is shared in between newdecl and oldecl. */
3012 if (TREE_CODE (newdecl) == FUNCTION_DECL)
3013 DECL_STRUCT_FUNCTION (newdecl) = NULL;
3014 if (VAR_OR_FUNCTION_DECL_P (newdecl))
3016 struct symtab_node *snode = symtab_node::get (newdecl);
3017 if (snode)
3018 snode->remove ();
3021 if (TREE_CODE (olddecl) == FUNCTION_DECL)
3023 tree clone;
3024 FOR_EACH_CLONE (clone, olddecl)
3026 DECL_ATTRIBUTES (clone) = DECL_ATTRIBUTES (olddecl);
3027 DECL_PRESERVE_P (clone) |= DECL_PRESERVE_P (olddecl);
3031 /* Remove the associated constraints for newdecl, if any, before
3032 reclaiming memory. */
3033 if (flag_concepts)
3034 remove_constraints (newdecl);
3036 ggc_free (newdecl);
3038 return olddecl;
3041 /* Return zero if the declaration NEWDECL is valid
3042 when the declaration OLDDECL (assumed to be for the same name)
3043 has already been seen.
3044 Otherwise return an error message format string with a %s
3045 where the identifier should go. */
3047 static const char *
3048 redeclaration_error_message (tree newdecl, tree olddecl)
3050 if (TREE_CODE (newdecl) == TYPE_DECL)
3052 /* Because C++ can put things into name space for free,
3053 constructs like "typedef struct foo { ... } foo"
3054 would look like an erroneous redeclaration. */
3055 if (same_type_p (TREE_TYPE (newdecl), TREE_TYPE (olddecl)))
3056 return NULL;
3057 else
3058 return G_("redefinition of %q#D");
3060 else if (TREE_CODE (newdecl) == FUNCTION_DECL)
3062 /* If this is a pure function, its olddecl will actually be
3063 the original initialization to `0' (which we force to call
3064 abort()). Don't complain about redefinition in this case. */
3065 if (DECL_LANG_SPECIFIC (olddecl) && DECL_PURE_VIRTUAL_P (olddecl)
3066 && DECL_INITIAL (olddecl) == NULL_TREE)
3067 return NULL;
3069 /* If both functions come from different namespaces, this is not
3070 a redeclaration - this is a conflict with a used function. */
3071 if (DECL_NAMESPACE_SCOPE_P (olddecl)
3072 && DECL_CONTEXT (olddecl) != DECL_CONTEXT (newdecl)
3073 && ! decls_match (olddecl, newdecl))
3074 return G_("%qD conflicts with used function");
3076 /* We'll complain about linkage mismatches in
3077 warn_extern_redeclared_static. */
3079 /* Defining the same name twice is no good. */
3080 if (decl_defined_p (olddecl)
3081 && decl_defined_p (newdecl))
3083 if (DECL_NAME (olddecl) == NULL_TREE)
3084 return G_("%q#D not declared in class");
3085 else if (!GNU_INLINE_P (olddecl)
3086 || GNU_INLINE_P (newdecl))
3087 return G_("redefinition of %q#D");
3090 if (DECL_DECLARED_INLINE_P (olddecl) && DECL_DECLARED_INLINE_P (newdecl))
3092 bool olda = GNU_INLINE_P (olddecl);
3093 bool newa = GNU_INLINE_P (newdecl);
3095 if (olda != newa)
3097 if (newa)
3098 return G_("%q+D redeclared inline with "
3099 "%<gnu_inline%> attribute");
3100 else
3101 return G_("%q+D redeclared inline without "
3102 "%<gnu_inline%> attribute");
3106 if (deduction_guide_p (olddecl)
3107 && deduction_guide_p (newdecl))
3108 return G_("deduction guide %q+D redeclared");
3110 /* [class.compare.default]: A definition of a comparison operator as
3111 defaulted that appears in a class shall be the first declaration of
3112 that function. */
3113 special_function_kind sfk = special_function_p (olddecl);
3114 if (sfk == sfk_comparison && DECL_DEFAULTED_FN (newdecl))
3115 return G_("comparison operator %q+D defaulted after "
3116 "its first declaration");
3118 check_abi_tag_redeclaration
3119 (olddecl, lookup_attribute ("abi_tag", DECL_ATTRIBUTES (olddecl)),
3120 lookup_attribute ("abi_tag", DECL_ATTRIBUTES (newdecl)));
3122 return NULL;
3124 else if (TREE_CODE (newdecl) == TEMPLATE_DECL)
3126 tree nt, ot;
3128 if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == CONCEPT_DECL)
3129 return G_("redefinition of %q#D");
3131 if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) != FUNCTION_DECL)
3132 return redeclaration_error_message (DECL_TEMPLATE_RESULT (newdecl),
3133 DECL_TEMPLATE_RESULT (olddecl));
3135 if (DECL_TEMPLATE_RESULT (newdecl) == DECL_TEMPLATE_RESULT (olddecl))
3136 return NULL;
3138 nt = DECL_TEMPLATE_RESULT (newdecl);
3139 if (DECL_TEMPLATE_INFO (nt))
3140 nt = DECL_TEMPLATE_RESULT (template_for_substitution (nt));
3141 ot = DECL_TEMPLATE_RESULT (olddecl);
3142 if (DECL_TEMPLATE_INFO (ot))
3143 ot = DECL_TEMPLATE_RESULT (template_for_substitution (ot));
3144 if (DECL_INITIAL (nt) && DECL_INITIAL (ot)
3145 && (!GNU_INLINE_P (ot) || GNU_INLINE_P (nt)))
3146 return G_("redefinition of %q#D");
3148 if (DECL_DECLARED_INLINE_P (ot) && DECL_DECLARED_INLINE_P (nt))
3150 bool olda = GNU_INLINE_P (ot);
3151 bool newa = GNU_INLINE_P (nt);
3153 if (olda != newa)
3155 if (newa)
3156 return G_("%q+D redeclared inline with "
3157 "%<gnu_inline%> attribute");
3158 else
3159 return G_("%q+D redeclared inline without "
3160 "%<gnu_inline%> attribute");
3164 if (deduction_guide_p (olddecl)
3165 && deduction_guide_p (newdecl))
3166 return G_("deduction guide %q+D redeclared");
3168 /* Core issue #226 (C++11):
3170 If a friend function template declaration specifies a
3171 default template-argument, that declaration shall be a
3172 definition and shall be the only declaration of the
3173 function template in the translation unit. */
3174 if ((cxx_dialect != cxx98)
3175 && TREE_CODE (ot) == FUNCTION_DECL && DECL_UNIQUE_FRIEND_P (ot)
3176 && !check_default_tmpl_args (nt, DECL_TEMPLATE_PARMS (newdecl),
3177 /*is_primary=*/true,
3178 /*is_partial=*/false,
3179 /*is_friend_decl=*/2))
3180 return G_("redeclaration of friend %q#D "
3181 "may not have default template arguments");
3183 return NULL;
3185 else if (VAR_P (newdecl)
3186 && (CP_DECL_THREAD_LOCAL_P (newdecl)
3187 != CP_DECL_THREAD_LOCAL_P (olddecl))
3188 && (! DECL_LANG_SPECIFIC (olddecl)
3189 || ! CP_DECL_THREADPRIVATE_P (olddecl)
3190 || CP_DECL_THREAD_LOCAL_P (newdecl)))
3192 /* Only variables can be thread-local, and all declarations must
3193 agree on this property. */
3194 if (CP_DECL_THREAD_LOCAL_P (newdecl))
3195 return G_("thread-local declaration of %q#D follows "
3196 "non-thread-local declaration");
3197 else
3198 return G_("non-thread-local declaration of %q#D follows "
3199 "thread-local declaration");
3201 else if (toplevel_bindings_p () || DECL_NAMESPACE_SCOPE_P (newdecl))
3203 /* The objects have been declared at namespace scope. If either
3204 is a member of an anonymous union, then this is an invalid
3205 redeclaration. For example:
3207 int i;
3208 union { int i; };
3210 is invalid. */
3211 if ((VAR_P (newdecl) && DECL_ANON_UNION_VAR_P (newdecl))
3212 || (VAR_P (olddecl) && DECL_ANON_UNION_VAR_P (olddecl)))
3213 return G_("redeclaration of %q#D");
3214 /* If at least one declaration is a reference, there is no
3215 conflict. For example:
3217 int i = 3;
3218 extern int i;
3220 is valid. */
3221 if (DECL_EXTERNAL (newdecl) || DECL_EXTERNAL (olddecl))
3222 return NULL;
3224 /* Static data member declared outside a class definition
3225 if the variable is defined within the class with constexpr
3226 specifier is declaration rather than definition (and
3227 deprecated). */
3228 if (cxx_dialect >= cxx17
3229 && VAR_P (olddecl)
3230 && DECL_CLASS_SCOPE_P (olddecl)
3231 && DECL_DECLARED_CONSTEXPR_P (olddecl)
3232 && !DECL_INITIAL (newdecl))
3234 DECL_EXTERNAL (newdecl) = 1;
3235 /* For now, only warn with explicit -Wdeprecated. */
3236 if (OPTION_SET_P (warn_deprecated))
3238 auto_diagnostic_group d;
3239 if (warning_at (DECL_SOURCE_LOCATION (newdecl), OPT_Wdeprecated,
3240 "redundant redeclaration of %<constexpr%> "
3241 "static data member %qD", newdecl))
3242 inform (DECL_SOURCE_LOCATION (olddecl),
3243 "previous declaration of %qD", olddecl);
3245 return NULL;
3248 /* Reject two definitions. */
3249 return G_("redefinition of %q#D");
3251 else
3253 /* Objects declared with block scope: */
3254 /* Reject two definitions, and reject a definition
3255 together with an external reference. */
3256 if (!(DECL_EXTERNAL (newdecl) && DECL_EXTERNAL (olddecl)))
3257 return G_("redeclaration of %q#D");
3258 return NULL;
3263 /* Hash and equality functions for the named_label table. */
3265 hashval_t
3266 named_label_hash::hash (const value_type entry)
3268 return IDENTIFIER_HASH_VALUE (entry->name);
3271 bool
3272 named_label_hash::equal (const value_type entry, compare_type name)
3274 return name == entry->name;
3277 /* Look for a label named ID in the current function. If one cannot
3278 be found, create one. Return the named_label_entry, or NULL on
3279 failure. */
3281 static named_label_entry *
3282 lookup_label_1 (tree id, bool making_local_p)
3284 auto_cond_timevar tv (TV_NAME_LOOKUP);
3286 /* You can't use labels at global scope. */
3287 if (current_function_decl == NULL_TREE)
3289 error ("label %qE referenced outside of any function", id);
3290 return NULL;
3293 if (!named_labels)
3294 named_labels = hash_table<named_label_hash>::create_ggc (13);
3296 hashval_t hash = IDENTIFIER_HASH_VALUE (id);
3297 named_label_entry **slot
3298 = named_labels->find_slot_with_hash (id, hash, INSERT);
3299 named_label_entry *old = *slot;
3301 if (old && old->label_decl)
3303 if (!making_local_p)
3304 return old;
3306 if (old->binding_level == current_binding_level)
3308 error ("local label %qE conflicts with existing label", id);
3309 inform (DECL_SOURCE_LOCATION (old->label_decl), "previous label");
3310 return NULL;
3314 /* We are making a new decl, create or reuse the named_label_entry */
3315 named_label_entry *ent = NULL;
3316 if (old && !old->label_decl)
3317 ent = old;
3318 else
3320 ent = ggc_cleared_alloc<named_label_entry> ();
3321 ent->name = id;
3322 ent->outer = old;
3323 *slot = ent;
3326 /* Now create the LABEL_DECL. */
3327 tree decl = build_decl (input_location, LABEL_DECL, id, void_type_node);
3329 DECL_CONTEXT (decl) = current_function_decl;
3330 SET_DECL_MODE (decl, VOIDmode);
3331 if (making_local_p)
3333 C_DECLARED_LABEL_FLAG (decl) = true;
3334 DECL_CHAIN (decl) = current_binding_level->names;
3335 current_binding_level->names = decl;
3338 ent->label_decl = decl;
3340 return ent;
3343 /* Wrapper for lookup_label_1. */
3345 tree
3346 lookup_label (tree id)
3348 named_label_entry *ent = lookup_label_1 (id, false);
3349 return ent ? ent->label_decl : NULL_TREE;
3352 tree
3353 declare_local_label (tree id)
3355 named_label_entry *ent = lookup_label_1 (id, true);
3356 return ent ? ent->label_decl : NULL_TREE;
3359 /* Returns nonzero if it is ill-formed to jump past the declaration of
3360 DECL. Returns 2 if it's also a real problem. */
3362 static int
3363 decl_jump_unsafe (tree decl)
3365 /* [stmt.dcl]/3: A program that jumps from a point where a local variable
3366 with automatic storage duration is not in scope to a point where it is
3367 in scope is ill-formed unless the variable has scalar type, class type
3368 with a trivial default constructor and a trivial destructor, a
3369 cv-qualified version of one of these types, or an array of one of the
3370 preceding types and is declared without an initializer (8.5). */
3371 tree type = TREE_TYPE (decl);
3373 if (!VAR_P (decl) || TREE_STATIC (decl)
3374 || type == error_mark_node)
3375 return 0;
3377 if (DECL_NONTRIVIALLY_INITIALIZED_P (decl)
3378 || variably_modified_type_p (type, NULL_TREE))
3379 return 2;
3381 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
3382 return 1;
3384 return 0;
3387 /* A subroutine of check_previous_goto_1 and check_goto to identify a branch
3388 to the user. */
3390 static bool
3391 identify_goto (tree decl, location_t loc, const location_t *locus,
3392 diagnostic_t diag_kind)
3394 bool complained
3395 = emit_diagnostic (diag_kind, loc, 0,
3396 decl ? N_("jump to label %qD")
3397 : N_("jump to case label"), decl);
3398 if (complained && locus)
3399 inform (*locus, " from here");
3400 return complained;
3403 /* Check that a single previously seen jump to a newly defined label
3404 is OK. DECL is the LABEL_DECL or 0; LEVEL is the binding_level for
3405 the jump context; NAMES are the names in scope in LEVEL at the jump
3406 context; LOCUS is the source position of the jump or 0. Returns
3407 true if all is well. */
3409 static bool
3410 check_previous_goto_1 (tree decl, cp_binding_level* level, tree names,
3411 bool exited_omp, const location_t *locus)
3413 cp_binding_level *b;
3414 bool complained = false;
3415 int identified = 0;
3416 bool saw_eh = false, saw_omp = false, saw_tm = false, saw_cxif = false;
3417 bool saw_ceif = false;
3419 if (exited_omp)
3421 complained = identify_goto (decl, input_location, locus, DK_ERROR);
3422 if (complained)
3423 inform (input_location, " exits OpenMP structured block");
3424 saw_omp = true;
3425 identified = 2;
3428 for (b = current_binding_level; b ; b = b->level_chain)
3430 tree new_decls, old_decls = (b == level ? names : NULL_TREE);
3432 for (new_decls = b->names; new_decls != old_decls;
3433 new_decls = (DECL_P (new_decls) ? DECL_CHAIN (new_decls)
3434 : TREE_CHAIN (new_decls)))
3436 int problem = decl_jump_unsafe (new_decls);
3437 if (! problem)
3438 continue;
3440 if (!identified)
3442 complained = identify_goto (decl, input_location, locus,
3443 problem > 1
3444 ? DK_ERROR : DK_PERMERROR);
3445 identified = 1;
3447 if (complained)
3449 if (problem > 1)
3450 inform (DECL_SOURCE_LOCATION (new_decls),
3451 " crosses initialization of %q#D", new_decls);
3452 else
3453 inform (DECL_SOURCE_LOCATION (new_decls),
3454 " enters scope of %q#D, which has "
3455 "non-trivial destructor", new_decls);
3459 if (b == level)
3460 break;
3462 const char *inf = NULL;
3463 location_t loc = input_location;
3464 switch (b->kind)
3466 case sk_try:
3467 if (!saw_eh)
3468 inf = G_(" enters %<try%> block");
3469 saw_eh = true;
3470 break;
3472 case sk_catch:
3473 if (!saw_eh)
3474 inf = G_(" enters %<catch%> block");
3475 saw_eh = true;
3476 break;
3478 case sk_omp:
3479 if (!saw_omp)
3480 inf = G_(" enters OpenMP structured block");
3481 saw_omp = true;
3482 break;
3484 case sk_transaction:
3485 if (!saw_tm)
3486 inf = G_(" enters synchronized or atomic statement");
3487 saw_tm = true;
3488 break;
3490 case sk_block:
3491 if (!saw_cxif && level_for_constexpr_if (b->level_chain))
3493 inf = G_(" enters %<constexpr if%> statement");
3494 loc = EXPR_LOCATION (b->level_chain->this_entity);
3495 saw_cxif = true;
3497 else if (!saw_ceif && level_for_consteval_if (b->level_chain))
3499 inf = G_(" enters %<consteval if%> statement");
3500 loc = EXPR_LOCATION (b->level_chain->this_entity);
3501 saw_ceif = true;
3503 break;
3505 default:
3506 break;
3509 if (inf)
3511 if (identified < 2)
3512 complained = identify_goto (decl, input_location, locus, DK_ERROR);
3513 identified = 2;
3514 if (complained)
3515 inform (loc, inf);
3519 return !identified;
3522 static void
3523 check_previous_goto (tree decl, struct named_label_use_entry *use)
3525 check_previous_goto_1 (decl, use->binding_level,
3526 use->names_in_scope, use->in_omp_scope,
3527 &use->o_goto_locus);
3530 static bool
3531 check_switch_goto (cp_binding_level* level)
3533 return check_previous_goto_1 (NULL_TREE, level, level->names, false, NULL);
3536 /* Check that a new jump to a label DECL is OK. Called by
3537 finish_goto_stmt. */
3539 void
3540 check_goto (tree decl)
3542 /* We can't know where a computed goto is jumping.
3543 So we assume that it's OK. */
3544 if (TREE_CODE (decl) != LABEL_DECL)
3545 return;
3547 /* We didn't record any information about this label when we created it,
3548 and there's not much point since it's trivial to analyze as a return. */
3549 if (decl == cdtor_label)
3550 return;
3552 hashval_t hash = IDENTIFIER_HASH_VALUE (DECL_NAME (decl));
3553 named_label_entry **slot
3554 = named_labels->find_slot_with_hash (DECL_NAME (decl), hash, NO_INSERT);
3555 named_label_entry *ent = *slot;
3557 /* If the label hasn't been defined yet, defer checking. */
3558 if (! DECL_INITIAL (decl))
3560 /* Don't bother creating another use if the last goto had the
3561 same data, and will therefore create the same set of errors. */
3562 if (ent->uses
3563 && ent->uses->names_in_scope == current_binding_level->names)
3564 return;
3566 named_label_use_entry *new_use
3567 = ggc_alloc<named_label_use_entry> ();
3568 new_use->binding_level = current_binding_level;
3569 new_use->names_in_scope = current_binding_level->names;
3570 new_use->o_goto_locus = input_location;
3571 new_use->in_omp_scope = false;
3573 new_use->next = ent->uses;
3574 ent->uses = new_use;
3575 return;
3578 bool saw_catch = false, complained = false;
3579 int identified = 0;
3580 tree bad;
3581 unsigned ix;
3583 if (ent->in_try_scope || ent->in_catch_scope || ent->in_transaction_scope
3584 || ent->in_constexpr_if || ent->in_consteval_if
3585 || ent->in_omp_scope || !vec_safe_is_empty (ent->bad_decls))
3587 diagnostic_t diag_kind = DK_PERMERROR;
3588 if (ent->in_try_scope || ent->in_catch_scope || ent->in_constexpr_if
3589 || ent->in_consteval_if || ent->in_transaction_scope
3590 || ent->in_omp_scope)
3591 diag_kind = DK_ERROR;
3592 complained = identify_goto (decl, DECL_SOURCE_LOCATION (decl),
3593 &input_location, diag_kind);
3594 identified = 1 + (diag_kind == DK_ERROR);
3597 FOR_EACH_VEC_SAFE_ELT (ent->bad_decls, ix, bad)
3599 int u = decl_jump_unsafe (bad);
3601 if (u > 1 && DECL_ARTIFICIAL (bad))
3603 /* Can't skip init of __exception_info. */
3604 if (identified == 1)
3606 complained = identify_goto (decl, DECL_SOURCE_LOCATION (decl),
3607 &input_location, DK_ERROR);
3608 identified = 2;
3610 if (complained)
3611 inform (DECL_SOURCE_LOCATION (bad), " enters %<catch%> block");
3612 saw_catch = true;
3614 else if (complained)
3616 if (u > 1)
3617 inform (DECL_SOURCE_LOCATION (bad),
3618 " skips initialization of %q#D", bad);
3619 else
3620 inform (DECL_SOURCE_LOCATION (bad),
3621 " enters scope of %q#D which has "
3622 "non-trivial destructor", bad);
3626 if (complained)
3628 if (ent->in_try_scope)
3629 inform (input_location, " enters %<try%> block");
3630 else if (ent->in_catch_scope && !saw_catch)
3631 inform (input_location, " enters %<catch%> block");
3632 else if (ent->in_transaction_scope)
3633 inform (input_location, " enters synchronized or atomic statement");
3634 else if (ent->in_constexpr_if)
3635 inform (input_location, " enters %<constexpr if%> statement");
3636 else if (ent->in_consteval_if)
3637 inform (input_location, " enters %<consteval if%> statement");
3640 if (ent->in_omp_scope)
3642 if (complained)
3643 inform (input_location, " enters OpenMP structured block");
3645 else if (flag_openmp)
3646 for (cp_binding_level *b = current_binding_level; b ; b = b->level_chain)
3648 if (b == ent->binding_level)
3649 break;
3650 if (b->kind == sk_omp)
3652 if (identified < 2)
3654 complained = identify_goto (decl,
3655 DECL_SOURCE_LOCATION (decl),
3656 &input_location, DK_ERROR);
3657 identified = 2;
3659 if (complained)
3660 inform (input_location, " exits OpenMP structured block");
3661 break;
3666 /* Check that a return is ok wrt OpenMP structured blocks.
3667 Called by finish_return_stmt. Returns true if all is well. */
3669 bool
3670 check_omp_return (void)
3672 for (cp_binding_level *b = current_binding_level; b ; b = b->level_chain)
3673 if (b->kind == sk_omp)
3675 error ("invalid exit from OpenMP structured block");
3676 return false;
3678 else if (b->kind == sk_function_parms)
3679 break;
3680 return true;
3683 /* Define a label, specifying the location in the source file.
3684 Return the LABEL_DECL node for the label. */
3686 tree
3687 define_label (location_t location, tree name)
3689 auto_cond_timevar tv (TV_NAME_LOOKUP);
3691 /* After labels, make any new cleanups in the function go into their
3692 own new (temporary) binding contour. */
3693 for (cp_binding_level *p = current_binding_level;
3694 p->kind != sk_function_parms;
3695 p = p->level_chain)
3696 p->more_cleanups_ok = 0;
3698 named_label_entry *ent = lookup_label_1 (name, false);
3699 tree decl = ent->label_decl;
3701 if (DECL_INITIAL (decl) != NULL_TREE)
3703 error ("duplicate label %qD", decl);
3704 return error_mark_node;
3706 else
3708 /* Mark label as having been defined. */
3709 DECL_INITIAL (decl) = error_mark_node;
3710 /* Say where in the source. */
3711 DECL_SOURCE_LOCATION (decl) = location;
3713 ent->binding_level = current_binding_level;
3714 ent->names_in_scope = current_binding_level->names;
3716 for (named_label_use_entry *use = ent->uses; use; use = use->next)
3717 check_previous_goto (decl, use);
3718 ent->uses = NULL;
3721 return decl;
3724 struct cp_switch
3726 cp_binding_level *level;
3727 struct cp_switch *next;
3728 /* The SWITCH_STMT being built. */
3729 tree switch_stmt;
3730 /* A splay-tree mapping the low element of a case range to the high
3731 element, or NULL_TREE if there is no high element. Used to
3732 determine whether or not a new case label duplicates an old case
3733 label. We need a tree, rather than simply a hash table, because
3734 of the GNU case range extension. */
3735 splay_tree cases;
3736 /* Remember whether a default: case label has been seen. */
3737 bool has_default_p;
3738 /* Remember whether a BREAK_STMT has been seen in this SWITCH_STMT. */
3739 bool break_stmt_seen_p;
3740 /* Set if inside of {FOR,DO,WHILE}_BODY nested inside of a switch,
3741 where BREAK_STMT doesn't belong to the SWITCH_STMT. */
3742 bool in_loop_body_p;
3745 /* A stack of the currently active switch statements. The innermost
3746 switch statement is on the top of the stack. There is no need to
3747 mark the stack for garbage collection because it is only active
3748 during the processing of the body of a function, and we never
3749 collect at that point. */
3751 static struct cp_switch *switch_stack;
3753 /* Called right after a switch-statement condition is parsed.
3754 SWITCH_STMT is the switch statement being parsed. */
3756 void
3757 push_switch (tree switch_stmt)
3759 struct cp_switch *p = XNEW (struct cp_switch);
3760 p->level = current_binding_level;
3761 p->next = switch_stack;
3762 p->switch_stmt = switch_stmt;
3763 p->cases = splay_tree_new (case_compare, NULL, NULL);
3764 p->has_default_p = false;
3765 p->break_stmt_seen_p = false;
3766 p->in_loop_body_p = false;
3767 switch_stack = p;
3770 void
3771 pop_switch (void)
3773 struct cp_switch *cs = switch_stack;
3775 /* Emit warnings as needed. */
3776 location_t switch_location = cp_expr_loc_or_input_loc (cs->switch_stmt);
3777 tree cond = SWITCH_STMT_COND (cs->switch_stmt);
3778 const bool bool_cond_p
3779 = (SWITCH_STMT_TYPE (cs->switch_stmt)
3780 && TREE_CODE (SWITCH_STMT_TYPE (cs->switch_stmt)) == BOOLEAN_TYPE);
3781 if (!processing_template_decl)
3782 c_do_switch_warnings (cs->cases, switch_location,
3783 SWITCH_STMT_TYPE (cs->switch_stmt), cond,
3784 bool_cond_p);
3786 /* For the benefit of block_may_fallthru remember if the switch body
3787 case labels cover all possible values and if there are break; stmts. */
3788 if (cs->has_default_p
3789 || (!processing_template_decl
3790 && c_switch_covers_all_cases_p (cs->cases,
3791 SWITCH_STMT_TYPE (cs->switch_stmt))))
3792 SWITCH_STMT_ALL_CASES_P (cs->switch_stmt) = 1;
3793 if (!cs->break_stmt_seen_p)
3794 SWITCH_STMT_NO_BREAK_P (cs->switch_stmt) = 1;
3795 /* Now that we're done with the switch warnings, set the switch type
3796 to the type of the condition if the index type was of scoped enum type.
3797 (Such types don't participate in the integer promotions.) We do this
3798 because of bit-fields whose declared type is a scoped enum type:
3799 gimplification will use the lowered index type, but convert the
3800 case values to SWITCH_STMT_TYPE, which would have been the declared type
3801 and verify_gimple_switch doesn't accept that. */
3802 if (is_bitfield_expr_with_lowered_type (cond))
3803 SWITCH_STMT_TYPE (cs->switch_stmt) = TREE_TYPE (cond);
3804 gcc_assert (!cs->in_loop_body_p);
3805 splay_tree_delete (cs->cases);
3806 switch_stack = switch_stack->next;
3807 free (cs);
3810 /* Note that a BREAK_STMT is about to be added. If it is inside of
3811 a SWITCH_STMT and not inside of a loop body inside of it, note
3812 in switch_stack we've seen a BREAK_STMT. */
3814 void
3815 note_break_stmt (void)
3817 if (switch_stack && !switch_stack->in_loop_body_p)
3818 switch_stack->break_stmt_seen_p = true;
3821 /* Note the start of processing of an iteration statement's body.
3822 The note_break_stmt function will do nothing while processing it.
3823 Return a flag that should be passed to note_iteration_stmt_body_end. */
3825 bool
3826 note_iteration_stmt_body_start (void)
3828 if (!switch_stack)
3829 return false;
3830 bool ret = switch_stack->in_loop_body_p;
3831 switch_stack->in_loop_body_p = true;
3832 return ret;
3835 /* Note the end of processing of an iteration statement's body. */
3837 void
3838 note_iteration_stmt_body_end (bool prev)
3840 if (switch_stack)
3841 switch_stack->in_loop_body_p = prev;
3844 /* Convert a case constant VALUE in a switch to the type TYPE of the switch
3845 condition. Note that if TYPE and VALUE are already integral we don't
3846 really do the conversion because the language-independent
3847 warning/optimization code will work better that way. */
3849 static tree
3850 case_conversion (tree type, tree value)
3852 if (value == NULL_TREE)
3853 return value;
3855 value = mark_rvalue_use (value);
3857 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3858 type = type_promotes_to (type);
3860 tree ovalue = value;
3861 /* The constant-expression VALUE shall be a converted constant expression
3862 of the adjusted type of the switch condition, which doesn't allow
3863 narrowing conversions. */
3864 value = build_converted_constant_expr (type, value, tf_warning_or_error);
3866 if (cxx_dialect >= cxx11
3867 && (SCOPED_ENUM_P (type)
3868 || !INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (ovalue))))
3869 /* Use the converted value. */;
3870 else
3871 /* The already integral case. */
3872 value = ovalue;
3874 return cxx_constant_value (value);
3877 /* Note that we've seen a definition of a case label, and complain if this
3878 is a bad place for one. */
3880 tree
3881 finish_case_label (location_t loc, tree low_value, tree high_value)
3883 tree cond, r;
3884 cp_binding_level *p;
3885 tree type;
3887 if (low_value == NULL_TREE && high_value == NULL_TREE)
3888 switch_stack->has_default_p = true;
3890 if (processing_template_decl)
3892 tree label;
3894 /* For templates, just add the case label; we'll do semantic
3895 analysis at instantiation-time. */
3896 label = build_decl (loc, LABEL_DECL, NULL_TREE, void_type_node);
3897 return add_stmt (build_case_label (low_value, high_value, label));
3900 /* Find the condition on which this switch statement depends. */
3901 cond = SWITCH_STMT_COND (switch_stack->switch_stmt);
3902 if (cond && TREE_CODE (cond) == TREE_LIST)
3903 cond = TREE_VALUE (cond);
3905 if (!check_switch_goto (switch_stack->level))
3906 return error_mark_node;
3908 type = SWITCH_STMT_TYPE (switch_stack->switch_stmt);
3909 if (type == error_mark_node)
3910 return error_mark_node;
3912 low_value = case_conversion (type, low_value);
3913 high_value = case_conversion (type, high_value);
3915 r = c_add_case_label (loc, switch_stack->cases, cond, low_value, high_value);
3917 /* After labels, make any new cleanups in the function go into their
3918 own new (temporary) binding contour. */
3919 for (p = current_binding_level;
3920 p->kind != sk_function_parms;
3921 p = p->level_chain)
3922 p->more_cleanups_ok = 0;
3924 return r;
3927 struct typename_info {
3928 tree scope;
3929 tree name;
3930 tree template_id;
3931 bool enum_p;
3932 bool class_p;
3935 struct typename_hasher : ggc_ptr_hash<tree_node>
3937 typedef typename_info *compare_type;
3939 /* Hash a TYPENAME_TYPE. */
3941 static hashval_t
3942 hash (tree t)
3944 hashval_t hash;
3946 hash = (htab_hash_pointer (TYPE_CONTEXT (t))
3947 ^ htab_hash_pointer (TYPE_IDENTIFIER (t)));
3949 return hash;
3952 /* Compare two TYPENAME_TYPEs. */
3954 static bool
3955 equal (tree t1, const typename_info *t2)
3957 return (TYPE_IDENTIFIER (t1) == t2->name
3958 && TYPE_CONTEXT (t1) == t2->scope
3959 && TYPENAME_TYPE_FULLNAME (t1) == t2->template_id
3960 && TYPENAME_IS_ENUM_P (t1) == t2->enum_p
3961 && TYPENAME_IS_CLASS_P (t1) == t2->class_p);
3965 /* Build a TYPENAME_TYPE. If the type is `typename T::t', CONTEXT is
3966 the type of `T', NAME is the IDENTIFIER_NODE for `t'.
3968 Returns the new TYPENAME_TYPE. */
3970 static GTY (()) hash_table<typename_hasher> *typename_htab;
3972 tree
3973 build_typename_type (tree context, tree name, tree fullname,
3974 enum tag_types tag_type)
3976 typename_info ti;
3978 if (typename_htab == NULL)
3979 typename_htab = hash_table<typename_hasher>::create_ggc (61);
3981 ti.scope = FROB_CONTEXT (context);
3982 ti.name = name;
3983 ti.template_id = fullname;
3984 ti.enum_p = tag_type == enum_type;
3985 ti.class_p = (tag_type == class_type
3986 || tag_type == record_type
3987 || tag_type == union_type);
3988 hashval_t hash = (htab_hash_pointer (ti.scope)
3989 ^ htab_hash_pointer (ti.name));
3991 /* See if we already have this type. */
3992 tree *e = typename_htab->find_slot_with_hash (&ti, hash, INSERT);
3993 tree t = *e;
3994 if (*e)
3995 t = *e;
3996 else
3998 /* Build the TYPENAME_TYPE. */
3999 t = cxx_make_type (TYPENAME_TYPE);
4000 TYPE_CONTEXT (t) = ti.scope;
4001 TYPENAME_TYPE_FULLNAME (t) = ti.template_id;
4002 TYPENAME_IS_ENUM_P (t) = ti.enum_p;
4003 TYPENAME_IS_CLASS_P (t) = ti.class_p;
4005 /* Build the corresponding TYPE_DECL. */
4006 tree d = build_decl (input_location, TYPE_DECL, name, t);
4007 TYPE_NAME (t) = d;
4008 TYPE_STUB_DECL (t) = d;
4009 DECL_CONTEXT (d) = ti.scope;
4010 DECL_ARTIFICIAL (d) = 1;
4012 /* Store it in the hash table. */
4013 *e = t;
4015 /* TYPENAME_TYPEs must always be compared structurally, because
4016 they may or may not resolve down to another type depending on
4017 the currently open classes. */
4018 SET_TYPE_STRUCTURAL_EQUALITY (t);
4021 return t;
4024 /* Resolve `typename CONTEXT::NAME'. TAG_TYPE indicates the tag
4025 provided to name the type. Returns an appropriate type, unless an
4026 error occurs, in which case error_mark_node is returned. If we
4027 locate a non-artificial TYPE_DECL and TF_KEEP_TYPE_DECL is set, we
4028 return that, rather than the _TYPE it corresponds to, in other
4029 cases we look through the type decl. If TF_ERROR is set, complain
4030 about errors, otherwise be quiet. */
4032 tree
4033 make_typename_type (tree context, tree name, enum tag_types tag_type,
4034 tsubst_flags_t complain)
4036 tree fullname;
4037 tree t;
4038 bool want_template;
4040 if (name == error_mark_node
4041 || context == NULL_TREE
4042 || context == error_mark_node)
4043 return error_mark_node;
4045 if (TYPE_P (name))
4047 if (!(TYPE_LANG_SPECIFIC (name)
4048 && (CLASSTYPE_IS_TEMPLATE (name)
4049 || CLASSTYPE_USE_TEMPLATE (name))))
4050 name = TYPE_IDENTIFIER (name);
4051 else
4052 /* Create a TEMPLATE_ID_EXPR for the type. */
4053 name = build_nt (TEMPLATE_ID_EXPR,
4054 CLASSTYPE_TI_TEMPLATE (name),
4055 CLASSTYPE_TI_ARGS (name));
4057 else if (TREE_CODE (name) == TYPE_DECL)
4058 name = DECL_NAME (name);
4060 fullname = name;
4062 if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
4064 name = TREE_OPERAND (name, 0);
4065 if (DECL_TYPE_TEMPLATE_P (name))
4066 name = TREE_OPERAND (fullname, 0) = DECL_NAME (name);
4067 if (TREE_CODE (name) != IDENTIFIER_NODE)
4069 if (complain & tf_error)
4070 error ("%qD is not a type", name);
4071 return error_mark_node;
4074 if (TREE_CODE (name) == TEMPLATE_DECL)
4076 if (complain & tf_error)
4077 error ("%qD used without template arguments", name);
4078 return error_mark_node;
4080 else if (is_overloaded_fn (name))
4082 if (complain & tf_error)
4083 error ("%qD is a function, not a type", name);
4084 return error_mark_node;
4086 gcc_assert (identifier_p (name));
4087 gcc_assert (TYPE_P (context));
4089 if (TREE_CODE (context) == TYPE_PACK_EXPANSION)
4090 /* This can happen for C++17 variadic using (c++/88986). */;
4091 else if (!MAYBE_CLASS_TYPE_P (context))
4093 if (complain & tf_error)
4094 error ("%q#T is not a class", context);
4095 return error_mark_node;
4098 /* When the CONTEXT is a dependent type, NAME could refer to a
4099 dependent base class of CONTEXT. But look inside it anyway
4100 if CONTEXT is a currently open scope, in case it refers to a
4101 member of the current instantiation or a non-dependent base;
4102 lookup will stop when we hit a dependent base. */
4103 if (!dependent_scope_p (context))
4104 /* We should only set WANT_TYPE when we're a nested typename type.
4105 Then we can give better diagnostics if we find a non-type. */
4106 t = lookup_field (context, name, 2, /*want_type=*/true);
4107 else
4108 t = NULL_TREE;
4110 if ((!t || TREE_CODE (t) == TREE_LIST) && dependent_type_p (context))
4111 return build_typename_type (context, name, fullname, tag_type);
4113 want_template = TREE_CODE (fullname) == TEMPLATE_ID_EXPR;
4115 if (!t)
4117 if (complain & tf_error)
4119 if (!COMPLETE_TYPE_P (context))
4120 cxx_incomplete_type_error (NULL_TREE, context);
4121 else
4122 error (want_template ? G_("no class template named %q#T in %q#T")
4123 : G_("no type named %q#T in %q#T"), name, context);
4125 return error_mark_node;
4128 /* Pull out the template from an injected-class-name (or multiple). */
4129 if (want_template)
4130 t = maybe_get_template_decl_from_type_decl (t);
4132 if (TREE_CODE (t) == TREE_LIST)
4134 if (complain & tf_error)
4136 error ("lookup of %qT in %qT is ambiguous", name, context);
4137 print_candidates (t);
4139 return error_mark_node;
4142 if (want_template && !DECL_TYPE_TEMPLATE_P (t))
4144 if (complain & tf_error)
4145 error ("%<typename %T::%D%> names %q#T, which is not a class template",
4146 context, name, t);
4147 return error_mark_node;
4149 if (!want_template && TREE_CODE (t) != TYPE_DECL)
4151 if (complain & tf_error)
4152 error ("%<typename %T::%D%> names %q#T, which is not a type",
4153 context, name, t);
4154 return error_mark_node;
4157 if (!check_accessibility_of_qualified_id (t, /*object_type=*/NULL_TREE,
4158 context, complain))
4159 return error_mark_node;
4161 if (want_template)
4163 t = lookup_template_class (t, TREE_OPERAND (fullname, 1),
4164 NULL_TREE, context,
4165 /*entering_scope=*/0,
4166 complain | tf_user);
4167 if (t == error_mark_node)
4168 return error_mark_node;
4169 t = TYPE_NAME (t);
4172 if (DECL_ARTIFICIAL (t) || !(complain & tf_keep_type_decl))
4173 t = TREE_TYPE (t);
4175 maybe_record_typedef_use (t);
4177 return t;
4180 /* Resolve `CONTEXT::template NAME'. Returns a TEMPLATE_DECL if the name
4181 can be resolved or an UNBOUND_CLASS_TEMPLATE, unless an error occurs,
4182 in which case error_mark_node is returned.
4184 If PARM_LIST is non-NULL, also make sure that the template parameter
4185 list of TEMPLATE_DECL matches.
4187 If COMPLAIN zero, don't complain about any errors that occur. */
4189 tree
4190 make_unbound_class_template (tree context, tree name, tree parm_list,
4191 tsubst_flags_t complain)
4193 if (TYPE_P (name))
4194 name = TYPE_IDENTIFIER (name);
4195 else if (DECL_P (name))
4196 name = DECL_NAME (name);
4197 gcc_assert (identifier_p (name));
4199 if (!dependent_type_p (context)
4200 || currently_open_class (context))
4202 tree tmpl = NULL_TREE;
4204 if (MAYBE_CLASS_TYPE_P (context))
4205 tmpl = lookup_field (context, name, 0, false);
4207 if (tmpl && TREE_CODE (tmpl) == TYPE_DECL)
4208 tmpl = maybe_get_template_decl_from_type_decl (tmpl);
4210 if (!tmpl || !DECL_TYPE_TEMPLATE_P (tmpl))
4212 if (complain & tf_error)
4213 error ("no class template named %q#T in %q#T", name, context);
4214 return error_mark_node;
4217 if (parm_list
4218 && !comp_template_parms (DECL_TEMPLATE_PARMS (tmpl), parm_list))
4220 if (complain & tf_error)
4222 error ("template parameters do not match template %qD", tmpl);
4223 inform (DECL_SOURCE_LOCATION (tmpl),
4224 "%qD declared here", tmpl);
4226 return error_mark_node;
4229 if (!perform_or_defer_access_check (TYPE_BINFO (context), tmpl, tmpl,
4230 complain))
4231 return error_mark_node;
4233 return tmpl;
4236 return make_unbound_class_template_raw (context, name, parm_list);
4239 /* Build an UNBOUND_CLASS_TEMPLATE. */
4241 tree
4242 make_unbound_class_template_raw (tree context, tree name, tree parm_list)
4244 /* Build the UNBOUND_CLASS_TEMPLATE. */
4245 tree t = cxx_make_type (UNBOUND_CLASS_TEMPLATE);
4246 TYPE_CONTEXT (t) = FROB_CONTEXT (context);
4247 TREE_TYPE (t) = NULL_TREE;
4248 SET_TYPE_STRUCTURAL_EQUALITY (t);
4250 /* Build the corresponding TEMPLATE_DECL. */
4251 tree d = build_decl (input_location, TEMPLATE_DECL, name, t);
4252 TYPE_NAME (t) = d;
4253 TYPE_STUB_DECL (t) = d;
4254 DECL_CONTEXT (d) = TYPE_CONTEXT (t);
4255 DECL_ARTIFICIAL (d) = 1;
4256 DECL_TEMPLATE_PARMS (d) = parm_list;
4258 return t;
4263 /* Push the declarations of builtin types into the global namespace.
4264 RID_INDEX is the index of the builtin type in the array
4265 RID_POINTERS. NAME is the name used when looking up the builtin
4266 type. TYPE is the _TYPE node for the builtin type.
4268 The calls to set_global_binding below should be
4269 eliminated. Built-in types should not be looked up name; their
4270 names are keywords that the parser can recognize. However, there
4271 is code in c-common.c that uses identifier_global_value to look up
4272 built-in types by name. */
4274 void
4275 record_builtin_type (enum rid rid_index,
4276 const char* name,
4277 tree type)
4279 tree decl = NULL_TREE;
4281 if (name)
4283 tree tname = get_identifier (name);
4284 tree tdecl = build_decl (BUILTINS_LOCATION, TYPE_DECL, tname, type);
4285 DECL_ARTIFICIAL (tdecl) = 1;
4286 set_global_binding (tdecl);
4287 decl = tdecl;
4290 if ((int) rid_index < (int) RID_MAX)
4291 if (tree rname = ridpointers[(int) rid_index])
4292 if (!decl || DECL_NAME (decl) != rname)
4294 tree rdecl = build_decl (BUILTINS_LOCATION, TYPE_DECL, rname, type);
4295 DECL_ARTIFICIAL (rdecl) = 1;
4296 set_global_binding (rdecl);
4297 if (!decl)
4298 decl = rdecl;
4301 if (decl)
4303 if (!TYPE_NAME (type))
4304 TYPE_NAME (type) = decl;
4305 debug_hooks->type_decl (decl, 0);
4309 /* Push a type into the namespace so that the back ends ignore it. */
4311 static void
4312 record_unknown_type (tree type, const char* name)
4314 tree decl = pushdecl (build_decl (UNKNOWN_LOCATION,
4315 TYPE_DECL, get_identifier (name), type));
4316 /* Make sure the "unknown type" typedecl gets ignored for debug info. */
4317 DECL_IGNORED_P (decl) = 1;
4318 TYPE_DECL_SUPPRESS_DEBUG (decl) = 1;
4319 TYPE_SIZE (type) = TYPE_SIZE (void_type_node);
4320 SET_TYPE_ALIGN (type, 1);
4321 TYPE_USER_ALIGN (type) = 0;
4322 SET_TYPE_MODE (type, TYPE_MODE (void_type_node));
4325 /* Create all the predefined identifiers. */
4327 static void
4328 initialize_predefined_identifiers (void)
4330 struct predefined_identifier
4332 const char *name; /* Name. */
4333 tree *node; /* Node to store it in. */
4334 cp_identifier_kind kind; /* Kind of identifier. */
4337 /* A table of identifiers to create at startup. */
4338 static const predefined_identifier predefined_identifiers[] = {
4339 {"C++", &lang_name_cplusplus, cik_normal},
4340 {"C", &lang_name_c, cik_normal},
4341 /* Some of these names have a trailing space so that it is
4342 impossible for them to conflict with names written by users. */
4343 {"__ct ", &ctor_identifier, cik_ctor},
4344 {"__ct_base ", &base_ctor_identifier, cik_ctor},
4345 {"__ct_comp ", &complete_ctor_identifier, cik_ctor},
4346 {"__dt ", &dtor_identifier, cik_dtor},
4347 {"__dt_base ", &base_dtor_identifier, cik_dtor},
4348 {"__dt_comp ", &complete_dtor_identifier, cik_dtor},
4349 {"__dt_del ", &deleting_dtor_identifier, cik_dtor},
4350 {"__conv_op ", &conv_op_identifier, cik_conv_op},
4351 {"__in_chrg", &in_charge_identifier, cik_normal},
4352 {"__as_base ", &as_base_identifier, cik_normal},
4353 {"this", &this_identifier, cik_normal},
4354 {"__delta", &delta_identifier, cik_normal},
4355 {"__pfn", &pfn_identifier, cik_normal},
4356 {"_vptr", &vptr_identifier, cik_normal},
4357 {"__vtt_parm", &vtt_parm_identifier, cik_normal},
4358 {"::", &global_identifier, cik_normal},
4359 /* The demangler expects anonymous namespaces to be called
4360 something starting with '_GLOBAL__N_'. It no longer needs
4361 to be unique to the TU. */
4362 {"_GLOBAL__N_1", &anon_identifier, cik_normal},
4363 {"auto", &auto_identifier, cik_normal},
4364 {"decltype(auto)", &decltype_auto_identifier, cik_normal},
4365 {"initializer_list", &init_list_identifier, cik_normal},
4366 {"__for_range ", &for_range__identifier, cik_normal},
4367 {"__for_begin ", &for_begin__identifier, cik_normal},
4368 {"__for_end ", &for_end__identifier, cik_normal},
4369 {"__for_range", &for_range_identifier, cik_normal},
4370 {"__for_begin", &for_begin_identifier, cik_normal},
4371 {"__for_end", &for_end_identifier, cik_normal},
4372 {"abi_tag", &abi_tag_identifier, cik_normal},
4373 {"aligned", &aligned_identifier, cik_normal},
4374 {"begin", &begin_identifier, cik_normal},
4375 {"end", &end_identifier, cik_normal},
4376 {"get", &get__identifier, cik_normal},
4377 {"gnu", &gnu_identifier, cik_normal},
4378 {"tuple_element", &tuple_element_identifier, cik_normal},
4379 {"tuple_size", &tuple_size_identifier, cik_normal},
4380 {"type", &type_identifier, cik_normal},
4381 {"value", &value_identifier, cik_normal},
4382 {"_FUN", &fun_identifier, cik_normal},
4383 {"__closure", &closure_identifier, cik_normal},
4384 {"heap uninit", &heap_uninit_identifier, cik_normal},
4385 {"heap ", &heap_identifier, cik_normal},
4386 {"heap deleted", &heap_deleted_identifier, cik_normal},
4387 {"heap [] uninit", &heap_vec_uninit_identifier, cik_normal},
4388 {"heap []", &heap_vec_identifier, cik_normal},
4389 {"omp", &omp_identifier, cik_normal},
4390 {NULL, NULL, cik_normal}
4393 for (const predefined_identifier *pid = predefined_identifiers;
4394 pid->name; ++pid)
4396 *pid->node = get_identifier (pid->name);
4397 /* Some of these identifiers already have a special kind. */
4398 if (pid->kind != cik_normal)
4399 set_identifier_kind (*pid->node, pid->kind);
4403 /* Create the predefined scalar types of C,
4404 and some nodes representing standard constants (0, 1, (void *)0).
4405 Initialize the global binding level.
4406 Make definitions for built-in primitive functions. */
4408 void
4409 cxx_init_decl_processing (void)
4411 tree void_ftype;
4412 tree void_ftype_ptr;
4414 /* Create all the identifiers we need. */
4415 initialize_predefined_identifiers ();
4417 /* Create the global variables. */
4418 push_to_top_level ();
4420 current_function_decl = NULL_TREE;
4421 current_binding_level = NULL;
4422 /* Enter the global namespace. */
4423 gcc_assert (global_namespace == NULL_TREE);
4424 global_namespace = build_lang_decl (NAMESPACE_DECL, global_identifier,
4425 void_type_node);
4426 TREE_PUBLIC (global_namespace) = true;
4427 DECL_MODULE_EXPORT_P (global_namespace) = true;
4428 DECL_CONTEXT (global_namespace)
4429 = build_translation_unit_decl (get_identifier (main_input_filename));
4430 /* Remember whether we want the empty class passing ABI change warning
4431 in this TU. */
4432 TRANSLATION_UNIT_WARN_EMPTY_P (DECL_CONTEXT (global_namespace))
4433 = warn_abi && abi_version_crosses (12);
4434 debug_hooks->register_main_translation_unit
4435 (DECL_CONTEXT (global_namespace));
4436 begin_scope (sk_namespace, global_namespace);
4437 current_namespace = global_namespace;
4439 if (flag_visibility_ms_compat)
4440 default_visibility = VISIBILITY_HIDDEN;
4442 /* Initially, C. */
4443 current_lang_name = lang_name_c;
4445 /* Create the `std' namespace. */
4446 push_namespace (get_identifier ("std"));
4447 std_node = current_namespace;
4448 pop_namespace ();
4450 flag_noexcept_type = (cxx_dialect >= cxx17);
4452 c_common_nodes_and_builtins ();
4454 tree bool_ftype = build_function_type_list (boolean_type_node, NULL_TREE);
4455 tree decl
4456 = add_builtin_function ("__builtin_is_constant_evaluated",
4457 bool_ftype, CP_BUILT_IN_IS_CONSTANT_EVALUATED,
4458 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4459 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4461 tree cptr_ftype = build_function_type_list (const_ptr_type_node, NULL_TREE);
4462 decl = add_builtin_function ("__builtin_source_location",
4463 cptr_ftype, CP_BUILT_IN_SOURCE_LOCATION,
4464 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4465 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4467 tree bool_vaftype = build_varargs_function_type_list (boolean_type_node,
4468 NULL_TREE);
4469 decl
4470 = add_builtin_function ("__builtin_is_corresponding_member",
4471 bool_vaftype,
4472 CP_BUILT_IN_IS_CORRESPONDING_MEMBER,
4473 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4474 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4476 decl
4477 = add_builtin_function ("__builtin_is_pointer_interconvertible_with_class",
4478 bool_vaftype,
4479 CP_BUILT_IN_IS_POINTER_INTERCONVERTIBLE_WITH_CLASS,
4480 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4481 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4483 integer_two_node = build_int_cst (NULL_TREE, 2);
4485 /* Guess at the initial static decls size. */
4486 vec_alloc (static_decls, 500);
4488 /* ... and keyed classes. */
4489 vec_alloc (keyed_classes, 100);
4491 record_builtin_type (RID_BOOL, "bool", boolean_type_node);
4492 truthvalue_type_node = boolean_type_node;
4493 truthvalue_false_node = boolean_false_node;
4494 truthvalue_true_node = boolean_true_node;
4496 empty_except_spec = build_tree_list (NULL_TREE, NULL_TREE);
4497 noexcept_true_spec = build_tree_list (boolean_true_node, NULL_TREE);
4498 noexcept_false_spec = build_tree_list (boolean_false_node, NULL_TREE);
4499 noexcept_deferred_spec = build_tree_list (make_node (DEFERRED_NOEXCEPT),
4500 NULL_TREE);
4502 #if 0
4503 record_builtin_type (RID_MAX, NULL, string_type_node);
4504 #endif
4506 delta_type_node = ptrdiff_type_node;
4507 vtable_index_type = ptrdiff_type_node;
4509 vtt_parm_type = build_pointer_type (const_ptr_type_node);
4510 void_ftype = build_function_type_list (void_type_node, NULL_TREE);
4511 void_ftype_ptr = build_function_type_list (void_type_node,
4512 ptr_type_node, NULL_TREE);
4513 void_ftype_ptr
4514 = build_exception_variant (void_ftype_ptr, empty_except_spec);
4516 /* Create the conversion operator marker. This operator's DECL_NAME
4517 is in the identifier table, so we can use identifier equality to
4518 find it. */
4519 conv_op_marker = build_lang_decl (FUNCTION_DECL, conv_op_identifier,
4520 void_ftype);
4522 /* C++ extensions */
4524 unknown_type_node = make_node (LANG_TYPE);
4525 record_unknown_type (unknown_type_node, "unknown type");
4527 /* Indirecting an UNKNOWN_TYPE node yields an UNKNOWN_TYPE node. */
4528 TREE_TYPE (unknown_type_node) = unknown_type_node;
4530 /* Looking up TYPE_POINTER_TO and TYPE_REFERENCE_TO yield the same
4531 result. */
4532 TYPE_POINTER_TO (unknown_type_node) = unknown_type_node;
4533 TYPE_REFERENCE_TO (unknown_type_node) = unknown_type_node;
4535 init_list_type_node = make_node (LANG_TYPE);
4536 record_unknown_type (init_list_type_node, "init list");
4538 /* Used when parsing to distinguish parameter-lists () and (void). */
4539 explicit_void_list_node = build_void_list_node ();
4542 /* Make sure we get a unique function type, so we can give
4543 its pointer type a name. (This wins for gdb.) */
4544 tree vfunc_type = make_node (FUNCTION_TYPE);
4545 TREE_TYPE (vfunc_type) = integer_type_node;
4546 TYPE_ARG_TYPES (vfunc_type) = NULL_TREE;
4547 layout_type (vfunc_type);
4549 vtable_entry_type = build_pointer_type (vfunc_type);
4551 record_builtin_type (RID_MAX, "__vtbl_ptr_type", vtable_entry_type);
4553 vtbl_type_node
4554 = build_cplus_array_type (vtable_entry_type, NULL_TREE);
4555 layout_type (vtbl_type_node);
4556 vtbl_type_node = cp_build_qualified_type (vtbl_type_node, TYPE_QUAL_CONST);
4557 record_builtin_type (RID_MAX, NULL, vtbl_type_node);
4558 vtbl_ptr_type_node = build_pointer_type (vtable_entry_type);
4559 layout_type (vtbl_ptr_type_node);
4560 record_builtin_type (RID_MAX, NULL, vtbl_ptr_type_node);
4562 push_namespace (get_identifier ("__cxxabiv1"));
4563 abi_node = current_namespace;
4564 pop_namespace ();
4566 any_targ_node = make_node (LANG_TYPE);
4567 record_unknown_type (any_targ_node, "any type");
4569 /* Now, C++. */
4570 current_lang_name = lang_name_cplusplus;
4572 if (aligned_new_threshold > 1
4573 && !pow2p_hwi (aligned_new_threshold))
4575 error ("%<-faligned-new=%d%> is not a power of two",
4576 aligned_new_threshold);
4577 aligned_new_threshold = 1;
4579 if (aligned_new_threshold == -1)
4580 aligned_new_threshold = (cxx_dialect >= cxx17) ? 1 : 0;
4581 if (aligned_new_threshold == 1)
4582 aligned_new_threshold = malloc_alignment () / BITS_PER_UNIT;
4585 tree newattrs, extvisattr;
4586 tree newtype, deltype;
4587 tree ptr_ftype_sizetype;
4588 tree new_eh_spec;
4590 ptr_ftype_sizetype
4591 = build_function_type_list (ptr_type_node, size_type_node, NULL_TREE);
4592 if (cxx_dialect == cxx98)
4594 tree bad_alloc_id;
4595 tree bad_alloc_type_node;
4596 tree bad_alloc_decl;
4598 push_nested_namespace (std_node);
4599 bad_alloc_id = get_identifier ("bad_alloc");
4600 bad_alloc_type_node = make_class_type (RECORD_TYPE);
4601 TYPE_CONTEXT (bad_alloc_type_node) = current_namespace;
4602 bad_alloc_decl
4603 = create_implicit_typedef (bad_alloc_id, bad_alloc_type_node);
4604 DECL_CONTEXT (bad_alloc_decl) = current_namespace;
4605 pop_nested_namespace (std_node);
4607 new_eh_spec
4608 = add_exception_specifier (NULL_TREE, bad_alloc_type_node, -1);
4610 else
4611 new_eh_spec = noexcept_false_spec;
4613 /* Ensure attribs.c is initialized. */
4614 init_attributes ();
4616 extvisattr = build_tree_list (get_identifier ("externally_visible"),
4617 NULL_TREE);
4618 newattrs = tree_cons (get_identifier ("alloc_size"),
4619 build_tree_list (NULL_TREE, integer_one_node),
4620 extvisattr);
4621 newtype = cp_build_type_attribute_variant (ptr_ftype_sizetype, newattrs);
4622 newtype = build_exception_variant (newtype, new_eh_spec);
4623 deltype = cp_build_type_attribute_variant (void_ftype_ptr, extvisattr);
4624 deltype = build_exception_variant (deltype, empty_except_spec);
4625 tree opnew = push_cp_library_fn (NEW_EXPR, newtype, 0);
4626 DECL_IS_MALLOC (opnew) = 1;
4627 DECL_SET_IS_OPERATOR_NEW (opnew, true);
4628 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4629 opnew = push_cp_library_fn (VEC_NEW_EXPR, newtype, 0);
4630 DECL_IS_MALLOC (opnew) = 1;
4631 DECL_SET_IS_OPERATOR_NEW (opnew, true);
4632 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4633 tree opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4634 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4635 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4636 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4637 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4638 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4639 if (flag_sized_deallocation)
4641 /* Also push the sized deallocation variants:
4642 void operator delete(void*, std::size_t) throw();
4643 void operator delete[](void*, std::size_t) throw(); */
4644 tree void_ftype_ptr_size
4645 = build_function_type_list (void_type_node, ptr_type_node,
4646 size_type_node, NULL_TREE);
4647 deltype = cp_build_type_attribute_variant (void_ftype_ptr_size,
4648 extvisattr);
4649 deltype = build_exception_variant (deltype, empty_except_spec);
4650 opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4651 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4652 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4653 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4654 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4655 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4658 if (aligned_new_threshold)
4660 push_nested_namespace (std_node);
4661 tree align_id = get_identifier ("align_val_t");
4662 align_type_node = start_enum (align_id, NULL_TREE, size_type_node,
4663 NULL_TREE, /*scoped*/true, NULL);
4664 pop_nested_namespace (std_node);
4666 /* operator new (size_t, align_val_t); */
4667 newtype = build_function_type_list (ptr_type_node, size_type_node,
4668 align_type_node, NULL_TREE);
4669 newtype = cp_build_type_attribute_variant (newtype, newattrs);
4670 newtype = build_exception_variant (newtype, new_eh_spec);
4671 opnew = push_cp_library_fn (NEW_EXPR, newtype, 0);
4672 DECL_IS_MALLOC (opnew) = 1;
4673 DECL_SET_IS_OPERATOR_NEW (opnew, true);
4674 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4675 opnew = push_cp_library_fn (VEC_NEW_EXPR, newtype, 0);
4676 DECL_IS_MALLOC (opnew) = 1;
4677 DECL_SET_IS_OPERATOR_NEW (opnew, true);
4678 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4680 /* operator delete (void *, align_val_t); */
4681 deltype = build_function_type_list (void_type_node, ptr_type_node,
4682 align_type_node, NULL_TREE);
4683 deltype = cp_build_type_attribute_variant (deltype, extvisattr);
4684 deltype = build_exception_variant (deltype, empty_except_spec);
4685 opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4686 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4687 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4688 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4689 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4690 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4692 if (flag_sized_deallocation)
4694 /* operator delete (void *, size_t, align_val_t); */
4695 deltype = build_function_type_list (void_type_node, ptr_type_node,
4696 size_type_node, align_type_node,
4697 NULL_TREE);
4698 deltype = cp_build_type_attribute_variant (deltype, extvisattr);
4699 deltype = build_exception_variant (deltype, empty_except_spec);
4700 opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4701 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4702 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4703 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4704 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4705 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4709 nullptr_type_node = make_node (NULLPTR_TYPE);
4710 TYPE_SIZE (nullptr_type_node) = bitsize_int (GET_MODE_BITSIZE (ptr_mode));
4711 TYPE_SIZE_UNIT (nullptr_type_node) = size_int (GET_MODE_SIZE (ptr_mode));
4712 TYPE_UNSIGNED (nullptr_type_node) = 1;
4713 TYPE_PRECISION (nullptr_type_node) = GET_MODE_BITSIZE (ptr_mode);
4714 if (abi_version_at_least (9))
4715 SET_TYPE_ALIGN (nullptr_type_node, GET_MODE_ALIGNMENT (ptr_mode));
4716 SET_TYPE_MODE (nullptr_type_node, ptr_mode);
4717 record_builtin_type (RID_MAX, "decltype(nullptr)", nullptr_type_node);
4718 nullptr_node = build_int_cst (nullptr_type_node, 0);
4721 abort_fndecl
4722 = build_library_fn_ptr ("__cxa_pure_virtual", void_ftype,
4723 ECF_NORETURN | ECF_NOTHROW | ECF_COLD);
4724 if (flag_weak)
4725 /* If no definition is available, resolve references to NULL. */
4726 declare_weak (abort_fndecl);
4728 /* Perform other language dependent initializations. */
4729 init_class_processing ();
4730 init_rtti_processing ();
4731 init_template_processing ();
4733 if (flag_exceptions)
4734 init_exception_processing ();
4736 if (! supports_one_only ())
4737 flag_weak = 0;
4739 if (modules_p ())
4740 init_modules (parse_in);
4742 make_fname_decl = cp_make_fname_decl;
4743 start_fname_decls ();
4745 /* Show we use EH for cleanups. */
4746 if (flag_exceptions)
4747 using_eh_for_cleanups ();
4749 /* Check that the hardware interference sizes are at least
4750 alignof(max_align_t), as required by the standard. */
4751 const int max_align = max_align_t_align () / BITS_PER_UNIT;
4752 if (OPTION_SET_P (param_destruct_interfere_size))
4754 if (param_destruct_interfere_size < max_align)
4755 error ("%<--param destructive-interference-size=%d%> is less than "
4756 "%d", param_destruct_interfere_size, max_align);
4757 else if (param_destruct_interfere_size < param_l1_cache_line_size)
4758 warning (OPT_Winterference_size,
4759 "%<--param destructive-interference-size=%d%> "
4760 "is less than %<--param l1-cache-line-size=%d%>",
4761 param_destruct_interfere_size, param_l1_cache_line_size);
4763 else if (param_destruct_interfere_size)
4764 /* Assume the internal value is OK. */;
4765 else if (param_l1_cache_line_size >= max_align)
4766 param_destruct_interfere_size = param_l1_cache_line_size;
4767 /* else leave it unset. */
4769 if (OPTION_SET_P (param_construct_interfere_size))
4771 if (param_construct_interfere_size < max_align)
4772 error ("%<--param constructive-interference-size=%d%> is less than "
4773 "%d", param_construct_interfere_size, max_align);
4774 else if (param_construct_interfere_size > param_l1_cache_line_size
4775 && param_l1_cache_line_size >= max_align)
4776 warning (OPT_Winterference_size,
4777 "%<--param constructive-interference-size=%d%> "
4778 "is greater than %<--param l1-cache-line-size=%d%>",
4779 param_construct_interfere_size, param_l1_cache_line_size);
4781 else if (param_construct_interfere_size)
4782 /* Assume the internal value is OK. */;
4783 else if (param_l1_cache_line_size >= max_align)
4784 param_construct_interfere_size = param_l1_cache_line_size;
4787 /* Enter an abi node in global-module context. returns a cookie to
4788 give to pop_abi_namespace. */
4790 unsigned
4791 push_abi_namespace (tree node)
4793 push_nested_namespace (node);
4794 push_visibility ("default", 2);
4795 unsigned flags = module_kind;
4796 module_kind = 0;
4797 return flags;
4800 /* Pop an abi namespace, FLAGS is the cookie push_abi_namespace gave
4801 you. */
4803 void
4804 pop_abi_namespace (unsigned flags, tree node)
4806 module_kind = flags;
4807 pop_visibility (2);
4808 pop_nested_namespace (node);
4811 /* Create the VAR_DECL for __FUNCTION__ etc. ID is the name to give
4812 the decl, LOC is the location to give the decl, NAME is the
4813 initialization string and TYPE_DEP indicates whether NAME depended
4814 on the type of the function. We make use of that to detect
4815 __PRETTY_FUNCTION__ inside a template fn. This is being done lazily
4816 at the point of first use, so we mustn't push the decl now. */
4818 static tree
4819 cp_make_fname_decl (location_t loc, tree id, int type_dep)
4821 tree domain = NULL_TREE;
4822 tree init = NULL_TREE;
4824 if (!(type_dep && in_template_function ()))
4826 const char *name = NULL;
4827 bool release_name = false;
4829 if (current_function_decl == NULL_TREE)
4830 name = "top level";
4831 else if (type_dep == 0)
4833 /* __FUNCTION__ */
4834 name = fname_as_string (type_dep);
4835 release_name = true;
4837 else
4839 /* __PRETTY_FUNCTION__ */
4840 gcc_checking_assert (type_dep == 1);
4841 name = cxx_printable_name (current_function_decl, 2);
4844 size_t length = strlen (name);
4845 domain = build_index_type (size_int (length));
4846 init = build_string (length + 1, name);
4847 if (release_name)
4848 free (const_cast<char *> (name));
4851 tree type = cp_build_qualified_type (char_type_node, TYPE_QUAL_CONST);
4852 type = build_cplus_array_type (type, domain);
4854 if (init)
4855 TREE_TYPE (init) = type;
4856 else
4857 init = error_mark_node;
4859 tree decl = build_decl (loc, VAR_DECL, id, type);
4861 TREE_READONLY (decl) = 1;
4862 DECL_ARTIFICIAL (decl) = 1;
4863 DECL_DECLARED_CONSTEXPR_P (decl) = 1;
4864 TREE_STATIC (decl) = 1;
4866 TREE_USED (decl) = 1;
4868 SET_DECL_VALUE_EXPR (decl, init);
4869 DECL_HAS_VALUE_EXPR_P (decl) = 1;
4870 /* For decl_constant_var_p. */
4871 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = 1;
4873 if (current_function_decl)
4875 DECL_CONTEXT (decl) = current_function_decl;
4876 decl = pushdecl_outermost_localscope (decl);
4877 if (decl != error_mark_node)
4878 add_decl_expr (decl);
4880 else
4882 DECL_THIS_STATIC (decl) = true;
4883 decl = pushdecl_top_level_and_finish (decl, NULL_TREE);
4886 return decl;
4889 /* Install DECL as a builtin function at current global scope. Return
4890 the new decl (if we found an existing version). Also installs it
4891 into ::std, if it's not '_*'. */
4893 tree
4894 cxx_builtin_function (tree decl)
4896 retrofit_lang_decl (decl);
4898 DECL_ARTIFICIAL (decl) = 1;
4899 SET_DECL_LANGUAGE (decl, lang_c);
4900 /* Runtime library routines are, by definition, available in an
4901 external shared object. */
4902 DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
4903 DECL_VISIBILITY_SPECIFIED (decl) = 1;
4905 tree id = DECL_NAME (decl);
4906 const char *name = IDENTIFIER_POINTER (id);
4907 bool hiding = false;
4908 if (name[0] != '_' || name[1] != '_')
4909 /* In the user's namespace, it must be declared before use. */
4910 hiding = true;
4911 else if (IDENTIFIER_LENGTH (id) > strlen ("___chk")
4912 && !startswith (name + 2, "builtin_")
4913 && 0 == memcmp (name + IDENTIFIER_LENGTH (id) - strlen ("_chk"),
4914 "_chk", strlen ("_chk") + 1))
4915 /* Treat __*_chk fortification functions as anticipated as well,
4916 unless they are __builtin_*_chk. */
4917 hiding = true;
4919 /* All builtins that don't begin with an '_' should additionally
4920 go in the 'std' namespace. */
4921 if (name[0] != '_')
4923 tree std_decl = copy_decl (decl);
4925 push_nested_namespace (std_node);
4926 DECL_CONTEXT (std_decl) = FROB_CONTEXT (std_node);
4927 pushdecl (std_decl, hiding);
4928 pop_nested_namespace (std_node);
4931 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4932 decl = pushdecl (decl, hiding);
4934 return decl;
4937 /* Like cxx_builtin_function, but guarantee the function is added to the global
4938 scope. This is to allow function specific options to add new machine
4939 dependent builtins when the target ISA changes via attribute((target(...)))
4940 which saves space on program startup if the program does not use non-generic
4941 ISAs. */
4943 tree
4944 cxx_builtin_function_ext_scope (tree decl)
4946 push_nested_namespace (global_namespace);
4947 decl = cxx_builtin_function (decl);
4948 pop_nested_namespace (global_namespace);
4950 return decl;
4953 /* Implement LANG_HOOKS_SIMULATE_BUILTIN_FUNCTION_DECL. */
4955 tree
4956 cxx_simulate_builtin_function_decl (tree decl)
4958 retrofit_lang_decl (decl);
4960 DECL_ARTIFICIAL (decl) = 1;
4961 SET_DECL_LANGUAGE (decl, lang_cplusplus);
4962 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4963 return pushdecl (decl);
4966 /* Generate a FUNCTION_DECL with the typical flags for a runtime library
4967 function. Not called directly. */
4969 static tree
4970 build_library_fn (tree name, enum tree_code operator_code, tree type,
4971 int ecf_flags)
4973 tree fn = build_lang_decl (FUNCTION_DECL, name, type);
4974 DECL_EXTERNAL (fn) = 1;
4975 TREE_PUBLIC (fn) = 1;
4976 DECL_ARTIFICIAL (fn) = 1;
4977 DECL_OVERLOADED_OPERATOR_CODE_RAW (fn)
4978 = OVL_OP_INFO (false, operator_code)->ovl_op_code;
4979 SET_DECL_LANGUAGE (fn, lang_c);
4980 /* Runtime library routines are, by definition, available in an
4981 external shared object. */
4982 DECL_VISIBILITY (fn) = VISIBILITY_DEFAULT;
4983 DECL_VISIBILITY_SPECIFIED (fn) = 1;
4984 set_call_expr_flags (fn, ecf_flags);
4985 return fn;
4988 /* Returns the _DECL for a library function with C++ linkage. */
4990 static tree
4991 build_cp_library_fn (tree name, enum tree_code operator_code, tree type,
4992 int ecf_flags)
4994 tree fn = build_library_fn (name, operator_code, type, ecf_flags);
4995 DECL_CONTEXT (fn) = FROB_CONTEXT (current_namespace);
4996 SET_DECL_LANGUAGE (fn, lang_cplusplus);
4997 return fn;
5000 /* Like build_library_fn, but takes a C string instead of an
5001 IDENTIFIER_NODE. */
5003 tree
5004 build_library_fn_ptr (const char* name, tree type, int ecf_flags)
5006 return build_library_fn (get_identifier (name), ERROR_MARK, type, ecf_flags);
5009 /* Like build_cp_library_fn, but takes a C string instead of an
5010 IDENTIFIER_NODE. */
5012 tree
5013 build_cp_library_fn_ptr (const char* name, tree type, int ecf_flags)
5015 return build_cp_library_fn (get_identifier (name), ERROR_MARK, type,
5016 ecf_flags);
5019 /* Like build_library_fn, but also pushes the function so that we will
5020 be able to find it via get_global_binding. Also, the function
5021 may throw exceptions listed in RAISES. */
5023 tree
5024 push_library_fn (tree name, tree type, tree raises, int ecf_flags)
5026 if (raises)
5027 type = build_exception_variant (type, raises);
5029 tree fn = build_library_fn (name, ERROR_MARK, type, ecf_flags);
5030 return pushdecl_top_level (fn);
5033 /* Like build_cp_library_fn, but also pushes the function so that it
5034 will be found by normal lookup. */
5036 static tree
5037 push_cp_library_fn (enum tree_code operator_code, tree type,
5038 int ecf_flags)
5040 tree fn = build_cp_library_fn (ovl_op_identifier (false, operator_code),
5041 operator_code, type, ecf_flags);
5042 pushdecl (fn);
5043 if (flag_tm)
5044 apply_tm_attr (fn, get_identifier ("transaction_safe"));
5045 return fn;
5048 /* Like push_library_fn, but also note that this function throws
5049 and does not return. Used for __throw_foo and the like. */
5051 tree
5052 push_throw_library_fn (tree name, tree type)
5054 tree fn = push_library_fn (name, type, NULL_TREE, ECF_NORETURN | ECF_COLD);
5055 return fn;
5058 /* When we call finish_struct for an anonymous union, we create
5059 default copy constructors and such. But, an anonymous union
5060 shouldn't have such things; this function undoes the damage to the
5061 anonymous union type T.
5063 (The reason that we create the synthesized methods is that we don't
5064 distinguish `union { int i; }' from `typedef union { int i; } U'.
5065 The first is an anonymous union; the second is just an ordinary
5066 union type.) */
5068 void
5069 fixup_anonymous_aggr (tree t)
5071 /* Wipe out memory of synthesized methods. */
5072 TYPE_HAS_USER_CONSTRUCTOR (t) = 0;
5073 TYPE_HAS_DEFAULT_CONSTRUCTOR (t) = 0;
5074 TYPE_HAS_COPY_CTOR (t) = 0;
5075 TYPE_HAS_CONST_COPY_CTOR (t) = 0;
5076 TYPE_HAS_COPY_ASSIGN (t) = 0;
5077 TYPE_HAS_CONST_COPY_ASSIGN (t) = 0;
5079 /* Splice the implicitly generated functions out of TYPE_FIELDS and diagnose
5080 invalid members. */
5081 for (tree probe, *prev_p = &TYPE_FIELDS (t); (probe = *prev_p);)
5083 if (TREE_CODE (probe) == FUNCTION_DECL && DECL_ARTIFICIAL (probe))
5084 *prev_p = DECL_CHAIN (probe);
5085 else
5086 prev_p = &DECL_CHAIN (probe);
5088 if (DECL_ARTIFICIAL (probe)
5089 && (!DECL_IMPLICIT_TYPEDEF_P (probe)
5090 || TYPE_ANON_P (TREE_TYPE (probe))))
5091 continue;
5093 if (TREE_CODE (probe) != FIELD_DECL
5094 || (TREE_PRIVATE (probe) || TREE_PROTECTED (probe)))
5096 /* We already complained about static data members in
5097 finish_static_data_member_decl. */
5098 if (!VAR_P (probe))
5100 auto_diagnostic_group d;
5101 if (permerror (DECL_SOURCE_LOCATION (probe),
5102 TREE_CODE (t) == UNION_TYPE
5103 ? "%q#D invalid; an anonymous union may "
5104 "only have public non-static data members"
5105 : "%q#D invalid; an anonymous struct may "
5106 "only have public non-static data members", probe))
5108 static bool hint;
5109 if (flag_permissive && !hint)
5111 hint = true;
5112 inform (DECL_SOURCE_LOCATION (probe),
5113 "this flexibility is deprecated and will be "
5114 "removed");
5121 /* Splice all functions out of CLASSTYPE_MEMBER_VEC. */
5122 vec<tree,va_gc>* vec = CLASSTYPE_MEMBER_VEC (t);
5123 unsigned store = 0;
5124 for (tree elt : vec)
5125 if (!is_overloaded_fn (elt))
5126 (*vec)[store++] = elt;
5127 vec_safe_truncate (vec, store);
5129 /* Wipe RTTI info. */
5130 CLASSTYPE_TYPEINFO_VAR (t) = NULL_TREE;
5132 /* Anonymous aggregates cannot have fields with ctors, dtors or complex
5133 assignment operators (because they cannot have these methods themselves).
5134 For anonymous unions this is already checked because they are not allowed
5135 in any union, otherwise we have to check it. */
5136 if (TREE_CODE (t) != UNION_TYPE)
5138 tree field, type;
5140 if (BINFO_N_BASE_BINFOS (TYPE_BINFO (t)))
5142 error_at (location_of (t), "anonymous struct with base classes");
5143 /* Avoid ICE after error on anon-struct9.C. */
5144 TYPE_NEEDS_CONSTRUCTING (t) = false;
5147 for (field = TYPE_FIELDS (t); field; field = DECL_CHAIN (field))
5148 if (TREE_CODE (field) == FIELD_DECL)
5150 type = TREE_TYPE (field);
5151 if (CLASS_TYPE_P (type))
5153 if (TYPE_NEEDS_CONSTRUCTING (type))
5154 error ("member %q+#D with constructor not allowed "
5155 "in anonymous aggregate", field);
5156 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
5157 error ("member %q+#D with destructor not allowed "
5158 "in anonymous aggregate", field);
5159 if (TYPE_HAS_COMPLEX_COPY_ASSIGN (type))
5160 error ("member %q+#D with copy assignment operator "
5161 "not allowed in anonymous aggregate", field);
5167 /* Warn for an attribute located at LOCATION that appertains to the
5168 class type CLASS_TYPE that has not been properly placed after its
5169 class-key, in it class-specifier. */
5171 void
5172 warn_misplaced_attr_for_class_type (location_t location,
5173 tree class_type)
5175 gcc_assert (OVERLOAD_TYPE_P (class_type));
5177 auto_diagnostic_group d;
5178 if (warning_at (location, OPT_Wattributes,
5179 "attribute ignored in declaration "
5180 "of %q#T", class_type))
5181 inform (location,
5182 "attribute for %q#T must follow the %qs keyword",
5183 class_type, class_key_or_enum_as_string (class_type));
5186 /* Returns the cv-qualifiers that apply to the type specified
5187 by the DECLSPECS. */
5189 static int
5190 get_type_quals (const cp_decl_specifier_seq *declspecs)
5192 int type_quals = TYPE_UNQUALIFIED;
5194 if (decl_spec_seq_has_spec_p (declspecs, ds_const))
5195 type_quals |= TYPE_QUAL_CONST;
5196 if (decl_spec_seq_has_spec_p (declspecs, ds_volatile))
5197 type_quals |= TYPE_QUAL_VOLATILE;
5198 if (decl_spec_seq_has_spec_p (declspecs, ds_restrict))
5199 type_quals |= TYPE_QUAL_RESTRICT;
5201 return type_quals;
5204 /* Make sure that a declaration with no declarator is well-formed, i.e.
5205 just declares a tagged type or anonymous union.
5207 Returns the type declared; or NULL_TREE if none. */
5209 tree
5210 check_tag_decl (cp_decl_specifier_seq *declspecs,
5211 bool explicit_type_instantiation_p)
5213 int saw_friend = decl_spec_seq_has_spec_p (declspecs, ds_friend);
5214 int saw_typedef = decl_spec_seq_has_spec_p (declspecs, ds_typedef);
5215 /* If a class, struct, or enum type is declared by the DECLSPECS
5216 (i.e, if a class-specifier, enum-specifier, or non-typename
5217 elaborated-type-specifier appears in the DECLSPECS),
5218 DECLARED_TYPE is set to the corresponding type. */
5219 tree declared_type = NULL_TREE;
5220 bool error_p = false;
5222 if (declspecs->multiple_types_p)
5223 error_at (smallest_type_location (declspecs),
5224 "multiple types in one declaration");
5225 else if (declspecs->redefined_builtin_type)
5227 location_t loc = declspecs->locations[ds_redefined_builtin_type_spec];
5228 if (!in_system_header_at (loc))
5229 permerror (loc, "redeclaration of C++ built-in type %qT",
5230 declspecs->redefined_builtin_type);
5231 return NULL_TREE;
5234 if (declspecs->type
5235 && TYPE_P (declspecs->type)
5236 && ((TREE_CODE (declspecs->type) != TYPENAME_TYPE
5237 && MAYBE_CLASS_TYPE_P (declspecs->type))
5238 || TREE_CODE (declspecs->type) == ENUMERAL_TYPE))
5239 declared_type = declspecs->type;
5240 else if (declspecs->type == error_mark_node)
5241 error_p = true;
5243 if (type_uses_auto (declared_type))
5245 error_at (declspecs->locations[ds_type_spec],
5246 "%<auto%> can only be specified for variables "
5247 "or function declarations");
5248 return error_mark_node;
5251 if (declared_type && !OVERLOAD_TYPE_P (declared_type))
5252 declared_type = NULL_TREE;
5254 if (!declared_type && !saw_friend && !error_p)
5255 permerror (input_location, "declaration does not declare anything");
5256 /* Check for an anonymous union. */
5257 else if (declared_type && RECORD_OR_UNION_CODE_P (TREE_CODE (declared_type))
5258 && TYPE_UNNAMED_P (declared_type))
5260 /* 7/3 In a simple-declaration, the optional init-declarator-list
5261 can be omitted only when declaring a class (clause 9) or
5262 enumeration (7.2), that is, when the decl-specifier-seq contains
5263 either a class-specifier, an elaborated-type-specifier with
5264 a class-key (9.1), or an enum-specifier. In these cases and
5265 whenever a class-specifier or enum-specifier is present in the
5266 decl-specifier-seq, the identifiers in these specifiers are among
5267 the names being declared by the declaration (as class-name,
5268 enum-names, or enumerators, depending on the syntax). In such
5269 cases, and except for the declaration of an unnamed bit-field (9.6),
5270 the decl-specifier-seq shall introduce one or more names into the
5271 program, or shall redeclare a name introduced by a previous
5272 declaration. [Example:
5273 enum { }; // ill-formed
5274 typedef class { }; // ill-formed
5275 --end example] */
5276 if (saw_typedef)
5278 error_at (declspecs->locations[ds_typedef],
5279 "missing type-name in typedef-declaration");
5280 return NULL_TREE;
5282 /* Anonymous unions are objects, so they can have specifiers. */;
5283 SET_ANON_AGGR_TYPE_P (declared_type);
5285 if (TREE_CODE (declared_type) != UNION_TYPE)
5286 pedwarn (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (declared_type)),
5287 OPT_Wpedantic, "ISO C++ prohibits anonymous structs");
5290 else
5292 if (decl_spec_seq_has_spec_p (declspecs, ds_inline))
5293 error_at (declspecs->locations[ds_inline],
5294 "%<inline%> can only be specified for functions");
5295 else if (decl_spec_seq_has_spec_p (declspecs, ds_virtual))
5296 error_at (declspecs->locations[ds_virtual],
5297 "%<virtual%> can only be specified for functions");
5298 else if (saw_friend
5299 && (!current_class_type
5300 || current_scope () != current_class_type))
5301 error_at (declspecs->locations[ds_friend],
5302 "%<friend%> can only be specified inside a class");
5303 else if (decl_spec_seq_has_spec_p (declspecs, ds_explicit))
5304 error_at (declspecs->locations[ds_explicit],
5305 "%<explicit%> can only be specified for constructors");
5306 else if (declspecs->storage_class)
5307 error_at (declspecs->locations[ds_storage_class],
5308 "a storage class can only be specified for objects "
5309 "and functions");
5310 else if (decl_spec_seq_has_spec_p (declspecs, ds_const))
5311 error_at (declspecs->locations[ds_const],
5312 "%<const%> can only be specified for objects and "
5313 "functions");
5314 else if (decl_spec_seq_has_spec_p (declspecs, ds_volatile))
5315 error_at (declspecs->locations[ds_volatile],
5316 "%<volatile%> can only be specified for objects and "
5317 "functions");
5318 else if (decl_spec_seq_has_spec_p (declspecs, ds_restrict))
5319 error_at (declspecs->locations[ds_restrict],
5320 "%<__restrict%> can only be specified for objects and "
5321 "functions");
5322 else if (decl_spec_seq_has_spec_p (declspecs, ds_thread))
5323 error_at (declspecs->locations[ds_thread],
5324 "%<__thread%> can only be specified for objects "
5325 "and functions");
5326 else if (saw_typedef)
5327 warning_at (declspecs->locations[ds_typedef], 0,
5328 "%<typedef%> was ignored in this declaration");
5329 else if (decl_spec_seq_has_spec_p (declspecs, ds_constexpr))
5330 error_at (declspecs->locations[ds_constexpr],
5331 "%qs cannot be used for type declarations", "constexpr");
5332 else if (decl_spec_seq_has_spec_p (declspecs, ds_constinit))
5333 error_at (declspecs->locations[ds_constinit],
5334 "%qs cannot be used for type declarations", "constinit");
5335 else if (decl_spec_seq_has_spec_p (declspecs, ds_consteval))
5336 error_at (declspecs->locations[ds_consteval],
5337 "%qs cannot be used for type declarations", "consteval");
5340 if (declspecs->attributes && warn_attributes && declared_type)
5342 location_t loc;
5343 if (!CLASS_TYPE_P (declared_type)
5344 || !CLASSTYPE_TEMPLATE_INSTANTIATION (declared_type))
5345 /* For a non-template class, use the name location. */
5346 loc = location_of (declared_type);
5347 else
5348 /* For a template class (an explicit instantiation), use the
5349 current location. */
5350 loc = input_location;
5352 if (explicit_type_instantiation_p)
5353 /* [dcl.attr.grammar]/4:
5355 No attribute-specifier-seq shall appertain to an explicit
5356 instantiation. */
5358 if (warning_at (loc, OPT_Wattributes,
5359 "attribute ignored in explicit instantiation %q#T",
5360 declared_type))
5361 inform (loc,
5362 "no attribute can be applied to "
5363 "an explicit instantiation");
5365 else
5366 warn_misplaced_attr_for_class_type (loc, declared_type);
5369 return declared_type;
5372 /* Called when a declaration is seen that contains no names to declare.
5373 If its type is a reference to a structure, union or enum inherited
5374 from a containing scope, shadow that tag name for the current scope
5375 with a forward reference.
5376 If its type defines a new named structure or union
5377 or defines an enum, it is valid but we need not do anything here.
5378 Otherwise, it is an error.
5380 C++: may have to grok the declspecs to learn about static,
5381 complain for anonymous unions.
5383 Returns the TYPE declared -- or NULL_TREE if none. */
5385 tree
5386 shadow_tag (cp_decl_specifier_seq *declspecs)
5388 tree t = check_tag_decl (declspecs,
5389 /*explicit_type_instantiation_p=*/false);
5391 if (!t)
5392 return NULL_TREE;
5394 if (maybe_process_partial_specialization (t) == error_mark_node)
5395 return NULL_TREE;
5397 /* This is where the variables in an anonymous union are
5398 declared. An anonymous union declaration looks like:
5399 union { ... } ;
5400 because there is no declarator after the union, the parser
5401 sends that declaration here. */
5402 if (ANON_AGGR_TYPE_P (t))
5404 fixup_anonymous_aggr (t);
5406 if (TYPE_FIELDS (t))
5408 tree decl = grokdeclarator (/*declarator=*/NULL,
5409 declspecs, NORMAL, 0, NULL);
5410 finish_anon_union (decl);
5414 return t;
5417 /* Decode a "typename", such as "int **", returning a ..._TYPE node. */
5419 tree
5420 groktypename (cp_decl_specifier_seq *type_specifiers,
5421 const cp_declarator *declarator,
5422 bool is_template_arg)
5424 tree attrs;
5425 tree type;
5426 enum decl_context context
5427 = is_template_arg ? TEMPLATE_TYPE_ARG : TYPENAME;
5428 attrs = type_specifiers->attributes;
5429 type_specifiers->attributes = NULL_TREE;
5430 type = grokdeclarator (declarator, type_specifiers, context, 0, &attrs);
5431 if (attrs && type != error_mark_node)
5433 if (CLASS_TYPE_P (type))
5434 warning (OPT_Wattributes, "ignoring attributes applied to class type %qT "
5435 "outside of definition", type);
5436 else if (MAYBE_CLASS_TYPE_P (type))
5437 /* A template type parameter or other dependent type. */
5438 warning (OPT_Wattributes, "ignoring attributes applied to dependent "
5439 "type %qT without an associated declaration", type);
5440 else
5441 cplus_decl_attributes (&type, attrs, 0);
5443 return type;
5446 /* Process a DECLARATOR for a function-scope or namespace-scope
5447 variable or function declaration.
5448 (Function definitions go through start_function; class member
5449 declarations appearing in the body of the class go through
5450 grokfield.) The DECL corresponding to the DECLARATOR is returned.
5451 If an error occurs, the error_mark_node is returned instead.
5453 DECLSPECS are the decl-specifiers for the declaration. INITIALIZED is
5454 SD_INITIALIZED if an explicit initializer is present, or SD_DEFAULTED
5455 for an explicitly defaulted function, or SD_DELETED for an explicitly
5456 deleted function, but 0 (SD_UNINITIALIZED) if this is a variable
5457 implicitly initialized via a default constructor. It can also be
5458 SD_DECOMPOSITION which behaves much like SD_INITIALIZED, but we also
5459 mark the new decl as DECL_DECOMPOSITION_P.
5461 ATTRIBUTES and PREFIX_ATTRIBUTES are GNU attributes associated with this
5462 declaration.
5464 The scope represented by the context of the returned DECL is pushed
5465 (if it is not the global namespace) and is assigned to
5466 *PUSHED_SCOPE_P. The caller is then responsible for calling
5467 pop_scope on *PUSHED_SCOPE_P if it is set. */
5469 tree
5470 start_decl (const cp_declarator *declarator,
5471 cp_decl_specifier_seq *declspecs,
5472 int initialized,
5473 tree attributes,
5474 tree prefix_attributes,
5475 tree *pushed_scope_p)
5477 tree decl;
5478 tree context;
5479 bool was_public;
5480 int flags;
5481 bool alias;
5482 tree initial;
5484 *pushed_scope_p = NULL_TREE;
5486 attributes = chainon (attributes, prefix_attributes);
5488 decl = grokdeclarator (declarator, declspecs, NORMAL, initialized,
5489 &attributes);
5491 if (decl == NULL_TREE || VOID_TYPE_P (decl)
5492 || decl == error_mark_node)
5493 return error_mark_node;
5495 context = CP_DECL_CONTEXT (decl);
5496 if (context != global_namespace)
5497 *pushed_scope_p = push_scope (context);
5499 if (initialized && TREE_CODE (decl) == TYPE_DECL)
5501 error_at (DECL_SOURCE_LOCATION (decl),
5502 "typedef %qD is initialized (use %qs instead)",
5503 decl, "decltype");
5504 return error_mark_node;
5507 /* Save the DECL_INITIAL value in case it gets clobbered to assist
5508 with attribute validation. */
5509 initial = DECL_INITIAL (decl);
5511 if (initialized)
5513 if (! toplevel_bindings_p ()
5514 && DECL_EXTERNAL (decl))
5515 warning (0, "declaration of %q#D has %<extern%> and is initialized",
5516 decl);
5517 DECL_EXTERNAL (decl) = 0;
5518 if (toplevel_bindings_p ())
5519 TREE_STATIC (decl) = 1;
5520 /* Tell 'cplus_decl_attributes' this is an initialized decl,
5521 even though we might not yet have the initializer expression. */
5522 if (!DECL_INITIAL (decl))
5523 DECL_INITIAL (decl) = error_mark_node;
5525 alias = lookup_attribute ("alias", DECL_ATTRIBUTES (decl)) != 0;
5527 if (alias && TREE_CODE (decl) == FUNCTION_DECL)
5528 record_key_method_defined (decl);
5530 /* If this is a typedef that names the class for linkage purposes
5531 (7.1.3p8), apply any attributes directly to the type. */
5532 if (TREE_CODE (decl) == TYPE_DECL
5533 && OVERLOAD_TYPE_P (TREE_TYPE (decl))
5534 && decl == TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (decl))))
5535 flags = ATTR_FLAG_TYPE_IN_PLACE;
5536 else
5537 flags = 0;
5539 /* Set attributes here so if duplicate decl, will have proper attributes. */
5540 cplus_decl_attributes (&decl, attributes, flags);
5542 /* Restore the original DECL_INITIAL that we may have clobbered earlier to
5543 assist with attribute validation. */
5544 DECL_INITIAL (decl) = initial;
5546 /* Dllimported symbols cannot be defined. Static data members (which
5547 can be initialized in-class and dllimported) go through grokfield,
5548 not here, so we don't need to exclude those decls when checking for
5549 a definition. */
5550 if (initialized && DECL_DLLIMPORT_P (decl))
5552 error_at (DECL_SOURCE_LOCATION (decl),
5553 "definition of %q#D is marked %<dllimport%>", decl);
5554 DECL_DLLIMPORT_P (decl) = 0;
5557 /* If #pragma weak was used, mark the decl weak now. */
5558 if (!processing_template_decl && !DECL_DECOMPOSITION_P (decl))
5559 maybe_apply_pragma_weak (decl);
5561 if (TREE_CODE (decl) == FUNCTION_DECL
5562 && DECL_DECLARED_INLINE_P (decl)
5563 && DECL_UNINLINABLE (decl)
5564 && lookup_attribute ("noinline", DECL_ATTRIBUTES (decl)))
5565 warning_at (DECL_SOURCE_LOCATION (decl), 0,
5566 "inline function %qD given attribute %qs", decl, "noinline");
5568 if (TYPE_P (context) && COMPLETE_TYPE_P (complete_type (context)))
5570 bool this_tmpl = (current_template_depth
5571 > template_class_depth (context));
5572 if (VAR_P (decl))
5574 tree field = lookup_field (context, DECL_NAME (decl), 0, false);
5575 if (field == NULL_TREE
5576 || !(VAR_P (field) || variable_template_p (field)))
5577 error ("%q+#D is not a static data member of %q#T", decl, context);
5578 else if (variable_template_p (field)
5579 && (DECL_LANG_SPECIFIC (decl)
5580 && DECL_TEMPLATE_SPECIALIZATION (decl)))
5581 /* OK, specialization was already checked. */;
5582 else if (variable_template_p (field) && !this_tmpl)
5584 error_at (DECL_SOURCE_LOCATION (decl),
5585 "non-member-template declaration of %qD", decl);
5586 inform (DECL_SOURCE_LOCATION (field), "does not match "
5587 "member template declaration here");
5588 return error_mark_node;
5590 else
5592 if (variable_template_p (field))
5593 field = DECL_TEMPLATE_RESULT (field);
5595 if (DECL_CONTEXT (field) != context)
5597 if (!same_type_p (DECL_CONTEXT (field), context))
5598 permerror (input_location, "ISO C++ does not permit %<%T::%D%> "
5599 "to be defined as %<%T::%D%>",
5600 DECL_CONTEXT (field), DECL_NAME (decl),
5601 context, DECL_NAME (decl));
5602 DECL_CONTEXT (decl) = DECL_CONTEXT (field);
5604 /* Static data member are tricky; an in-class initialization
5605 still doesn't provide a definition, so the in-class
5606 declaration will have DECL_EXTERNAL set, but will have an
5607 initialization. Thus, duplicate_decls won't warn
5608 about this situation, and so we check here. */
5609 if (initialized && DECL_INITIALIZED_IN_CLASS_P (field))
5610 error ("duplicate initialization of %qD", decl);
5611 field = duplicate_decls (decl, field);
5612 if (field == error_mark_node)
5613 return error_mark_node;
5614 else if (field)
5615 decl = field;
5618 else
5620 tree field = check_classfn (context, decl,
5621 this_tmpl
5622 ? current_template_parms
5623 : NULL_TREE);
5624 if (field && field != error_mark_node
5625 && duplicate_decls (decl, field))
5626 decl = field;
5629 /* cp_finish_decl sets DECL_EXTERNAL if DECL_IN_AGGR_P is set. */
5630 DECL_IN_AGGR_P (decl) = 0;
5631 /* Do not mark DECL as an explicit specialization if it was not
5632 already marked as an instantiation; a declaration should
5633 never be marked as a specialization unless we know what
5634 template is being specialized. */
5635 if (DECL_LANG_SPECIFIC (decl) && DECL_USE_TEMPLATE (decl))
5637 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
5638 if (TREE_CODE (decl) == FUNCTION_DECL)
5639 DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
5640 && DECL_DECLARED_INLINE_P (decl));
5641 else
5642 DECL_COMDAT (decl) = false;
5644 /* [temp.expl.spec] An explicit specialization of a static data
5645 member of a template is a definition if the declaration
5646 includes an initializer; otherwise, it is a declaration.
5648 We check for processing_specialization so this only applies
5649 to the new specialization syntax. */
5650 if (!initialized && processing_specialization)
5651 DECL_EXTERNAL (decl) = 1;
5654 if (DECL_EXTERNAL (decl) && ! DECL_TEMPLATE_SPECIALIZATION (decl)
5655 /* Aliases are definitions. */
5656 && !alias)
5657 permerror (declarator->id_loc,
5658 "declaration of %q#D outside of class is not definition",
5659 decl);
5662 /* Create a DECL_LANG_SPECIFIC so that DECL_DECOMPOSITION_P works. */
5663 if (initialized == SD_DECOMPOSITION)
5664 fit_decomposition_lang_decl (decl, NULL_TREE);
5666 was_public = TREE_PUBLIC (decl);
5668 if ((DECL_EXTERNAL (decl) || TREE_CODE (decl) == FUNCTION_DECL)
5669 && current_function_decl)
5671 /* A function-scope decl of some namespace-scope decl. */
5672 DECL_LOCAL_DECL_P (decl) = true;
5673 if (named_module_purview_p ())
5674 error_at (declarator->id_loc,
5675 "block-scope extern declaration %q#D not permitted"
5676 " in module purview", decl);
5679 /* Enter this declaration into the symbol table. Don't push the plain
5680 VAR_DECL for a variable template. */
5681 if (!template_parm_scope_p ()
5682 || !VAR_P (decl))
5683 decl = maybe_push_decl (decl);
5685 if (processing_template_decl)
5686 decl = push_template_decl (decl);
5688 if (decl == error_mark_node)
5689 return error_mark_node;
5691 if (VAR_P (decl)
5692 && DECL_NAMESPACE_SCOPE_P (decl) && !TREE_PUBLIC (decl) && !was_public
5693 && !DECL_THIS_STATIC (decl) && !DECL_ARTIFICIAL (decl)
5694 /* But not templated variables. */
5695 && !(DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)))
5697 /* This is a const variable with implicit 'static'. Set
5698 DECL_THIS_STATIC so we can tell it from variables that are
5699 !TREE_PUBLIC because of the anonymous namespace. */
5700 gcc_assert (CP_TYPE_CONST_P (TREE_TYPE (decl)) || errorcount);
5701 DECL_THIS_STATIC (decl) = 1;
5704 if (current_function_decl && VAR_P (decl)
5705 && DECL_DECLARED_CONSTEXPR_P (current_function_decl)
5706 && cxx_dialect < cxx23)
5708 bool ok = false;
5709 if (CP_DECL_THREAD_LOCAL_P (decl))
5710 error_at (DECL_SOURCE_LOCATION (decl),
5711 "%qD declared %<thread_local%> in %qs function only "
5712 "available with %<-std=c++2b%> or %<-std=gnu++2b%>", decl,
5713 DECL_IMMEDIATE_FUNCTION_P (current_function_decl)
5714 ? "consteval" : "constexpr");
5715 else if (TREE_STATIC (decl))
5716 error_at (DECL_SOURCE_LOCATION (decl),
5717 "%qD declared %<static%> in %qs function only available "
5718 "with %<-std=c++2b%> or %<-std=gnu++2b%>", decl,
5719 DECL_IMMEDIATE_FUNCTION_P (current_function_decl)
5720 ? "consteval" : "constexpr");
5721 else
5722 ok = true;
5723 if (!ok)
5724 cp_function_chain->invalid_constexpr = true;
5727 if (!processing_template_decl && VAR_P (decl))
5728 start_decl_1 (decl, initialized);
5730 return decl;
5733 /* Process the declaration of a variable DECL. INITIALIZED is true
5734 iff DECL is explicitly initialized. (INITIALIZED is false if the
5735 variable is initialized via an implicitly-called constructor.)
5736 This function must be called for ordinary variables (including, for
5737 example, implicit instantiations of templates), but must not be
5738 called for template declarations. */
5740 void
5741 start_decl_1 (tree decl, bool initialized)
5743 gcc_checking_assert (!processing_template_decl);
5745 if (error_operand_p (decl))
5746 return;
5748 gcc_checking_assert (VAR_P (decl));
5750 tree type = TREE_TYPE (decl);
5751 bool complete_p = COMPLETE_TYPE_P (type);
5752 bool aggregate_definition_p
5753 = MAYBE_CLASS_TYPE_P (type) && !DECL_EXTERNAL (decl);
5755 /* If an explicit initializer is present, or if this is a definition
5756 of an aggregate, then we need a complete type at this point.
5757 (Scalars are always complete types, so there is nothing to
5758 check.) This code just sets COMPLETE_P; errors (if necessary)
5759 are issued below. */
5760 if ((initialized || aggregate_definition_p)
5761 && !complete_p
5762 && COMPLETE_TYPE_P (complete_type (type)))
5764 complete_p = true;
5765 /* We will not yet have set TREE_READONLY on DECL if the type
5766 was "const", but incomplete, before this point. But, now, we
5767 have a complete type, so we can try again. */
5768 cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
5771 if (initialized)
5772 /* Is it valid for this decl to have an initializer at all? */
5774 /* Don't allow initializations for incomplete types except for
5775 arrays which might be completed by the initialization. */
5776 if (complete_p)
5777 ; /* A complete type is ok. */
5778 else if (type_uses_auto (type))
5779 ; /* An auto type is ok. */
5780 else if (TREE_CODE (type) != ARRAY_TYPE)
5782 error ("variable %q#D has initializer but incomplete type", decl);
5783 type = TREE_TYPE (decl) = error_mark_node;
5785 else if (!COMPLETE_TYPE_P (complete_type (TREE_TYPE (type))))
5787 if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
5788 error ("elements of array %q#D have incomplete type", decl);
5789 /* else we already gave an error in start_decl. */
5792 else if (aggregate_definition_p && !complete_p)
5794 if (type_uses_auto (type))
5795 gcc_assert (CLASS_PLACEHOLDER_TEMPLATE (type));
5796 else
5798 error ("aggregate %q#D has incomplete type and cannot be defined",
5799 decl);
5800 /* Change the type so that assemble_variable will give
5801 DECL an rtl we can live with: (mem (const_int 0)). */
5802 type = TREE_TYPE (decl) = error_mark_node;
5806 /* Create a new scope to hold this declaration if necessary.
5807 Whether or not a new scope is necessary cannot be determined
5808 until after the type has been completed; if the type is a
5809 specialization of a class template it is not until after
5810 instantiation has occurred that TYPE_HAS_NONTRIVIAL_DESTRUCTOR
5811 will be set correctly. */
5812 maybe_push_cleanup_level (type);
5815 /* Given a parenthesized list of values INIT, create a CONSTRUCTOR to handle
5816 C++20 P0960. TYPE is the type of the object we're initializing. */
5818 tree
5819 do_aggregate_paren_init (tree init, tree type)
5821 tree val = TREE_VALUE (init);
5823 if (TREE_CHAIN (init) == NULL_TREE)
5825 /* If the list has a single element and it's a string literal,
5826 then it's the initializer for the array as a whole. */
5827 if (TREE_CODE (type) == ARRAY_TYPE
5828 && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type)))
5829 && TREE_CODE (tree_strip_any_location_wrapper (val))
5830 == STRING_CST)
5831 return val;
5832 /* Handle non-standard extensions like compound literals. This also
5833 prevents triggering aggregate parenthesized-initialization in
5834 compiler-generated code for =default. */
5835 else if (same_type_ignoring_top_level_qualifiers_p (type,
5836 TREE_TYPE (val)))
5837 return val;
5840 init = build_constructor_from_list (init_list_type_node, init);
5841 CONSTRUCTOR_IS_DIRECT_INIT (init) = true;
5842 CONSTRUCTOR_IS_PAREN_INIT (init) = true;
5843 return init;
5846 /* Handle initialization of references. DECL, TYPE, and INIT have the
5847 same meaning as in cp_finish_decl. *CLEANUP must be NULL on entry,
5848 but will be set to a new CLEANUP_STMT if a temporary is created
5849 that must be destroyed subsequently.
5851 Returns an initializer expression to use to initialize DECL, or
5852 NULL if the initialization can be performed statically.
5854 Quotes on semantics can be found in ARM 8.4.3. */
5856 static tree
5857 grok_reference_init (tree decl, tree type, tree init, int flags)
5859 if (init == NULL_TREE)
5861 if ((DECL_LANG_SPECIFIC (decl) == 0
5862 || DECL_IN_AGGR_P (decl) == 0)
5863 && ! DECL_THIS_EXTERN (decl))
5864 error_at (DECL_SOURCE_LOCATION (decl),
5865 "%qD declared as reference but not initialized", decl);
5866 return NULL_TREE;
5869 tree ttype = TREE_TYPE (type);
5870 if (TREE_CODE (init) == TREE_LIST)
5872 /* This handles (C++20 only) code like
5874 const A& r(1, 2, 3);
5876 where we treat the parenthesized list as a CONSTRUCTOR. */
5877 if (TREE_TYPE (init) == NULL_TREE
5878 && CP_AGGREGATE_TYPE_P (ttype)
5879 && !DECL_DECOMPOSITION_P (decl)
5880 && (cxx_dialect >= cxx20))
5882 /* We don't know yet if we should treat const A& r(1) as
5883 const A& r{1}. */
5884 if (list_length (init) == 1)
5886 flags |= LOOKUP_AGGREGATE_PAREN_INIT;
5887 init = build_x_compound_expr_from_list (init, ELK_INIT,
5888 tf_warning_or_error);
5890 /* If the list had more than one element, the code is ill-formed
5891 pre-C++20, so we can build a constructor right away. */
5892 else
5893 init = do_aggregate_paren_init (init, ttype);
5895 else
5896 init = build_x_compound_expr_from_list (init, ELK_INIT,
5897 tf_warning_or_error);
5900 if (TREE_CODE (ttype) != ARRAY_TYPE
5901 && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
5902 /* Note: default conversion is only called in very special cases. */
5903 init = decay_conversion (init, tf_warning_or_error);
5905 /* check_initializer handles this for non-reference variables, but for
5906 references we need to do it here or the initializer will get the
5907 incomplete array type and confuse later calls to
5908 cp_complete_array_type. */
5909 if (TREE_CODE (ttype) == ARRAY_TYPE
5910 && TYPE_DOMAIN (ttype) == NULL_TREE
5911 && (BRACE_ENCLOSED_INITIALIZER_P (init)
5912 || TREE_CODE (init) == STRING_CST))
5914 cp_complete_array_type (&ttype, init, false);
5915 if (ttype != TREE_TYPE (type))
5916 type = cp_build_reference_type (ttype, TYPE_REF_IS_RVALUE (type));
5919 /* Convert INIT to the reference type TYPE. This may involve the
5920 creation of a temporary, whose lifetime must be the same as that
5921 of the reference. If so, a DECL_EXPR for the temporary will be
5922 added just after the DECL_EXPR for DECL. That's why we don't set
5923 DECL_INITIAL for local references (instead assigning to them
5924 explicitly); we need to allow the temporary to be initialized
5925 first. */
5926 return initialize_reference (type, init, flags,
5927 tf_warning_or_error);
5930 /* Designated initializers in arrays are not supported in GNU C++.
5931 The parser cannot detect this error since it does not know whether
5932 a given brace-enclosed initializer is for a class type or for an
5933 array. This function checks that CE does not use a designated
5934 initializer. If it does, an error is issued. Returns true if CE
5935 is valid, i.e., does not have a designated initializer. */
5937 bool
5938 check_array_designated_initializer (constructor_elt *ce,
5939 unsigned HOST_WIDE_INT index)
5941 /* Designated initializers for array elements are not supported. */
5942 if (ce->index)
5944 /* The parser only allows identifiers as designated
5945 initializers. */
5946 if (ce->index == error_mark_node)
5948 error ("name used in a GNU-style designated "
5949 "initializer for an array");
5950 return false;
5952 else if (identifier_p (ce->index))
5954 error ("name %qD used in a GNU-style designated "
5955 "initializer for an array", ce->index);
5956 return false;
5959 tree ce_index = build_expr_type_conversion (WANT_INT | WANT_ENUM,
5960 ce->index, true);
5961 if (ce_index
5962 && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (ce_index))
5963 && (TREE_CODE (ce_index = fold_non_dependent_expr (ce_index))
5964 == INTEGER_CST))
5966 /* A C99 designator is OK if it matches the current index. */
5967 if (wi::to_wide (ce_index) == index)
5969 ce->index = ce_index;
5970 return true;
5972 else
5973 sorry ("non-trivial designated initializers not supported");
5975 else
5976 error_at (cp_expr_loc_or_input_loc (ce->index),
5977 "C99 designator %qE is not an integral constant-expression",
5978 ce->index);
5980 return false;
5983 return true;
5986 /* When parsing `int a[] = {1, 2};' we don't know the size of the
5987 array until we finish parsing the initializer. If that's the
5988 situation we're in, update DECL accordingly. */
5990 static void
5991 maybe_deduce_size_from_array_init (tree decl, tree init)
5993 tree type = TREE_TYPE (decl);
5995 if (TREE_CODE (type) == ARRAY_TYPE
5996 && TYPE_DOMAIN (type) == NULL_TREE
5997 && TREE_CODE (decl) != TYPE_DECL)
5999 /* do_default is really a C-ism to deal with tentative definitions.
6000 But let's leave it here to ease the eventual merge. */
6001 int do_default = !DECL_EXTERNAL (decl);
6002 tree initializer = init ? init : DECL_INITIAL (decl);
6003 int failure = 0;
6005 /* Check that there are no designated initializers in INIT, as
6006 those are not supported in GNU C++, and as the middle-end
6007 will crash if presented with a non-numeric designated
6008 initializer. */
6009 if (initializer && BRACE_ENCLOSED_INITIALIZER_P (initializer))
6011 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (initializer);
6012 constructor_elt *ce;
6013 HOST_WIDE_INT i;
6014 FOR_EACH_VEC_SAFE_ELT (v, i, ce)
6016 if (instantiation_dependent_expression_p (ce->index))
6017 return;
6018 if (!check_array_designated_initializer (ce, i))
6019 failure = 1;
6023 if (failure)
6024 TREE_TYPE (decl) = error_mark_node;
6025 else
6027 failure = cp_complete_array_type (&TREE_TYPE (decl), initializer,
6028 do_default);
6029 if (failure == 1)
6031 error_at (cp_expr_loc_or_loc (initializer,
6032 DECL_SOURCE_LOCATION (decl)),
6033 "initializer fails to determine size of %qD", decl);
6035 else if (failure == 2)
6037 if (do_default)
6039 error_at (DECL_SOURCE_LOCATION (decl),
6040 "array size missing in %qD", decl);
6042 /* If a `static' var's size isn't known, make it extern as
6043 well as static, so it does not get allocated. If it's not
6044 `static', then don't mark it extern; finish_incomplete_decl
6045 will give it a default size and it will get allocated. */
6046 else if (!pedantic && TREE_STATIC (decl) && !TREE_PUBLIC (decl))
6047 DECL_EXTERNAL (decl) = 1;
6049 else if (failure == 3)
6051 error_at (DECL_SOURCE_LOCATION (decl),
6052 "zero-size array %qD", decl);
6056 cp_apply_type_quals_to_decl (cp_type_quals (TREE_TYPE (decl)), decl);
6058 relayout_decl (decl);
6062 /* Set DECL_SIZE, DECL_ALIGN, etc. for DECL (a VAR_DECL), and issue
6063 any appropriate error messages regarding the layout. */
6065 static void
6066 layout_var_decl (tree decl)
6068 tree type;
6070 type = TREE_TYPE (decl);
6071 if (type == error_mark_node)
6072 return;
6074 /* If we haven't already laid out this declaration, do so now.
6075 Note that we must not call complete type for an external object
6076 because it's type might involve templates that we are not
6077 supposed to instantiate yet. (And it's perfectly valid to say
6078 `extern X x' for some incomplete type `X'.) */
6079 if (!DECL_EXTERNAL (decl))
6080 complete_type (type);
6081 if (!DECL_SIZE (decl)
6082 && TREE_TYPE (decl) != error_mark_node
6083 && complete_or_array_type_p (type))
6084 layout_decl (decl, 0);
6086 if (!DECL_EXTERNAL (decl) && DECL_SIZE (decl) == NULL_TREE)
6088 /* An automatic variable with an incomplete type: that is an error.
6089 Don't talk about array types here, since we took care of that
6090 message in grokdeclarator. */
6091 error_at (DECL_SOURCE_LOCATION (decl),
6092 "storage size of %qD isn%'t known", decl);
6093 TREE_TYPE (decl) = error_mark_node;
6095 #if 0
6096 /* Keep this code around in case we later want to control debug info
6097 based on whether a type is "used". (jason 1999-11-11) */
6099 else if (!DECL_EXTERNAL (decl) && MAYBE_CLASS_TYPE_P (ttype))
6100 /* Let debugger know it should output info for this type. */
6101 note_debug_info_needed (ttype);
6103 if (TREE_STATIC (decl) && DECL_CLASS_SCOPE_P (decl))
6104 note_debug_info_needed (DECL_CONTEXT (decl));
6105 #endif
6107 if ((DECL_EXTERNAL (decl) || TREE_STATIC (decl))
6108 && DECL_SIZE (decl) != NULL_TREE
6109 && ! TREE_CONSTANT (DECL_SIZE (decl)))
6111 if (TREE_CODE (DECL_SIZE (decl)) == INTEGER_CST
6112 && !DECL_LOCAL_DECL_P (decl))
6113 constant_expression_warning (DECL_SIZE (decl));
6114 else
6116 error_at (DECL_SOURCE_LOCATION (decl),
6117 "storage size of %qD isn%'t constant", decl);
6118 TREE_TYPE (decl) = error_mark_node;
6119 type = error_mark_node;
6123 /* If the final element initializes a flexible array field, add the size of
6124 that initializer to DECL's size. */
6125 if (type != error_mark_node
6126 && DECL_INITIAL (decl)
6127 && TREE_CODE (DECL_INITIAL (decl)) == CONSTRUCTOR
6128 && !vec_safe_is_empty (CONSTRUCTOR_ELTS (DECL_INITIAL (decl)))
6129 && DECL_SIZE (decl) != NULL_TREE
6130 && TREE_CODE (DECL_SIZE (decl)) == INTEGER_CST
6131 && TYPE_SIZE (type) != NULL_TREE
6132 && TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST
6133 && tree_int_cst_equal (DECL_SIZE (decl), TYPE_SIZE (type)))
6135 constructor_elt &elt = CONSTRUCTOR_ELTS (DECL_INITIAL (decl))->last ();
6136 if (elt.index)
6138 tree itype = TREE_TYPE (elt.index);
6139 tree vtype = TREE_TYPE (elt.value);
6140 if (TREE_CODE (itype) == ARRAY_TYPE
6141 && TYPE_DOMAIN (itype) == NULL
6142 && TREE_CODE (vtype) == ARRAY_TYPE
6143 && COMPLETE_TYPE_P (vtype))
6145 DECL_SIZE (decl)
6146 = size_binop (PLUS_EXPR, DECL_SIZE (decl), TYPE_SIZE (vtype));
6147 DECL_SIZE_UNIT (decl)
6148 = size_binop (PLUS_EXPR, DECL_SIZE_UNIT (decl),
6149 TYPE_SIZE_UNIT (vtype));
6155 /* If a local static variable is declared in an inline function, or if
6156 we have a weak definition, we must endeavor to create only one
6157 instance of the variable at link-time. */
6159 void
6160 maybe_commonize_var (tree decl)
6162 /* Don't mess with __FUNCTION__ and similar. */
6163 if (DECL_ARTIFICIAL (decl))
6164 return;
6166 /* Static data in a function with comdat linkage also has comdat
6167 linkage. */
6168 if ((TREE_STATIC (decl)
6169 && DECL_FUNCTION_SCOPE_P (decl)
6170 && vague_linkage_p (DECL_CONTEXT (decl)))
6171 || (TREE_PUBLIC (decl) && DECL_INLINE_VAR_P (decl)))
6173 if (flag_weak)
6175 /* With weak symbols, we simply make the variable COMDAT;
6176 that will cause copies in multiple translations units to
6177 be merged. */
6178 comdat_linkage (decl);
6180 else
6182 if (DECL_INITIAL (decl) == NULL_TREE
6183 || DECL_INITIAL (decl) == error_mark_node)
6185 /* Without weak symbols, we can use COMMON to merge
6186 uninitialized variables. */
6187 TREE_PUBLIC (decl) = 1;
6188 DECL_COMMON (decl) = 1;
6190 else
6192 /* While for initialized variables, we must use internal
6193 linkage -- which means that multiple copies will not
6194 be merged. */
6195 TREE_PUBLIC (decl) = 0;
6196 DECL_COMMON (decl) = 0;
6197 DECL_INTERFACE_KNOWN (decl) = 1;
6198 const char *msg;
6199 if (DECL_INLINE_VAR_P (decl))
6200 msg = G_("sorry: semantics of inline variable "
6201 "%q#D are wrong (you%'ll wind up with "
6202 "multiple copies)");
6203 else
6204 msg = G_("sorry: semantics of inline function "
6205 "static data %q#D are wrong (you%'ll wind "
6206 "up with multiple copies)");
6207 if (warning_at (DECL_SOURCE_LOCATION (decl), 0,
6208 msg, decl))
6209 inform (DECL_SOURCE_LOCATION (decl),
6210 "you can work around this by removing the initializer");
6216 /* Issue an error message if DECL is an uninitialized const variable.
6217 CONSTEXPR_CONTEXT_P is true when the function is called in a constexpr
6218 context from potential_constant_expression. Returns true if all is well,
6219 false otherwise. */
6221 bool
6222 check_for_uninitialized_const_var (tree decl, bool constexpr_context_p,
6223 tsubst_flags_t complain)
6225 tree type = strip_array_types (TREE_TYPE (decl));
6227 /* ``Unless explicitly declared extern, a const object does not have
6228 external linkage and must be initialized. ($8.4; $12.1)'' ARM
6229 7.1.6 */
6230 if (VAR_P (decl)
6231 && !TYPE_REF_P (type)
6232 && (CP_TYPE_CONST_P (type)
6233 /* C++20 permits trivial default initialization in constexpr
6234 context (P1331R2). */
6235 || (cxx_dialect < cxx20
6236 && (constexpr_context_p
6237 || var_in_constexpr_fn (decl))))
6238 && !DECL_NONTRIVIALLY_INITIALIZED_P (decl))
6240 tree field = default_init_uninitialized_part (type);
6241 if (!field)
6242 return true;
6244 bool show_notes = true;
6246 if (!constexpr_context_p || cxx_dialect >= cxx20)
6248 if (CP_TYPE_CONST_P (type))
6250 if (complain & tf_error)
6251 show_notes = permerror (DECL_SOURCE_LOCATION (decl),
6252 "uninitialized %<const %D%>", decl);
6254 else
6256 if (!is_instantiation_of_constexpr (current_function_decl)
6257 && (complain & tf_error))
6258 error_at (DECL_SOURCE_LOCATION (decl),
6259 "uninitialized variable %qD in %<constexpr%> "
6260 "function", decl);
6261 else
6262 show_notes = false;
6263 cp_function_chain->invalid_constexpr = true;
6266 else if (complain & tf_error)
6267 error_at (DECL_SOURCE_LOCATION (decl),
6268 "uninitialized variable %qD in %<constexpr%> context",
6269 decl);
6271 if (show_notes && CLASS_TYPE_P (type) && (complain & tf_error))
6273 tree defaulted_ctor;
6275 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)),
6276 "%q#T has no user-provided default constructor", type);
6277 defaulted_ctor = in_class_defaulted_default_constructor (type);
6278 if (defaulted_ctor)
6279 inform (DECL_SOURCE_LOCATION (defaulted_ctor),
6280 "constructor is not user-provided because it is "
6281 "explicitly defaulted in the class body");
6282 inform (DECL_SOURCE_LOCATION (field),
6283 "and the implicitly-defined constructor does not "
6284 "initialize %q#D", field);
6287 return false;
6290 return true;
6293 /* Structure holding the current initializer being processed by reshape_init.
6294 CUR is a pointer to the current element being processed, END is a pointer
6295 after the last element present in the initializer. */
6296 struct reshape_iter
6298 constructor_elt *cur;
6299 constructor_elt *end;
6302 static tree reshape_init_r (tree, reshape_iter *, tree, tsubst_flags_t);
6304 /* FIELD is an element of TYPE_FIELDS or NULL. In the former case, the value
6305 returned is the next FIELD_DECL (possibly FIELD itself) that can be
6306 initialized. If there are no more such fields, the return value
6307 will be NULL. */
6309 tree
6310 next_initializable_field (tree field)
6312 while (field
6313 && (TREE_CODE (field) != FIELD_DECL
6314 || DECL_UNNAMED_BIT_FIELD (field)
6315 || (DECL_ARTIFICIAL (field)
6316 /* In C++17, don't skip base class fields. */
6317 && !(cxx_dialect >= cxx17 && DECL_FIELD_IS_BASE (field))
6318 /* Don't skip vptr fields. We might see them when we're
6319 called from reduced_constant_expression_p. */
6320 && !DECL_VIRTUAL_P (field))))
6321 field = DECL_CHAIN (field);
6323 return field;
6326 /* Return true for [dcl.init.list] direct-list-initialization from
6327 single element of enumeration with a fixed underlying type. */
6329 bool
6330 is_direct_enum_init (tree type, tree init)
6332 if (cxx_dialect >= cxx17
6333 && TREE_CODE (type) == ENUMERAL_TYPE
6334 && ENUM_FIXED_UNDERLYING_TYPE_P (type)
6335 && TREE_CODE (init) == CONSTRUCTOR
6336 && CONSTRUCTOR_IS_DIRECT_INIT (init)
6337 && CONSTRUCTOR_NELTS (init) == 1
6338 /* DR 2374: The single element needs to be implicitly
6339 convertible to the underlying type of the enum. */
6340 && can_convert_arg (ENUM_UNDERLYING_TYPE (type),
6341 TREE_TYPE (CONSTRUCTOR_ELT (init, 0)->value),
6342 CONSTRUCTOR_ELT (init, 0)->value,
6343 LOOKUP_IMPLICIT, tf_none))
6344 return true;
6345 return false;
6348 /* Subroutine of reshape_init_array and reshape_init_vector, which does
6349 the actual work. ELT_TYPE is the element type of the array. MAX_INDEX is an
6350 INTEGER_CST representing the size of the array minus one (the maximum index),
6351 or NULL_TREE if the array was declared without specifying the size. D is
6352 the iterator within the constructor. */
6354 static tree
6355 reshape_init_array_1 (tree elt_type, tree max_index, reshape_iter *d,
6356 tree first_initializer_p, tsubst_flags_t complain)
6358 tree new_init;
6359 bool sized_array_p = (max_index && TREE_CONSTANT (max_index));
6360 unsigned HOST_WIDE_INT max_index_cst = 0;
6361 unsigned HOST_WIDE_INT index;
6363 /* The initializer for an array is always a CONSTRUCTOR. If this is the
6364 outermost CONSTRUCTOR and the element type is non-aggregate, we don't need
6365 to build a new one. But don't reuse if not complaining; if this is
6366 tentative, we might also reshape to another type (95319). */
6367 bool reuse = (first_initializer_p
6368 && (complain & tf_error)
6369 && !CP_AGGREGATE_TYPE_P (elt_type)
6370 && !TREE_SIDE_EFFECTS (first_initializer_p));
6371 if (reuse)
6372 new_init = first_initializer_p;
6373 else
6374 new_init = build_constructor (init_list_type_node, NULL);
6376 if (sized_array_p)
6378 /* Minus 1 is used for zero sized arrays. */
6379 if (integer_all_onesp (max_index))
6380 return new_init;
6382 if (tree_fits_uhwi_p (max_index))
6383 max_index_cst = tree_to_uhwi (max_index);
6384 /* sizetype is sign extended, not zero extended. */
6385 else
6386 max_index_cst = tree_to_uhwi (fold_convert (size_type_node, max_index));
6389 /* Loop until there are no more initializers. */
6390 for (index = 0;
6391 d->cur != d->end && (!sized_array_p || index <= max_index_cst);
6392 ++index)
6394 tree elt_init;
6395 constructor_elt *old_cur = d->cur;
6397 check_array_designated_initializer (d->cur, index);
6398 elt_init = reshape_init_r (elt_type, d,
6399 /*first_initializer_p=*/NULL_TREE,
6400 complain);
6401 if (elt_init == error_mark_node)
6402 return error_mark_node;
6403 tree idx = size_int (index);
6404 if (reuse)
6406 old_cur->index = idx;
6407 old_cur->value = elt_init;
6409 else
6410 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init),
6411 idx, elt_init);
6412 if (!TREE_CONSTANT (elt_init))
6413 TREE_CONSTANT (new_init) = false;
6415 /* This can happen with an invalid initializer (c++/54501). */
6416 if (d->cur == old_cur && !sized_array_p)
6417 break;
6420 return new_init;
6423 /* Subroutine of reshape_init_r, processes the initializers for arrays.
6424 Parameters are the same of reshape_init_r. */
6426 static tree
6427 reshape_init_array (tree type, reshape_iter *d, tree first_initializer_p,
6428 tsubst_flags_t complain)
6430 tree max_index = NULL_TREE;
6432 gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
6434 if (TYPE_DOMAIN (type))
6435 max_index = array_type_nelts (type);
6437 return reshape_init_array_1 (TREE_TYPE (type), max_index, d,
6438 first_initializer_p, complain);
6441 /* Subroutine of reshape_init_r, processes the initializers for vectors.
6442 Parameters are the same of reshape_init_r. */
6444 static tree
6445 reshape_init_vector (tree type, reshape_iter *d, tsubst_flags_t complain)
6447 tree max_index = NULL_TREE;
6449 gcc_assert (VECTOR_TYPE_P (type));
6451 if (COMPOUND_LITERAL_P (d->cur->value))
6453 tree value = d->cur->value;
6454 if (!same_type_p (TREE_TYPE (value), type))
6456 if (complain & tf_error)
6457 error ("invalid type %qT as initializer for a vector of type %qT",
6458 TREE_TYPE (d->cur->value), type);
6459 value = error_mark_node;
6461 ++d->cur;
6462 return value;
6465 /* For a vector, we initialize it as an array of the appropriate size. */
6466 if (VECTOR_TYPE_P (type))
6467 max_index = size_int (TYPE_VECTOR_SUBPARTS (type) - 1);
6469 return reshape_init_array_1 (TREE_TYPE (type), max_index, d,
6470 NULL_TREE, complain);
6473 /* Subroutine of reshape_init_r, processes the initializers for classes
6474 or union. Parameters are the same of reshape_init_r. */
6476 static tree
6477 reshape_init_class (tree type, reshape_iter *d, bool first_initializer_p,
6478 tsubst_flags_t complain)
6480 tree field;
6481 tree new_init;
6483 gcc_assert (CLASS_TYPE_P (type));
6485 /* The initializer for a class is always a CONSTRUCTOR. */
6486 new_init = build_constructor (init_list_type_node, NULL);
6488 int binfo_idx = -1;
6489 tree binfo = TYPE_BINFO (type);
6490 tree base_binfo = NULL_TREE;
6491 if (cxx_dialect >= cxx17 && uses_template_parms (type))
6493 /* We get here from maybe_aggr_guide for C++20 class template argument
6494 deduction. In this case we need to look through the binfo because a
6495 template doesn't have base fields. */
6496 binfo_idx = 0;
6497 BINFO_BASE_ITERATE (binfo, binfo_idx, base_binfo);
6499 if (base_binfo)
6500 field = base_binfo;
6501 else
6502 field = next_initializable_field (TYPE_FIELDS (type));
6504 if (!field)
6506 /* [dcl.init.aggr]
6508 An initializer for an aggregate member that is an
6509 empty class shall have the form of an empty
6510 initializer-list {}. */
6511 if (!first_initializer_p)
6513 if (complain & tf_error)
6514 error ("initializer for %qT must be brace-enclosed", type);
6515 return error_mark_node;
6517 return new_init;
6520 /* For C++20 CTAD, handle pack expansions in the base list. */
6521 tree last_was_pack_expansion = NULL_TREE;
6523 /* Loop through the initializable fields, gathering initializers. */
6524 while (d->cur != d->end)
6526 tree field_init;
6527 constructor_elt *old_cur = d->cur;
6529 /* Handle designated initializers, as an extension. */
6530 if (d->cur->index)
6532 if (d->cur->index == error_mark_node)
6533 return error_mark_node;
6535 if (TREE_CODE (d->cur->index) == FIELD_DECL)
6537 /* We already reshaped this. */
6538 if (field != d->cur->index)
6540 if (tree id = DECL_NAME (d->cur->index))
6541 gcc_checking_assert (d->cur->index
6542 == get_class_binding (type, id));
6543 field = d->cur->index;
6546 else if (TREE_CODE (d->cur->index) == IDENTIFIER_NODE)
6547 field = get_class_binding (type, d->cur->index);
6548 else
6550 if (complain & tf_error)
6551 error ("%<[%E] =%> used in a GNU-style designated initializer"
6552 " for class %qT", d->cur->index, type);
6553 return error_mark_node;
6556 if (!field || TREE_CODE (field) != FIELD_DECL)
6558 if (complain & tf_error)
6559 error ("%qT has no non-static data member named %qD", type,
6560 d->cur->index);
6561 return error_mark_node;
6564 /* If the element is an anonymous union object and the initializer
6565 list is a designated-initializer-list, the anonymous union object
6566 is initialized by the designated-initializer-list { D }, where D
6567 is the designated-initializer-clause naming a member of the
6568 anonymous union object. */
6569 tree ictx = DECL_CONTEXT (field);
6570 if (!same_type_ignoring_top_level_qualifiers_p (ictx, type))
6572 gcc_assert (ANON_AGGR_TYPE_P (ictx));
6573 /* Find the anon aggr that is a direct member of TYPE. */
6574 while (true)
6576 tree cctx = TYPE_CONTEXT (ictx);
6577 if (same_type_ignoring_top_level_qualifiers_p (cctx, type))
6578 break;
6579 ictx = cctx;
6581 /* And then the TYPE member with that anon aggr type. */
6582 tree aafield = TYPE_FIELDS (type);
6583 for (; aafield; aafield = TREE_CHAIN (aafield))
6584 if (TREE_TYPE (aafield) == ictx)
6585 break;
6586 gcc_assert (aafield);
6587 field = aafield;
6591 /* If we processed all the member of the class, we are done. */
6592 if (!field)
6593 break;
6595 last_was_pack_expansion = (PACK_EXPANSION_P (TREE_TYPE (field))
6596 ? field : NULL_TREE);
6597 if (last_was_pack_expansion)
6598 /* Each non-trailing aggregate element that is a pack expansion is
6599 assumed to correspond to no elements of the initializer list. */
6600 goto continue_;
6602 field_init = reshape_init_r (TREE_TYPE (field), d,
6603 /*first_initializer_p=*/NULL_TREE,
6604 complain);
6605 if (field_init == error_mark_node)
6606 return error_mark_node;
6608 if (d->cur == old_cur && d->cur->index)
6610 /* This can happen with an invalid initializer for a flexible
6611 array member (c++/54441). */
6612 if (complain & tf_error)
6613 error ("invalid initializer for %q#D", field);
6614 return error_mark_node;
6617 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init), field, field_init);
6619 /* [dcl.init.aggr]
6621 When a union is initialized with a brace-enclosed
6622 initializer, the braces shall only contain an
6623 initializer for the first member of the union. */
6624 if (TREE_CODE (type) == UNION_TYPE)
6625 break;
6627 continue_:
6628 if (base_binfo)
6630 if (BINFO_BASE_ITERATE (binfo, ++binfo_idx, base_binfo))
6631 field = base_binfo;
6632 else
6633 field = next_initializable_field (TYPE_FIELDS (type));
6635 else
6636 field = next_initializable_field (DECL_CHAIN (field));
6639 /* A trailing aggregate element that is a pack expansion is assumed to
6640 correspond to all remaining elements of the initializer list (if any). */
6641 if (last_was_pack_expansion)
6643 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init),
6644 last_was_pack_expansion, d->cur->value);
6645 while (d->cur != d->end)
6646 d->cur++;
6649 return new_init;
6652 /* Subroutine of reshape_init_r. We're in a context where C99 initializer
6653 designators are not valid; either complain or return true to indicate
6654 that reshape_init_r should return error_mark_node. */
6656 static bool
6657 has_designator_problem (reshape_iter *d, tsubst_flags_t complain)
6659 if (d->cur->index)
6661 if (complain & tf_error)
6662 error_at (cp_expr_loc_or_input_loc (d->cur->index),
6663 "C99 designator %qE outside aggregate initializer",
6664 d->cur->index);
6665 else
6666 return true;
6668 return false;
6671 /* Subroutine of reshape_init, which processes a single initializer (part of
6672 a CONSTRUCTOR). TYPE is the type of the variable being initialized, D is the
6673 iterator within the CONSTRUCTOR which points to the initializer to process.
6674 If this is the first initializer of the outermost CONSTRUCTOR node,
6675 FIRST_INITIALIZER_P is that CONSTRUCTOR; otherwise, it is NULL_TREE. */
6677 static tree
6678 reshape_init_r (tree type, reshape_iter *d, tree first_initializer_p,
6679 tsubst_flags_t complain)
6681 tree init = d->cur->value;
6683 if (error_operand_p (init))
6684 return error_mark_node;
6686 if (first_initializer_p && !CP_AGGREGATE_TYPE_P (type)
6687 && has_designator_problem (d, complain))
6688 return error_mark_node;
6690 tree stripped_init = tree_strip_any_location_wrapper (init);
6692 if (TREE_CODE (type) == COMPLEX_TYPE)
6694 /* A complex type can be initialized from one or two initializers,
6695 but braces are not elided. */
6696 d->cur++;
6697 if (BRACE_ENCLOSED_INITIALIZER_P (stripped_init))
6699 if (CONSTRUCTOR_NELTS (stripped_init) > 2)
6701 if (complain & tf_error)
6702 error ("too many initializers for %qT", type);
6703 else
6704 return error_mark_node;
6707 else if (first_initializer_p && d->cur != d->end)
6709 vec<constructor_elt, va_gc> *v = 0;
6710 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, init);
6711 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, d->cur->value);
6712 if (has_designator_problem (d, complain))
6713 return error_mark_node;
6714 d->cur++;
6715 init = build_constructor (init_list_type_node, v);
6717 return init;
6720 /* A non-aggregate type is always initialized with a single
6721 initializer. */
6722 if (!CP_AGGREGATE_TYPE_P (type)
6723 /* As is an array with dependent bound, which we can see
6724 during C++20 aggregate CTAD. */
6725 || (cxx_dialect >= cxx20
6726 && TREE_CODE (type) == ARRAY_TYPE
6727 && uses_template_parms (TYPE_DOMAIN (type))))
6729 /* It is invalid to initialize a non-aggregate type with a
6730 brace-enclosed initializer before C++0x.
6731 We need to check for BRACE_ENCLOSED_INITIALIZER_P here because
6732 of g++.old-deja/g++.mike/p7626.C: a pointer-to-member constant is
6733 a CONSTRUCTOR (with a record type). */
6734 if (TREE_CODE (stripped_init) == CONSTRUCTOR
6735 /* Don't complain about a capture-init. */
6736 && !CONSTRUCTOR_IS_DIRECT_INIT (stripped_init)
6737 && BRACE_ENCLOSED_INITIALIZER_P (stripped_init)) /* p7626.C */
6739 if (SCALAR_TYPE_P (type))
6741 if (cxx_dialect < cxx11)
6743 if (complain & tf_error)
6744 error ("braces around scalar initializer for type %qT",
6745 type);
6746 init = error_mark_node;
6748 else if (first_initializer_p
6749 || (CONSTRUCTOR_NELTS (stripped_init) > 0
6750 && (BRACE_ENCLOSED_INITIALIZER_P
6751 (CONSTRUCTOR_ELT (stripped_init,0)->value))))
6753 if (complain & tf_error)
6754 error ("too many braces around scalar initializer "
6755 "for type %qT", type);
6756 init = error_mark_node;
6759 else
6760 maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
6763 d->cur++;
6764 return init;
6767 /* "If T is a class type and the initializer list has a single element of
6768 type cv U, where U is T or a class derived from T, the object is
6769 initialized from that element." Even if T is an aggregate. */
6770 if (cxx_dialect >= cxx11 && (CLASS_TYPE_P (type) || VECTOR_TYPE_P (type))
6771 && first_initializer_p
6772 /* But not if it's a designated init. */
6773 && !d->cur->index
6774 && d->end - d->cur == 1
6775 && reference_related_p (type, TREE_TYPE (init)))
6777 d->cur++;
6778 return init;
6781 /* [dcl.init.aggr]
6783 All implicit type conversions (clause _conv_) are considered when
6784 initializing the aggregate member with an initializer from an
6785 initializer-list. If the initializer can initialize a member,
6786 the member is initialized. Otherwise, if the member is itself a
6787 non-empty subaggregate, brace elision is assumed and the
6788 initializer is considered for the initialization of the first
6789 member of the subaggregate. */
6790 if ((TREE_CODE (init) != CONSTRUCTOR || COMPOUND_LITERAL_P (init))
6791 /* But don't try this for the first initializer, since that would be
6792 looking through the outermost braces; A a2 = { a1 }; is not a
6793 valid aggregate initialization. */
6794 && !first_initializer_p
6795 && (same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (init))
6796 || can_convert_arg (type, TREE_TYPE (init), init, LOOKUP_NORMAL,
6797 complain)))
6799 d->cur++;
6800 return init;
6803 /* [dcl.init.string]
6805 A char array (whether plain char, signed char, or unsigned char)
6806 can be initialized by a string-literal (optionally enclosed in
6807 braces); a wchar_t array can be initialized by a wide
6808 string-literal (optionally enclosed in braces). */
6809 if (TREE_CODE (type) == ARRAY_TYPE
6810 && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type))))
6812 tree str_init = init;
6813 tree stripped_str_init = stripped_init;
6815 /* Strip one level of braces if and only if they enclose a single
6816 element (as allowed by [dcl.init.string]). */
6817 if (!first_initializer_p
6818 && TREE_CODE (stripped_str_init) == CONSTRUCTOR
6819 && CONSTRUCTOR_NELTS (stripped_str_init) == 1)
6821 str_init = (*CONSTRUCTOR_ELTS (stripped_str_init))[0].value;
6822 stripped_str_init = tree_strip_any_location_wrapper (str_init);
6825 /* If it's a string literal, then it's the initializer for the array
6826 as a whole. Otherwise, continue with normal initialization for
6827 array types (one value per array element). */
6828 if (TREE_CODE (stripped_str_init) == STRING_CST)
6830 if (has_designator_problem (d, complain))
6831 return error_mark_node;
6832 d->cur++;
6833 return str_init;
6837 /* The following cases are about aggregates. If we are not within a full
6838 initializer already, and there is not a CONSTRUCTOR, it means that there
6839 is a missing set of braces (that is, we are processing the case for
6840 which reshape_init exists). */
6841 bool braces_elided_p = false;
6842 if (!first_initializer_p)
6844 if (TREE_CODE (stripped_init) == CONSTRUCTOR)
6846 tree init_type = TREE_TYPE (init);
6847 if (init_type && TYPE_PTRMEMFUNC_P (init_type))
6848 /* There is no need to call reshape_init for pointer-to-member
6849 function initializers, as they are always constructed correctly
6850 by the front end. Here we have e.g. {.__pfn=0B, .__delta=0},
6851 which is missing outermost braces. We should warn below, and
6852 one of the routines below will wrap it in additional { }. */;
6853 /* For a nested compound literal, proceed to specialized routines,
6854 to handle initialization of arrays and similar. */
6855 else if (COMPOUND_LITERAL_P (stripped_init))
6856 gcc_assert (!BRACE_ENCLOSED_INITIALIZER_P (stripped_init));
6857 /* A CONSTRUCTOR of the target's type is a previously
6858 digested initializer. */
6859 else if (same_type_ignoring_top_level_qualifiers_p (type, init_type))
6861 ++d->cur;
6862 return init;
6864 else
6866 /* Something that hasn't been reshaped yet. */
6867 ++d->cur;
6868 gcc_assert (BRACE_ENCLOSED_INITIALIZER_P (stripped_init));
6869 return reshape_init (type, init, complain);
6873 if (complain & tf_warning)
6874 warning (OPT_Wmissing_braces,
6875 "missing braces around initializer for %qT",
6876 type);
6877 braces_elided_p = true;
6880 /* Dispatch to specialized routines. */
6881 tree new_init;
6882 if (CLASS_TYPE_P (type))
6883 new_init = reshape_init_class (type, d, first_initializer_p, complain);
6884 else if (TREE_CODE (type) == ARRAY_TYPE)
6885 new_init = reshape_init_array (type, d, first_initializer_p, complain);
6886 else if (VECTOR_TYPE_P (type))
6887 new_init = reshape_init_vector (type, d, complain);
6888 else
6889 gcc_unreachable();
6891 if (braces_elided_p
6892 && TREE_CODE (new_init) == CONSTRUCTOR)
6893 CONSTRUCTOR_BRACES_ELIDED_P (new_init) = true;
6895 return new_init;
6898 /* Undo the brace-elision allowed by [dcl.init.aggr] in a
6899 brace-enclosed aggregate initializer.
6901 INIT is the CONSTRUCTOR containing the list of initializers describing
6902 a brace-enclosed initializer for an entity of the indicated aggregate TYPE.
6903 It may not presently match the shape of the TYPE; for example:
6905 struct S { int a; int b; };
6906 struct S a[] = { 1, 2, 3, 4 };
6908 Here INIT will hold a vector of four elements, rather than a
6909 vector of two elements, each itself a vector of two elements. This
6910 routine transforms INIT from the former form into the latter. The
6911 revised CONSTRUCTOR node is returned. */
6913 tree
6914 reshape_init (tree type, tree init, tsubst_flags_t complain)
6916 vec<constructor_elt, va_gc> *v;
6917 reshape_iter d;
6918 tree new_init;
6920 gcc_assert (BRACE_ENCLOSED_INITIALIZER_P (init));
6922 v = CONSTRUCTOR_ELTS (init);
6924 /* An empty constructor does not need reshaping, and it is always a valid
6925 initializer. */
6926 if (vec_safe_is_empty (v))
6927 return init;
6929 /* Brace elision is not performed for a CONSTRUCTOR representing
6930 parenthesized aggregate initialization. */
6931 if (CONSTRUCTOR_IS_PAREN_INIT (init))
6933 tree elt = (*v)[0].value;
6934 /* If we're initializing a char array from a string-literal that is
6935 enclosed in braces, unwrap it here. */
6936 if (TREE_CODE (type) == ARRAY_TYPE
6937 && vec_safe_length (v) == 1
6938 && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type)))
6939 && TREE_CODE (tree_strip_any_location_wrapper (elt)) == STRING_CST)
6940 return elt;
6941 return init;
6944 /* Handle [dcl.init.list] direct-list-initialization from
6945 single element of enumeration with a fixed underlying type. */
6946 if (is_direct_enum_init (type, init))
6948 tree elt = CONSTRUCTOR_ELT (init, 0)->value;
6949 type = cv_unqualified (type);
6950 if (check_narrowing (ENUM_UNDERLYING_TYPE (type), elt, complain))
6952 warning_sentinel w (warn_useless_cast);
6953 warning_sentinel w2 (warn_ignored_qualifiers);
6954 return cp_build_c_cast (input_location, type, elt,
6955 tf_warning_or_error);
6957 else
6958 return error_mark_node;
6961 /* Recurse on this CONSTRUCTOR. */
6962 d.cur = &(*v)[0];
6963 d.end = d.cur + v->length ();
6965 new_init = reshape_init_r (type, &d, init, complain);
6966 if (new_init == error_mark_node)
6967 return error_mark_node;
6969 /* Make sure all the element of the constructor were used. Otherwise,
6970 issue an error about exceeding initializers. */
6971 if (d.cur != d.end)
6973 if (complain & tf_error)
6974 error ("too many initializers for %qT", type);
6975 return error_mark_node;
6978 if (CONSTRUCTOR_IS_DIRECT_INIT (init)
6979 && BRACE_ENCLOSED_INITIALIZER_P (new_init))
6980 CONSTRUCTOR_IS_DIRECT_INIT (new_init) = true;
6981 if (CONSTRUCTOR_IS_DESIGNATED_INIT (init)
6982 && BRACE_ENCLOSED_INITIALIZER_P (new_init))
6983 CONSTRUCTOR_IS_DESIGNATED_INIT (new_init) = true;
6985 return new_init;
6988 /* Verify array initializer. Returns true if errors have been reported. */
6990 bool
6991 check_array_initializer (tree decl, tree type, tree init)
6993 tree element_type = TREE_TYPE (type);
6995 /* Structured binding when initialized with an array type needs
6996 to have complete type. */
6997 if (decl
6998 && DECL_DECOMPOSITION_P (decl)
6999 && !DECL_DECOMP_BASE (decl)
7000 && !COMPLETE_TYPE_P (type))
7002 error_at (DECL_SOURCE_LOCATION (decl),
7003 "structured binding has incomplete type %qT", type);
7004 TREE_TYPE (decl) = error_mark_node;
7005 return true;
7008 /* The array type itself need not be complete, because the
7009 initializer may tell us how many elements are in the array.
7010 But, the elements of the array must be complete. */
7011 if (!COMPLETE_TYPE_P (complete_type (element_type)))
7013 if (decl)
7014 error_at (DECL_SOURCE_LOCATION (decl),
7015 "elements of array %q#D have incomplete type", decl);
7016 else
7017 error ("elements of array %q#T have incomplete type", type);
7018 return true;
7021 location_t loc = (decl ? location_of (decl) : input_location);
7022 if (!verify_type_context (loc, TCTX_ARRAY_ELEMENT, element_type))
7023 return true;
7025 /* A compound literal can't have variable size. */
7026 if (init && !decl
7027 && ((COMPLETE_TYPE_P (type) && !TREE_CONSTANT (TYPE_SIZE (type)))
7028 || !TREE_CONSTANT (TYPE_SIZE (element_type))))
7030 error ("variable-sized compound literal");
7031 return true;
7033 return false;
7036 /* Subroutine of check_initializer; args are passed down from that function.
7037 Set stmts_are_full_exprs_p to 1 across a call to build_aggr_init. */
7039 static tree
7040 build_aggr_init_full_exprs (tree decl, tree init, int flags)
7043 gcc_assert (stmts_are_full_exprs_p ());
7044 return build_aggr_init (decl, init, flags, tf_warning_or_error);
7047 /* Verify INIT (the initializer for DECL), and record the
7048 initialization in DECL_INITIAL, if appropriate. CLEANUP is as for
7049 grok_reference_init.
7051 If the return value is non-NULL, it is an expression that must be
7052 evaluated dynamically to initialize DECL. */
7054 static tree
7055 check_initializer (tree decl, tree init, int flags, vec<tree, va_gc> **cleanups)
7057 tree type;
7058 tree init_code = NULL;
7059 tree core_type;
7061 /* Things that are going to be initialized need to have complete
7062 type. */
7063 TREE_TYPE (decl) = type = complete_type (TREE_TYPE (decl));
7065 if (DECL_HAS_VALUE_EXPR_P (decl))
7067 /* A variable with DECL_HAS_VALUE_EXPR_P set is just a placeholder,
7068 it doesn't have storage to be initialized. */
7069 gcc_assert (init == NULL_TREE);
7070 return NULL_TREE;
7073 if (type == error_mark_node)
7074 /* We will have already complained. */
7075 return NULL_TREE;
7077 if (TREE_CODE (type) == ARRAY_TYPE)
7079 if (check_array_initializer (decl, type, init))
7080 return NULL_TREE;
7082 else if (!COMPLETE_TYPE_P (type))
7084 error_at (DECL_SOURCE_LOCATION (decl),
7085 "%q#D has incomplete type", decl);
7086 TREE_TYPE (decl) = error_mark_node;
7087 return NULL_TREE;
7089 else
7090 /* There is no way to make a variable-sized class type in GNU C++. */
7091 gcc_assert (TREE_CONSTANT (TYPE_SIZE (type)));
7093 if (init && BRACE_ENCLOSED_INITIALIZER_P (init))
7095 int init_len = CONSTRUCTOR_NELTS (init);
7096 if (SCALAR_TYPE_P (type))
7098 if (init_len == 0)
7100 maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
7101 init = build_zero_init (type, NULL_TREE, false);
7103 else if (init_len != 1 && TREE_CODE (type) != COMPLEX_TYPE)
7105 error_at (cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (decl)),
7106 "scalar object %qD requires one element in "
7107 "initializer", decl);
7108 TREE_TYPE (decl) = error_mark_node;
7109 return NULL_TREE;
7114 if (TREE_CODE (decl) == CONST_DECL)
7116 gcc_assert (!TYPE_REF_P (type));
7118 DECL_INITIAL (decl) = init;
7120 gcc_assert (init != NULL_TREE);
7121 init = NULL_TREE;
7123 else if (!init && DECL_REALLY_EXTERN (decl))
7125 else if (init || type_build_ctor_call (type)
7126 || TYPE_REF_P (type))
7128 if (TYPE_REF_P (type))
7130 init = grok_reference_init (decl, type, init, flags);
7131 flags |= LOOKUP_ALREADY_DIGESTED;
7133 else if (!init)
7134 check_for_uninitialized_const_var (decl, /*constexpr_context_p=*/false,
7135 tf_warning_or_error);
7136 /* Do not reshape constructors of vectors (they don't need to be
7137 reshaped. */
7138 else if (BRACE_ENCLOSED_INITIALIZER_P (init))
7140 if (is_std_init_list (type))
7142 init = perform_implicit_conversion (type, init,
7143 tf_warning_or_error);
7144 flags |= LOOKUP_ALREADY_DIGESTED;
7146 else if (TYPE_NON_AGGREGATE_CLASS (type))
7148 /* Don't reshape if the class has constructors. */
7149 if (cxx_dialect == cxx98)
7150 error_at (cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (decl)),
7151 "in C++98 %qD must be initialized by "
7152 "constructor, not by %<{...}%>",
7153 decl);
7155 else if (VECTOR_TYPE_P (type) && TYPE_VECTOR_OPAQUE (type))
7157 error ("opaque vector types cannot be initialized");
7158 init = error_mark_node;
7160 else
7162 init = reshape_init (type, init, tf_warning_or_error);
7163 flags |= LOOKUP_NO_NARROWING;
7166 /* [dcl.init] "Otherwise, if the destination type is an array, the object
7167 is initialized as follows..." So handle things like
7169 int a[](1, 2, 3);
7171 which is permitted in C++20 by P0960. */
7172 else if (TREE_CODE (init) == TREE_LIST
7173 && TREE_TYPE (init) == NULL_TREE
7174 && TREE_CODE (type) == ARRAY_TYPE
7175 && !DECL_DECOMPOSITION_P (decl)
7176 && (cxx_dialect >= cxx20))
7177 init = do_aggregate_paren_init (init, type);
7178 else if (TREE_CODE (init) == TREE_LIST
7179 && TREE_TYPE (init) != unknown_type_node
7180 && !MAYBE_CLASS_TYPE_P (type))
7182 gcc_assert (TREE_CODE (decl) != RESULT_DECL);
7184 /* We get here with code like `int a (2);' */
7185 init = build_x_compound_expr_from_list (init, ELK_INIT,
7186 tf_warning_or_error);
7189 /* If DECL has an array type without a specific bound, deduce the
7190 array size from the initializer. */
7191 maybe_deduce_size_from_array_init (decl, init);
7192 type = TREE_TYPE (decl);
7193 if (type == error_mark_node)
7194 return NULL_TREE;
7196 if (((type_build_ctor_call (type) || CLASS_TYPE_P (type))
7197 && !(flags & LOOKUP_ALREADY_DIGESTED)
7198 && !(init && BRACE_ENCLOSED_INITIALIZER_P (init)
7199 && CP_AGGREGATE_TYPE_P (type)
7200 && (CLASS_TYPE_P (type)
7201 || !TYPE_NEEDS_CONSTRUCTING (type)
7202 || type_has_extended_temps (type))))
7203 || (DECL_DECOMPOSITION_P (decl) && TREE_CODE (type) == ARRAY_TYPE))
7205 init_code = build_aggr_init_full_exprs (decl, init, flags);
7207 /* A constructor call is a non-trivial initializer even if
7208 it isn't explicitly written. */
7209 if (TREE_SIDE_EFFECTS (init_code))
7210 DECL_NONTRIVIALLY_INITIALIZED_P (decl) = true;
7212 /* If this is a constexpr initializer, expand_default_init will
7213 have returned an INIT_EXPR rather than a CALL_EXPR. In that
7214 case, pull the initializer back out and pass it down into
7215 store_init_value. */
7216 while (true)
7218 if (TREE_CODE (init_code) == EXPR_STMT
7219 || TREE_CODE (init_code) == STMT_EXPR
7220 || TREE_CODE (init_code) == CONVERT_EXPR)
7221 init_code = TREE_OPERAND (init_code, 0);
7222 else if (TREE_CODE (init_code) == BIND_EXPR)
7223 init_code = BIND_EXPR_BODY (init_code);
7224 else
7225 break;
7227 if (TREE_CODE (init_code) == INIT_EXPR)
7229 /* In C++20, the call to build_aggr_init could have created
7230 an INIT_EXPR with a CONSTRUCTOR as the RHS to handle
7231 A(1, 2). */
7232 init = TREE_OPERAND (init_code, 1);
7233 init_code = NULL_TREE;
7234 /* Don't call digest_init; it's unnecessary and will complain
7235 about aggregate initialization of non-aggregate classes. */
7236 flags |= LOOKUP_ALREADY_DIGESTED;
7238 else if (DECL_DECLARED_CONSTEXPR_P (decl)
7239 || DECL_DECLARED_CONSTINIT_P (decl))
7241 /* Declared constexpr or constinit, but no suitable initializer;
7242 massage init appropriately so we can pass it into
7243 store_init_value for the error. */
7244 if (CLASS_TYPE_P (type)
7245 && (!init || TREE_CODE (init) == TREE_LIST))
7247 init = build_functional_cast (input_location, type,
7248 init, tf_none);
7249 if (TREE_CODE (init) == TARGET_EXPR)
7250 TARGET_EXPR_DIRECT_INIT_P (init) = true;
7252 init_code = NULL_TREE;
7254 else
7255 init = NULL_TREE;
7258 if (init && TREE_CODE (init) != TREE_VEC)
7260 /* In aggregate initialization of a variable, each element
7261 initialization is a full-expression because there is no
7262 enclosing expression. */
7263 gcc_assert (stmts_are_full_exprs_p ());
7265 init_code = store_init_value (decl, init, cleanups, flags);
7267 if (DECL_INITIAL (decl)
7268 && TREE_CODE (DECL_INITIAL (decl)) == CONSTRUCTOR
7269 && !vec_safe_is_empty (CONSTRUCTOR_ELTS (DECL_INITIAL (decl))))
7271 tree elt = CONSTRUCTOR_ELTS (DECL_INITIAL (decl))->last ().value;
7272 if (TREE_CODE (TREE_TYPE (elt)) == ARRAY_TYPE
7273 && TYPE_SIZE (TREE_TYPE (elt)) == NULL_TREE)
7274 cp_complete_array_type (&TREE_TYPE (elt), elt, false);
7277 if (pedantic && TREE_CODE (type) == ARRAY_TYPE
7278 && DECL_INITIAL (decl)
7279 && TREE_CODE (DECL_INITIAL (decl)) == STRING_CST
7280 && PAREN_STRING_LITERAL_P (DECL_INITIAL (decl)))
7281 warning_at (cp_expr_loc_or_loc (DECL_INITIAL (decl),
7282 DECL_SOURCE_LOCATION (decl)),
7283 0, "array %qD initialized by parenthesized "
7284 "string literal %qE",
7285 decl, DECL_INITIAL (decl));
7286 init = NULL_TREE;
7289 else
7291 if (CLASS_TYPE_P (core_type = strip_array_types (type))
7292 && (CLASSTYPE_READONLY_FIELDS_NEED_INIT (core_type)
7293 || CLASSTYPE_REF_FIELDS_NEED_INIT (core_type)))
7294 diagnose_uninitialized_cst_or_ref_member (core_type, /*using_new=*/false,
7295 /*complain=*/true);
7297 check_for_uninitialized_const_var (decl, /*constexpr_context_p=*/false,
7298 tf_warning_or_error);
7301 if (init && init != error_mark_node)
7302 init_code = build2 (INIT_EXPR, type, decl, init);
7304 if (init_code)
7306 /* We might have set these in cp_finish_decl. */
7307 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = false;
7308 TREE_CONSTANT (decl) = false;
7311 if (init_code
7312 && DECL_IN_AGGR_P (decl)
7313 && DECL_INITIALIZED_IN_CLASS_P (decl))
7315 static int explained = 0;
7317 if (cxx_dialect < cxx11)
7318 error ("initializer invalid for static member with constructor");
7319 else if (cxx_dialect < cxx17)
7320 error ("non-constant in-class initialization invalid for static "
7321 "member %qD", decl);
7322 else
7323 error ("non-constant in-class initialization invalid for non-inline "
7324 "static member %qD", decl);
7325 if (!explained)
7327 inform (input_location,
7328 "(an out of class initialization is required)");
7329 explained = 1;
7331 return NULL_TREE;
7334 return init_code;
7337 /* If DECL is not a local variable, give it RTL. */
7339 static void
7340 make_rtl_for_nonlocal_decl (tree decl, tree init, const char* asmspec)
7342 int toplev = toplevel_bindings_p ();
7343 int defer_p;
7345 /* Set the DECL_ASSEMBLER_NAME for the object. */
7346 if (asmspec)
7348 /* The `register' keyword, when used together with an
7349 asm-specification, indicates that the variable should be
7350 placed in a particular register. */
7351 if (VAR_P (decl) && DECL_REGISTER (decl))
7353 set_user_assembler_name (decl, asmspec);
7354 DECL_HARD_REGISTER (decl) = 1;
7356 else
7358 if (TREE_CODE (decl) == FUNCTION_DECL
7359 && fndecl_built_in_p (decl, BUILT_IN_NORMAL))
7360 set_builtin_user_assembler_name (decl, asmspec);
7361 set_user_assembler_name (decl, asmspec);
7362 if (DECL_LOCAL_DECL_P (decl))
7363 if (auto ns_decl = DECL_LOCAL_DECL_ALIAS (decl))
7364 /* We have to propagate the name to the ns-alias.
7365 This is horrible, as we're affecting a
7366 possibly-shared decl. Again, a one-true-decl
7367 model breaks down. */
7368 if (ns_decl != error_mark_node)
7369 set_user_assembler_name (ns_decl, asmspec);
7373 /* Handle non-variables up front. */
7374 if (!VAR_P (decl))
7376 rest_of_decl_compilation (decl, toplev, at_eof);
7377 return;
7380 /* If we see a class member here, it should be a static data
7381 member. */
7382 if (DECL_LANG_SPECIFIC (decl) && DECL_IN_AGGR_P (decl))
7384 gcc_assert (TREE_STATIC (decl));
7385 /* An in-class declaration of a static data member should be
7386 external; it is only a declaration, and not a definition. */
7387 if (init == NULL_TREE)
7388 gcc_assert (DECL_EXTERNAL (decl)
7389 || !TREE_PUBLIC (decl));
7392 /* We don't create any RTL for local variables. */
7393 if (DECL_FUNCTION_SCOPE_P (decl) && !TREE_STATIC (decl))
7394 return;
7396 /* We defer emission of local statics until the corresponding
7397 DECL_EXPR is expanded. But with constexpr its function might never
7398 be expanded, so go ahead and tell cgraph about the variable now. */
7399 defer_p = ((DECL_FUNCTION_SCOPE_P (decl)
7400 && !var_in_maybe_constexpr_fn (decl))
7401 || DECL_VIRTUAL_P (decl));
7403 /* Defer template instantiations. */
7404 if (DECL_LANG_SPECIFIC (decl)
7405 && DECL_IMPLICIT_INSTANTIATION (decl))
7406 defer_p = 1;
7408 /* If we're not deferring, go ahead and assemble the variable. */
7409 if (!defer_p)
7410 rest_of_decl_compilation (decl, toplev, at_eof);
7413 /* walk_tree helper for wrap_temporary_cleanups, below. */
7415 static tree
7416 wrap_cleanups_r (tree *stmt_p, int *walk_subtrees, void *data)
7418 /* Stop at types or full-expression boundaries. */
7419 if (TYPE_P (*stmt_p)
7420 || TREE_CODE (*stmt_p) == CLEANUP_POINT_EXPR)
7422 *walk_subtrees = 0;
7423 return NULL_TREE;
7426 if (TREE_CODE (*stmt_p) == TARGET_EXPR)
7428 tree guard = (tree)data;
7429 tree tcleanup = TARGET_EXPR_CLEANUP (*stmt_p);
7431 tcleanup = build2 (TRY_CATCH_EXPR, void_type_node, tcleanup, guard);
7432 /* Tell honor_protect_cleanup_actions to handle this as a separate
7433 cleanup. */
7434 TRY_CATCH_IS_CLEANUP (tcleanup) = 1;
7436 TARGET_EXPR_CLEANUP (*stmt_p) = tcleanup;
7439 return NULL_TREE;
7442 /* We're initializing a local variable which has a cleanup GUARD. If there
7443 are any temporaries used in the initializer INIT of this variable, we
7444 need to wrap their cleanups with TRY_CATCH_EXPR (, GUARD) so that the
7445 variable will be cleaned up properly if one of them throws.
7447 Unfortunately, there's no way to express this properly in terms of
7448 nesting, as the regions for the temporaries overlap the region for the
7449 variable itself; if there are two temporaries, the variable needs to be
7450 the first thing destroyed if either of them throws. However, we only
7451 want to run the variable's cleanup if it actually got constructed. So
7452 we need to guard the temporary cleanups with the variable's cleanup if
7453 they are run on the normal path, but not if they are run on the
7454 exceptional path. We implement this by telling
7455 honor_protect_cleanup_actions to strip the variable cleanup from the
7456 exceptional path. */
7458 static void
7459 wrap_temporary_cleanups (tree init, tree guard)
7461 cp_walk_tree_without_duplicates (&init, wrap_cleanups_r, (void *)guard);
7464 /* Generate code to initialize DECL (a local variable). */
7466 static void
7467 initialize_local_var (tree decl, tree init)
7469 tree type = TREE_TYPE (decl);
7470 tree cleanup;
7471 int already_used;
7473 gcc_assert (VAR_P (decl)
7474 || TREE_CODE (decl) == RESULT_DECL);
7475 gcc_assert (!TREE_STATIC (decl));
7477 if (DECL_SIZE (decl) == NULL_TREE)
7479 /* If we used it already as memory, it must stay in memory. */
7480 DECL_INITIAL (decl) = NULL_TREE;
7481 TREE_ADDRESSABLE (decl) = TREE_USED (decl);
7482 return;
7485 if (type == error_mark_node)
7486 return;
7488 /* Compute and store the initial value. */
7489 already_used = TREE_USED (decl) || TREE_USED (type);
7490 if (TREE_USED (type))
7491 DECL_READ_P (decl) = 1;
7493 /* Generate a cleanup, if necessary. */
7494 cleanup = cxx_maybe_build_cleanup (decl, tf_warning_or_error);
7496 /* Perform the initialization. */
7497 if (init)
7499 tree rinit = (TREE_CODE (init) == INIT_EXPR
7500 ? TREE_OPERAND (init, 1) : NULL_TREE);
7501 if (rinit && !TREE_SIDE_EFFECTS (rinit))
7503 /* Stick simple initializers in DECL_INITIAL so that
7504 -Wno-init-self works (c++/34772). */
7505 gcc_assert (TREE_OPERAND (init, 0) == decl);
7506 DECL_INITIAL (decl) = rinit;
7508 if (warn_init_self && TYPE_REF_P (type))
7510 STRIP_NOPS (rinit);
7511 if (rinit == decl)
7512 warning_at (DECL_SOURCE_LOCATION (decl),
7513 OPT_Winit_self,
7514 "reference %qD is initialized with itself", decl);
7517 else
7519 int saved_stmts_are_full_exprs_p;
7521 /* If we're only initializing a single object, guard the
7522 destructors of any temporaries used in its initializer with
7523 its destructor. This isn't right for arrays because each
7524 element initialization is a full-expression. */
7525 if (cleanup && TREE_CODE (type) != ARRAY_TYPE)
7526 wrap_temporary_cleanups (init, cleanup);
7528 gcc_assert (building_stmt_list_p ());
7529 saved_stmts_are_full_exprs_p = stmts_are_full_exprs_p ();
7530 current_stmt_tree ()->stmts_are_full_exprs_p = 1;
7531 finish_expr_stmt (init);
7532 current_stmt_tree ()->stmts_are_full_exprs_p =
7533 saved_stmts_are_full_exprs_p;
7537 /* Set this to 0 so we can tell whether an aggregate which was
7538 initialized was ever used. Don't do this if it has a
7539 destructor, so we don't complain about the 'resource
7540 allocation is initialization' idiom. Now set
7541 attribute((unused)) on types so decls of that type will be
7542 marked used. (see TREE_USED, above.) */
7543 if (TYPE_NEEDS_CONSTRUCTING (type)
7544 && ! already_used
7545 && TYPE_HAS_TRIVIAL_DESTRUCTOR (type)
7546 && DECL_NAME (decl))
7547 TREE_USED (decl) = 0;
7548 else if (already_used)
7549 TREE_USED (decl) = 1;
7551 if (cleanup)
7552 finish_decl_cleanup (decl, cleanup);
7555 /* DECL is a VAR_DECL for a compiler-generated variable with static
7556 storage duration (like a virtual table) whose initializer is a
7557 compile-time constant. Initialize the variable and provide it to the
7558 back end. */
7560 void
7561 initialize_artificial_var (tree decl, vec<constructor_elt, va_gc> *v)
7563 tree init;
7564 gcc_assert (DECL_ARTIFICIAL (decl));
7565 init = build_constructor (TREE_TYPE (decl), v);
7566 gcc_assert (TREE_CODE (init) == CONSTRUCTOR);
7567 DECL_INITIAL (decl) = init;
7568 DECL_INITIALIZED_P (decl) = 1;
7569 /* Mark the decl as constexpr so that we can access its content
7570 at compile time. */
7571 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = true;
7572 DECL_DECLARED_CONSTEXPR_P (decl) = true;
7573 determine_visibility (decl);
7574 layout_var_decl (decl);
7575 maybe_commonize_var (decl);
7576 make_rtl_for_nonlocal_decl (decl, init, /*asmspec=*/NULL);
7579 /* INIT is the initializer for a variable, as represented by the
7580 parser. Returns true iff INIT is value-dependent. */
7582 static bool
7583 value_dependent_init_p (tree init)
7585 if (TREE_CODE (init) == TREE_LIST)
7586 /* A parenthesized initializer, e.g.: int i (3, 2); ? */
7587 return any_value_dependent_elements_p (init);
7588 else if (TREE_CODE (init) == CONSTRUCTOR)
7589 /* A brace-enclosed initializer, e.g.: int i = { 3 }; ? */
7591 if (dependent_type_p (TREE_TYPE (init)))
7592 return true;
7594 vec<constructor_elt, va_gc> *elts;
7595 size_t nelts;
7596 size_t i;
7598 elts = CONSTRUCTOR_ELTS (init);
7599 nelts = vec_safe_length (elts);
7600 for (i = 0; i < nelts; ++i)
7601 if (value_dependent_init_p ((*elts)[i].value))
7602 return true;
7604 else
7605 /* It must be a simple expression, e.g., int i = 3; */
7606 return value_dependent_expression_p (init);
7608 return false;
7611 // Returns true if a DECL is VAR_DECL with the concept specifier.
7612 static inline bool
7613 is_concept_var (tree decl)
7615 return (VAR_P (decl)
7616 // Not all variables have DECL_LANG_SPECIFIC.
7617 && DECL_LANG_SPECIFIC (decl)
7618 && DECL_DECLARED_CONCEPT_P (decl));
7621 /* A helper function to be called via walk_tree. If any label exists
7622 under *TP, it is (going to be) forced. Set has_forced_label_in_static. */
7624 static tree
7625 notice_forced_label_r (tree *tp, int *walk_subtrees, void *)
7627 if (TYPE_P (*tp))
7628 *walk_subtrees = 0;
7629 if (TREE_CODE (*tp) == LABEL_DECL)
7630 cfun->has_forced_label_in_static = 1;
7631 return NULL_TREE;
7634 /* Return true if DECL has either a trivial destructor, or for C++20
7635 is constexpr and has a constexpr destructor. */
7637 static bool
7638 decl_maybe_constant_destruction (tree decl, tree type)
7640 return (TYPE_HAS_TRIVIAL_DESTRUCTOR (type)
7641 || (cxx_dialect >= cxx20
7642 && VAR_P (decl)
7643 && DECL_DECLARED_CONSTEXPR_P (decl)
7644 && type_has_constexpr_destructor (strip_array_types (type))));
7647 static tree declare_simd_adjust_this (tree *, int *, void *);
7649 /* Helper function of omp_declare_variant_finalize. Finalize one
7650 "omp declare variant base" attribute. Return true if it should be
7651 removed. */
7653 static bool
7654 omp_declare_variant_finalize_one (tree decl, tree attr)
7656 if (TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
7658 walk_tree (&TREE_VALUE (TREE_VALUE (attr)), declare_simd_adjust_this,
7659 DECL_ARGUMENTS (decl), NULL);
7660 walk_tree (&TREE_PURPOSE (TREE_VALUE (attr)), declare_simd_adjust_this,
7661 DECL_ARGUMENTS (decl), NULL);
7664 tree ctx = TREE_VALUE (TREE_VALUE (attr));
7665 tree simd = omp_get_context_selector (ctx, "construct", "simd");
7666 if (simd)
7668 TREE_VALUE (simd)
7669 = c_omp_declare_simd_clauses_to_numbers (DECL_ARGUMENTS (decl),
7670 TREE_VALUE (simd));
7671 /* FIXME, adjusting simd args unimplemented. */
7672 return true;
7675 tree chain = TREE_CHAIN (TREE_VALUE (attr));
7676 location_t varid_loc
7677 = cp_expr_loc_or_input_loc (TREE_PURPOSE (TREE_CHAIN (chain)));
7678 location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
7679 cp_id_kind idk = (cp_id_kind) tree_to_uhwi (TREE_VALUE (chain));
7680 tree variant = TREE_PURPOSE (TREE_VALUE (attr));
7682 location_t save_loc = input_location;
7683 input_location = varid_loc;
7685 releasing_vec args;
7686 tree parm = DECL_ARGUMENTS (decl);
7687 if (TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
7688 parm = DECL_CHAIN (parm);
7689 for (; parm; parm = DECL_CHAIN (parm))
7690 if (type_dependent_expression_p (parm))
7691 vec_safe_push (args, build_constructor (TREE_TYPE (parm), NULL));
7692 else if (MAYBE_CLASS_TYPE_P (TREE_TYPE (parm)))
7693 vec_safe_push (args, build_local_temp (TREE_TYPE (parm)));
7694 else
7695 vec_safe_push (args, build_zero_cst (TREE_TYPE (parm)));
7697 bool koenig_p = false;
7698 if (idk == CP_ID_KIND_UNQUALIFIED || idk == CP_ID_KIND_TEMPLATE_ID)
7700 if (identifier_p (variant)
7701 /* In C++20, we may need to perform ADL for a template
7702 name. */
7703 || (TREE_CODE (variant) == TEMPLATE_ID_EXPR
7704 && identifier_p (TREE_OPERAND (variant, 0))))
7706 if (!args->is_empty ())
7708 koenig_p = true;
7709 if (!any_type_dependent_arguments_p (args))
7710 variant = perform_koenig_lookup (variant, args,
7711 tf_warning_or_error);
7713 else
7714 variant = unqualified_fn_lookup_error (variant);
7716 else if (!args->is_empty () && is_overloaded_fn (variant))
7718 tree fn = get_first_fn (variant);
7719 fn = STRIP_TEMPLATE (fn);
7720 if (!((TREE_CODE (fn) == USING_DECL && DECL_DEPENDENT_P (fn))
7721 || DECL_FUNCTION_MEMBER_P (fn)
7722 || DECL_LOCAL_DECL_P (fn)))
7724 koenig_p = true;
7725 if (!any_type_dependent_arguments_p (args))
7726 variant = perform_koenig_lookup (variant, args,
7727 tf_warning_or_error);
7732 if (idk == CP_ID_KIND_QUALIFIED)
7733 variant = finish_call_expr (variant, &args, /*disallow_virtual=*/true,
7734 koenig_p, tf_warning_or_error);
7735 else
7736 variant = finish_call_expr (variant, &args, /*disallow_virtual=*/false,
7737 koenig_p, tf_warning_or_error);
7738 if (variant == error_mark_node && !processing_template_decl)
7739 return true;
7741 variant = cp_get_callee_fndecl_nofold (variant);
7742 input_location = save_loc;
7744 if (variant)
7746 const char *varname = IDENTIFIER_POINTER (DECL_NAME (variant));
7747 if (!comptypes (TREE_TYPE (decl), TREE_TYPE (variant), 0))
7749 error_at (varid_loc, "variant %qD and base %qD have incompatible "
7750 "types", variant, decl);
7751 return true;
7753 if (fndecl_built_in_p (variant)
7754 && (startswith (varname, "__builtin_")
7755 || startswith (varname, "__sync_")
7756 || startswith (varname, "__atomic_")))
7758 error_at (varid_loc, "variant %qD is a built-in", variant);
7759 return true;
7761 else
7763 tree construct = omp_get_context_selector (ctx, "construct", NULL);
7764 omp_mark_declare_variant (match_loc, variant, construct);
7765 if (!omp_context_selector_matches (ctx))
7766 return true;
7767 TREE_PURPOSE (TREE_VALUE (attr)) = variant;
7770 else if (!processing_template_decl)
7772 error_at (varid_loc, "could not find variant declaration");
7773 return true;
7776 return false;
7779 /* Helper function, finish up "omp declare variant base" attribute
7780 now that there is a DECL. ATTR is the first "omp declare variant base"
7781 attribute. */
7783 void
7784 omp_declare_variant_finalize (tree decl, tree attr)
7786 size_t attr_len = strlen ("omp declare variant base");
7787 tree *list = &DECL_ATTRIBUTES (decl);
7788 bool remove_all = false;
7789 location_t match_loc = DECL_SOURCE_LOCATION (decl);
7790 if (TREE_CHAIN (TREE_VALUE (attr))
7791 && TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr)))
7792 && EXPR_HAS_LOCATION (TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr)))))
7793 match_loc = EXPR_LOCATION (TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr))));
7794 if (DECL_CONSTRUCTOR_P (decl))
7796 error_at (match_loc, "%<declare variant%> on constructor %qD", decl);
7797 remove_all = true;
7799 else if (DECL_DESTRUCTOR_P (decl))
7801 error_at (match_loc, "%<declare variant%> on destructor %qD", decl);
7802 remove_all = true;
7804 else if (DECL_DEFAULTED_FN (decl))
7806 error_at (match_loc, "%<declare variant%> on defaulted %qD", decl);
7807 remove_all = true;
7809 else if (DECL_DELETED_FN (decl))
7811 error_at (match_loc, "%<declare variant%> on deleted %qD", decl);
7812 remove_all = true;
7814 else if (DECL_VIRTUAL_P (decl))
7816 error_at (match_loc, "%<declare variant%> on virtual %qD", decl);
7817 remove_all = true;
7819 /* This loop is like private_lookup_attribute, except that it works
7820 with tree * rather than tree, as we might want to remove the
7821 attributes that are diagnosed as errorneous. */
7822 while (*list)
7824 tree attr = get_attribute_name (*list);
7825 size_t ident_len = IDENTIFIER_LENGTH (attr);
7826 if (cmp_attribs ("omp declare variant base", attr_len,
7827 IDENTIFIER_POINTER (attr), ident_len))
7829 if (remove_all || omp_declare_variant_finalize_one (decl, *list))
7831 *list = TREE_CHAIN (*list);
7832 continue;
7835 list = &TREE_CHAIN (*list);
7839 /* Finish processing of a declaration;
7840 install its line number and initial value.
7841 If the length of an array type is not known before,
7842 it must be determined now, from the initial value, or it is an error.
7844 INIT is the initializer (if any) for DECL. If INIT_CONST_EXPR_P is
7845 true, then INIT is an integral constant expression.
7847 FLAGS is LOOKUP_ONLYCONVERTING if the = init syntax was used, else 0
7848 if the (init) syntax was used. */
7850 void
7851 cp_finish_decl (tree decl, tree init, bool init_const_expr_p,
7852 tree asmspec_tree, int flags)
7854 tree type;
7855 vec<tree, va_gc> *cleanups = NULL;
7856 const char *asmspec = NULL;
7857 int was_readonly = 0;
7858 bool var_definition_p = false;
7859 tree auto_node;
7861 if (decl == error_mark_node)
7862 return;
7863 else if (! decl)
7865 if (init)
7866 error ("assignment (not initialization) in declaration");
7867 return;
7870 gcc_assert (TREE_CODE (decl) != RESULT_DECL);
7871 /* Parameters are handled by store_parm_decls, not cp_finish_decl. */
7872 gcc_assert (TREE_CODE (decl) != PARM_DECL);
7874 type = TREE_TYPE (decl);
7875 if (type == error_mark_node)
7876 return;
7878 /* Warn about register storage specifiers except when in GNU global
7879 or local register variable extension. */
7880 if (VAR_P (decl) && DECL_REGISTER (decl) && asmspec_tree == NULL_TREE)
7882 if (cxx_dialect >= cxx17)
7883 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
7884 "ISO C++17 does not allow %<register%> storage "
7885 "class specifier");
7886 else
7887 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
7888 "%<register%> storage class specifier used");
7891 /* If a name was specified, get the string. */
7892 if (at_namespace_scope_p ())
7893 asmspec_tree = maybe_apply_renaming_pragma (decl, asmspec_tree);
7894 if (asmspec_tree && asmspec_tree != error_mark_node)
7895 asmspec = TREE_STRING_POINTER (asmspec_tree);
7897 bool in_class_decl
7898 = (current_class_type
7899 && CP_DECL_CONTEXT (decl) == current_class_type
7900 && TYPE_BEING_DEFINED (current_class_type)
7901 && !CLASSTYPE_TEMPLATE_INSTANTIATION (current_class_type));
7903 if (in_class_decl
7904 && (DECL_INITIAL (decl) || init))
7905 DECL_INITIALIZED_IN_CLASS_P (decl) = 1;
7907 if (TREE_CODE (decl) != FUNCTION_DECL
7908 && (auto_node = type_uses_auto (type)))
7910 tree d_init;
7911 if (init == NULL_TREE)
7913 if (DECL_LANG_SPECIFIC (decl)
7914 && DECL_TEMPLATE_INSTANTIATION (decl)
7915 && !DECL_TEMPLATE_INSTANTIATED (decl))
7917 /* init is null because we're deferring instantiating the
7918 initializer until we need it. Well, we need it now. */
7919 instantiate_decl (decl, /*defer_ok*/true, /*expl*/false);
7920 return;
7923 gcc_assert (CLASS_PLACEHOLDER_TEMPLATE (auto_node));
7925 d_init = init;
7926 if (d_init)
7928 if (TREE_CODE (d_init) == TREE_LIST
7929 && !CLASS_PLACEHOLDER_TEMPLATE (auto_node))
7930 d_init = build_x_compound_expr_from_list (d_init, ELK_INIT,
7931 tf_warning_or_error);
7932 d_init = resolve_nondeduced_context (d_init, tf_warning_or_error);
7934 enum auto_deduction_context adc = adc_variable_type;
7935 if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
7936 adc = adc_decomp_type;
7937 type = TREE_TYPE (decl) = do_auto_deduction (type, d_init, auto_node,
7938 tf_warning_or_error, adc,
7939 NULL_TREE, flags);
7940 if (type == error_mark_node)
7941 return;
7942 if (TREE_CODE (type) == FUNCTION_TYPE)
7944 error ("initializer for %<decltype(auto) %D%> has function type; "
7945 "did you forget the %<()%>?", decl);
7946 TREE_TYPE (decl) = error_mark_node;
7947 return;
7949 cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
7952 if (ensure_literal_type_for_constexpr_object (decl) == error_mark_node)
7954 DECL_DECLARED_CONSTEXPR_P (decl) = 0;
7955 if (VAR_P (decl) && DECL_CLASS_SCOPE_P (decl))
7957 init = NULL_TREE;
7958 DECL_EXTERNAL (decl) = 1;
7962 if (VAR_P (decl)
7963 && DECL_CLASS_SCOPE_P (decl)
7964 && verify_type_context (DECL_SOURCE_LOCATION (decl),
7965 TCTX_STATIC_STORAGE, type)
7966 && DECL_INITIALIZED_IN_CLASS_P (decl))
7967 check_static_variable_definition (decl, type);
7969 if (!processing_template_decl && VAR_P (decl) && is_global_var (decl))
7971 type_context_kind context = (DECL_THREAD_LOCAL_P (decl)
7972 ? TCTX_THREAD_STORAGE
7973 : TCTX_STATIC_STORAGE);
7974 verify_type_context (input_location, context, TREE_TYPE (decl));
7977 if (init && TREE_CODE (decl) == FUNCTION_DECL)
7979 tree clone;
7980 if (init == ridpointers[(int)RID_DELETE])
7982 /* FIXME check this is 1st decl. */
7983 DECL_DELETED_FN (decl) = 1;
7984 DECL_DECLARED_INLINE_P (decl) = 1;
7985 DECL_INITIAL (decl) = error_mark_node;
7986 FOR_EACH_CLONE (clone, decl)
7988 DECL_DELETED_FN (clone) = 1;
7989 DECL_DECLARED_INLINE_P (clone) = 1;
7990 DECL_INITIAL (clone) = error_mark_node;
7992 init = NULL_TREE;
7994 else if (init == ridpointers[(int)RID_DEFAULT])
7996 if (defaultable_fn_check (decl))
7997 DECL_DEFAULTED_FN (decl) = 1;
7998 else
7999 DECL_INITIAL (decl) = NULL_TREE;
8003 if (init && VAR_P (decl))
8005 DECL_NONTRIVIALLY_INITIALIZED_P (decl) = 1;
8006 /* If DECL is a reference, then we want to know whether init is a
8007 reference constant; init_const_expr_p as passed tells us whether
8008 it's an rvalue constant. */
8009 if (TYPE_REF_P (type))
8010 init_const_expr_p = potential_constant_expression (init);
8011 if (init_const_expr_p)
8013 /* Set these flags now for templates. We'll update the flags in
8014 store_init_value for instantiations. */
8015 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = 1;
8016 if (decl_maybe_constant_var_p (decl)
8017 /* FIXME setting TREE_CONSTANT on refs breaks the back end. */
8018 && !TYPE_REF_P (type))
8019 TREE_CONSTANT (decl) = 1;
8023 if (flag_openmp
8024 && TREE_CODE (decl) == FUNCTION_DECL
8025 /* #pragma omp declare variant on methods handled in finish_struct
8026 instead. */
8027 && (!DECL_NONSTATIC_MEMBER_FUNCTION_P (decl)
8028 || COMPLETE_TYPE_P (DECL_CONTEXT (decl))))
8029 if (tree attr = lookup_attribute ("omp declare variant base",
8030 DECL_ATTRIBUTES (decl)))
8031 omp_declare_variant_finalize (decl, attr);
8033 if (processing_template_decl)
8035 bool type_dependent_p;
8037 /* Add this declaration to the statement-tree. */
8038 if (at_function_scope_p ())
8039 add_decl_expr (decl);
8041 type_dependent_p = dependent_type_p (type);
8043 if (check_for_bare_parameter_packs (init))
8045 init = NULL_TREE;
8046 DECL_INITIAL (decl) = NULL_TREE;
8049 /* Generally, initializers in templates are expanded when the
8050 template is instantiated. But, if DECL is a variable constant
8051 then it can be used in future constant expressions, so its value
8052 must be available. */
8054 bool dep_init = false;
8056 if (!VAR_P (decl) || type_dependent_p)
8057 /* We can't do anything if the decl has dependent type. */;
8058 else if (!init && is_concept_var (decl))
8060 error ("variable concept has no initializer");
8061 init = boolean_true_node;
8063 else if (init
8064 && (init_const_expr_p || DECL_DECLARED_CONSTEXPR_P (decl))
8065 && !TYPE_REF_P (type)
8066 && decl_maybe_constant_var_p (decl)
8067 && !(dep_init = value_dependent_init_p (init)))
8069 /* This variable seems to be a non-dependent constant, so process
8070 its initializer. If check_initializer returns non-null the
8071 initialization wasn't constant after all. */
8072 tree init_code;
8073 cleanups = make_tree_vector ();
8074 init_code = check_initializer (decl, init, flags, &cleanups);
8075 if (init_code == NULL_TREE)
8076 init = NULL_TREE;
8077 release_tree_vector (cleanups);
8079 else
8081 gcc_assert (!DECL_PRETTY_FUNCTION_P (decl));
8082 /* Deduce array size even if the initializer is dependent. */
8083 maybe_deduce_size_from_array_init (decl, init);
8084 /* And complain about multiple initializers. */
8085 if (init && TREE_CODE (init) == TREE_LIST && TREE_CHAIN (init)
8086 && !MAYBE_CLASS_TYPE_P (type))
8087 init = build_x_compound_expr_from_list (init, ELK_INIT,
8088 tf_warning_or_error);
8091 if (init)
8092 DECL_INITIAL (decl) = init;
8094 if (dep_init)
8096 retrofit_lang_decl (decl);
8097 SET_DECL_DEPENDENT_INIT_P (decl, true);
8100 if (VAR_P (decl) && DECL_REGISTER (decl) && asmspec)
8102 set_user_assembler_name (decl, asmspec);
8103 DECL_HARD_REGISTER (decl) = 1;
8105 return;
8108 /* Just store non-static data member initializers for later. */
8109 if (init && TREE_CODE (decl) == FIELD_DECL)
8110 DECL_INITIAL (decl) = init;
8112 /* Take care of TYPE_DECLs up front. */
8113 if (TREE_CODE (decl) == TYPE_DECL)
8115 if (type != error_mark_node
8116 && MAYBE_CLASS_TYPE_P (type) && DECL_NAME (decl))
8118 if (TREE_TYPE (DECL_NAME (decl)) && TREE_TYPE (decl) != type)
8119 warning (0, "shadowing previous type declaration of %q#D", decl);
8120 set_identifier_type_value (DECL_NAME (decl), decl);
8123 /* If we have installed this as the canonical typedef for this
8124 type, and that type has not been defined yet, delay emitting
8125 the debug information for it, as we will emit it later. */
8126 if (TYPE_MAIN_DECL (TREE_TYPE (decl)) == decl
8127 && !COMPLETE_TYPE_P (TREE_TYPE (decl)))
8128 TYPE_DECL_SUPPRESS_DEBUG (decl) = 1;
8130 rest_of_decl_compilation (decl, DECL_FILE_SCOPE_P (decl),
8131 at_eof);
8132 return;
8135 /* A reference will be modified here, as it is initialized. */
8136 if (! DECL_EXTERNAL (decl)
8137 && TREE_READONLY (decl)
8138 && TYPE_REF_P (type))
8140 was_readonly = 1;
8141 TREE_READONLY (decl) = 0;
8144 /* This needs to happen before extend_ref_init_temps. */
8145 if (VAR_OR_FUNCTION_DECL_P (decl))
8147 if (VAR_P (decl))
8148 maybe_commonize_var (decl);
8149 determine_visibility (decl);
8152 if (VAR_P (decl))
8154 duration_kind dk = decl_storage_duration (decl);
8155 /* [dcl.constinit]/1 "The constinit specifier shall be applied
8156 only to a declaration of a variable with static or thread storage
8157 duration." */
8158 if (DECL_DECLARED_CONSTINIT_P (decl)
8159 && !(dk == dk_thread || dk == dk_static))
8161 error_at (DECL_SOURCE_LOCATION (decl),
8162 "%<constinit%> can only be applied to a variable with "
8163 "static or thread storage duration");
8164 return;
8167 /* If this is a local variable that will need a mangled name,
8168 register it now. We must do this before processing the
8169 initializer for the variable, since the initialization might
8170 require a guard variable, and since the mangled name of the
8171 guard variable will depend on the mangled name of this
8172 variable. */
8173 if (DECL_FUNCTION_SCOPE_P (decl)
8174 && TREE_STATIC (decl)
8175 && !DECL_ARTIFICIAL (decl))
8177 /* The variable holding an anonymous union will have had its
8178 discriminator set in finish_anon_union, after which it's
8179 NAME will have been cleared. */
8180 if (DECL_NAME (decl))
8181 determine_local_discriminator (decl);
8182 /* Normally has_forced_label_in_static is set during GIMPLE
8183 lowering, but [cd]tors are never actually compiled directly.
8184 We need to set this early so we can deal with the label
8185 address extension. */
8186 if ((DECL_CONSTRUCTOR_P (current_function_decl)
8187 || DECL_DESTRUCTOR_P (current_function_decl))
8188 && init)
8190 walk_tree (&init, notice_forced_label_r, NULL, NULL);
8191 add_local_decl (cfun, decl);
8193 /* And make sure it's in the symbol table for
8194 c_parse_final_cleanups to find. */
8195 varpool_node::get_create (decl);
8198 /* Convert the initializer to the type of DECL, if we have not
8199 already initialized DECL. */
8200 if (!DECL_INITIALIZED_P (decl)
8201 /* If !DECL_EXTERNAL then DECL is being defined. In the
8202 case of a static data member initialized inside the
8203 class-specifier, there can be an initializer even if DECL
8204 is *not* defined. */
8205 && (!DECL_EXTERNAL (decl) || init))
8207 cleanups = make_tree_vector ();
8208 init = check_initializer (decl, init, flags, &cleanups);
8210 /* Handle:
8212 [dcl.init]
8214 The memory occupied by any object of static storage
8215 duration is zero-initialized at program startup before
8216 any other initialization takes place.
8218 We cannot create an appropriate initializer until after
8219 the type of DECL is finalized. If DECL_INITIAL is set,
8220 then the DECL is statically initialized, and any
8221 necessary zero-initialization has already been performed. */
8222 if (TREE_STATIC (decl) && !DECL_INITIAL (decl))
8223 DECL_INITIAL (decl) = build_zero_init (TREE_TYPE (decl),
8224 /*nelts=*/NULL_TREE,
8225 /*static_storage_p=*/true);
8226 /* Remember that the initialization for this variable has
8227 taken place. */
8228 DECL_INITIALIZED_P (decl) = 1;
8229 /* This declaration is the definition of this variable,
8230 unless we are initializing a static data member within
8231 the class specifier. */
8232 if (!DECL_EXTERNAL (decl))
8233 var_definition_p = true;
8235 /* If the variable has an array type, lay out the type, even if
8236 there is no initializer. It is valid to index through the
8237 array, and we must get TYPE_ALIGN set correctly on the array
8238 type. */
8239 else if (TREE_CODE (type) == ARRAY_TYPE)
8240 layout_type (type);
8242 if (TREE_STATIC (decl)
8243 && !at_function_scope_p ()
8244 && current_function_decl == NULL)
8245 /* So decl is a global variable or a static member of a
8246 non local class. Record the types it uses
8247 so that we can decide later to emit debug info for them. */
8248 record_types_used_by_current_var_decl (decl);
8251 /* Add this declaration to the statement-tree. This needs to happen
8252 after the call to check_initializer so that the DECL_EXPR for a
8253 reference temp is added before the DECL_EXPR for the reference itself. */
8254 if (DECL_FUNCTION_SCOPE_P (decl))
8256 /* If we're building a variable sized type, and we might be
8257 reachable other than via the top of the current binding
8258 level, then create a new BIND_EXPR so that we deallocate
8259 the object at the right time. */
8260 if (VAR_P (decl)
8261 && DECL_SIZE (decl)
8262 && !TREE_CONSTANT (DECL_SIZE (decl))
8263 && STATEMENT_LIST_HAS_LABEL (cur_stmt_list))
8265 tree bind;
8266 bind = build3 (BIND_EXPR, void_type_node, NULL, NULL, NULL);
8267 TREE_SIDE_EFFECTS (bind) = 1;
8268 add_stmt (bind);
8269 BIND_EXPR_BODY (bind) = push_stmt_list ();
8271 add_decl_expr (decl);
8274 /* Let the middle end know about variables and functions -- but not
8275 static data members in uninstantiated class templates. */
8276 if (VAR_OR_FUNCTION_DECL_P (decl))
8278 if (VAR_P (decl))
8280 layout_var_decl (decl);
8281 if (!flag_weak)
8282 /* Check again now that we have an initializer. */
8283 maybe_commonize_var (decl);
8284 /* A class-scope constexpr variable with an out-of-class declaration.
8285 C++17 makes them implicitly inline, but still force it out. */
8286 if (DECL_INLINE_VAR_P (decl)
8287 && !DECL_VAR_DECLARED_INLINE_P (decl)
8288 && !DECL_TEMPLATE_INSTANTIATION (decl)
8289 && !in_class_decl)
8290 mark_needed (decl);
8293 if (var_definition_p
8294 /* With -fmerge-all-constants, gimplify_init_constructor
8295 might add TREE_STATIC to the variable. */
8296 && (TREE_STATIC (decl) || flag_merge_constants >= 2))
8298 /* If a TREE_READONLY variable needs initialization
8299 at runtime, it is no longer readonly and we need to
8300 avoid MEM_READONLY_P being set on RTL created for it. */
8301 if (init)
8303 if (TREE_READONLY (decl))
8304 TREE_READONLY (decl) = 0;
8305 was_readonly = 0;
8307 else if (was_readonly)
8308 TREE_READONLY (decl) = 1;
8310 /* Likewise if it needs destruction. */
8311 if (!decl_maybe_constant_destruction (decl, type))
8312 TREE_READONLY (decl) = 0;
8315 make_rtl_for_nonlocal_decl (decl, init, asmspec);
8317 /* Check for abstractness of the type. */
8318 if (var_definition_p)
8319 abstract_virtuals_error (decl, type);
8321 if (TREE_TYPE (decl) == error_mark_node)
8322 /* No initialization required. */
8324 else if (TREE_CODE (decl) == FUNCTION_DECL)
8326 if (init)
8328 if (init == ridpointers[(int)RID_DEFAULT])
8330 /* An out-of-class default definition is defined at
8331 the point where it is explicitly defaulted. */
8332 if (DECL_DELETED_FN (decl))
8333 maybe_explain_implicit_delete (decl);
8334 else if (DECL_INITIAL (decl) == error_mark_node)
8335 synthesize_method (decl);
8337 else
8338 error_at (cp_expr_loc_or_loc (init,
8339 DECL_SOURCE_LOCATION (decl)),
8340 "function %q#D is initialized like a variable",
8341 decl);
8343 /* else no initialization required. */
8345 else if (DECL_EXTERNAL (decl)
8346 && ! (DECL_LANG_SPECIFIC (decl)
8347 && DECL_NOT_REALLY_EXTERN (decl)))
8349 /* check_initializer will have done any constant initialization. */
8351 /* A variable definition. */
8352 else if (DECL_FUNCTION_SCOPE_P (decl) && !TREE_STATIC (decl))
8353 /* Initialize the local variable. */
8354 initialize_local_var (decl, init);
8356 /* If a variable is defined, and then a subsequent
8357 definition with external linkage is encountered, we will
8358 get here twice for the same variable. We want to avoid
8359 calling expand_static_init more than once. For variables
8360 that are not static data members, we can call
8361 expand_static_init only when we actually process the
8362 initializer. It is not legal to redeclare a static data
8363 member, so this issue does not arise in that case. */
8364 else if (var_definition_p && TREE_STATIC (decl))
8365 expand_static_init (decl, init);
8368 /* If a CLEANUP_STMT was created to destroy a temporary bound to a
8369 reference, insert it in the statement-tree now. */
8370 if (cleanups)
8372 for (tree t : *cleanups)
8373 push_cleanup (decl, t, false);
8374 release_tree_vector (cleanups);
8377 if (was_readonly)
8378 TREE_READONLY (decl) = 1;
8380 if (flag_openmp
8381 && VAR_P (decl)
8382 && lookup_attribute ("omp declare target implicit",
8383 DECL_ATTRIBUTES (decl)))
8385 DECL_ATTRIBUTES (decl)
8386 = remove_attribute ("omp declare target implicit",
8387 DECL_ATTRIBUTES (decl));
8388 complete_type (TREE_TYPE (decl));
8389 if (!cp_omp_mappable_type (TREE_TYPE (decl)))
8391 error ("%q+D in declare target directive does not have mappable"
8392 " type", decl);
8393 cp_omp_emit_unmappable_type_notes (TREE_TYPE (decl));
8395 else if (!lookup_attribute ("omp declare target",
8396 DECL_ATTRIBUTES (decl))
8397 && !lookup_attribute ("omp declare target link",
8398 DECL_ATTRIBUTES (decl)))
8400 DECL_ATTRIBUTES (decl)
8401 = tree_cons (get_identifier ("omp declare target"),
8402 NULL_TREE, DECL_ATTRIBUTES (decl));
8403 symtab_node *node = symtab_node::get (decl);
8404 if (node != NULL)
8406 node->offloadable = 1;
8407 if (ENABLE_OFFLOADING)
8409 g->have_offload = true;
8410 if (is_a <varpool_node *> (node))
8411 vec_safe_push (offload_vars, decl);
8417 /* This is the last point we can lower alignment so give the target the
8418 chance to do so. */
8419 if (VAR_P (decl)
8420 && !is_global_var (decl)
8421 && !DECL_HARD_REGISTER (decl))
8422 targetm.lower_local_decl_alignment (decl);
8424 invoke_plugin_callbacks (PLUGIN_FINISH_DECL, decl);
8427 /* For class TYPE return itself or some its bases that contain
8428 any direct non-static data members. Return error_mark_node if an
8429 error has been diagnosed. */
8431 static tree
8432 find_decomp_class_base (location_t loc, tree type, tree ret)
8434 bool member_seen = false;
8435 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
8436 if (TREE_CODE (field) != FIELD_DECL
8437 || DECL_ARTIFICIAL (field)
8438 || DECL_UNNAMED_BIT_FIELD (field))
8439 continue;
8440 else if (ret)
8441 return type;
8442 else if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
8444 if (TREE_CODE (TREE_TYPE (field)) == RECORD_TYPE)
8445 error_at (loc, "cannot decompose class type %qT because it has an "
8446 "anonymous struct member", type);
8447 else
8448 error_at (loc, "cannot decompose class type %qT because it has an "
8449 "anonymous union member", type);
8450 inform (DECL_SOURCE_LOCATION (field), "declared here");
8451 return error_mark_node;
8453 else if (!accessible_p (type, field, true))
8455 error_at (loc, "cannot decompose inaccessible member %qD of %qT",
8456 field, type);
8457 inform (DECL_SOURCE_LOCATION (field),
8458 TREE_PRIVATE (field)
8459 ? G_("declared private here")
8460 : G_("declared protected here"));
8461 return error_mark_node;
8463 else
8464 member_seen = true;
8466 tree base_binfo, binfo;
8467 tree orig_ret = ret;
8468 int i;
8469 if (member_seen)
8470 ret = type;
8471 for (binfo = TYPE_BINFO (type), i = 0;
8472 BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
8474 tree t = find_decomp_class_base (loc, TREE_TYPE (base_binfo), ret);
8475 if (t == error_mark_node)
8476 return error_mark_node;
8477 if (t != NULL_TREE && t != ret)
8479 if (ret == type)
8481 error_at (loc, "cannot decompose class type %qT: both it and "
8482 "its base class %qT have non-static data members",
8483 type, t);
8484 return error_mark_node;
8486 else if (orig_ret != NULL_TREE)
8487 return t;
8488 else if (ret != NULL_TREE)
8490 error_at (loc, "cannot decompose class type %qT: its base "
8491 "classes %qT and %qT have non-static data "
8492 "members", type, ret, t);
8493 return error_mark_node;
8495 else
8496 ret = t;
8499 return ret;
8502 /* Return std::tuple_size<TYPE>::value. */
8504 static tree
8505 get_tuple_size (tree type)
8507 tree args = make_tree_vec (1);
8508 TREE_VEC_ELT (args, 0) = type;
8509 tree inst = lookup_template_class (tuple_size_identifier, args,
8510 /*in_decl*/NULL_TREE,
8511 /*context*/std_node,
8512 /*entering_scope*/false, tf_none);
8513 inst = complete_type (inst);
8514 if (inst == error_mark_node || !COMPLETE_TYPE_P (inst))
8515 return NULL_TREE;
8516 tree val = lookup_qualified_name (inst, value_identifier,
8517 LOOK_want::NORMAL, /*complain*/false);
8518 if (TREE_CODE (val) == VAR_DECL || TREE_CODE (val) == CONST_DECL)
8519 val = maybe_constant_value (val);
8520 if (TREE_CODE (val) == INTEGER_CST)
8521 return val;
8522 else
8523 return error_mark_node;
8526 /* Return std::tuple_element<I,TYPE>::type. */
8528 static tree
8529 get_tuple_element_type (tree type, unsigned i)
8531 tree args = make_tree_vec (2);
8532 TREE_VEC_ELT (args, 0) = build_int_cst (integer_type_node, i);
8533 TREE_VEC_ELT (args, 1) = type;
8534 tree inst = lookup_template_class (tuple_element_identifier, args,
8535 /*in_decl*/NULL_TREE,
8536 /*context*/std_node,
8537 /*entering_scope*/false,
8538 tf_warning_or_error);
8539 return make_typename_type (inst, type_identifier,
8540 none_type, tf_warning_or_error);
8543 /* Return e.get<i>() or get<i>(e). */
8545 static tree
8546 get_tuple_decomp_init (tree decl, unsigned i)
8548 tree targs = make_tree_vec (1);
8549 TREE_VEC_ELT (targs, 0) = build_int_cst (integer_type_node, i);
8551 tree etype = TREE_TYPE (decl);
8552 tree e = convert_from_reference (decl);
8554 /* [The id-expression] e is an lvalue if the type of the entity e is an
8555 lvalue reference and an xvalue otherwise. */
8556 if (!TYPE_REF_P (etype)
8557 || TYPE_REF_IS_RVALUE (etype))
8558 e = move (e);
8560 tree fns = lookup_qualified_name (TREE_TYPE (e), get__identifier,
8561 LOOK_want::NORMAL, /*complain*/false);
8562 bool use_member_get = false;
8564 /* To use a member get, member lookup must find at least one
8565 declaration that is a function template
8566 whose first template parameter is a non-type parameter. */
8567 for (lkp_iterator iter (MAYBE_BASELINK_FUNCTIONS (fns)); iter; ++iter)
8569 tree fn = *iter;
8570 if (TREE_CODE (fn) == TEMPLATE_DECL)
8572 tree tparms = DECL_TEMPLATE_PARMS (fn);
8573 tree parm = TREE_VEC_ELT (INNERMOST_TEMPLATE_PARMS (tparms), 0);
8574 if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
8576 use_member_get = true;
8577 break;
8582 if (use_member_get)
8584 fns = lookup_template_function (fns, targs);
8585 return build_new_method_call (e, fns, /*args*/NULL,
8586 /*path*/NULL_TREE, LOOKUP_NORMAL,
8587 /*fn_p*/NULL, tf_warning_or_error);
8589 else
8591 releasing_vec args (make_tree_vector_single (e));
8592 fns = lookup_template_function (get__identifier, targs);
8593 fns = perform_koenig_lookup (fns, args, tf_warning_or_error);
8594 return finish_call_expr (fns, &args, /*novirt*/false,
8595 /*koenig*/true, tf_warning_or_error);
8599 /* It's impossible to recover the decltype of a tuple decomposition variable
8600 based on the actual type of the variable, so store it in a hash table. */
8602 static GTY((cache)) decl_tree_cache_map *decomp_type_table;
8604 tree
8605 lookup_decomp_type (tree v)
8607 return *decomp_type_table->get (v);
8610 /* Mangle a decomposition declaration if needed. Arguments like
8611 in cp_finish_decomp. */
8613 void
8614 cp_maybe_mangle_decomp (tree decl, tree first, unsigned int count)
8616 if (!processing_template_decl
8617 && !error_operand_p (decl)
8618 && TREE_STATIC (decl))
8620 auto_vec<tree, 16> v;
8621 v.safe_grow (count, true);
8622 tree d = first;
8623 for (unsigned int i = 0; i < count; i++, d = DECL_CHAIN (d))
8624 v[count - i - 1] = d;
8625 SET_DECL_ASSEMBLER_NAME (decl, mangle_decomp (decl, v));
8626 maybe_apply_pragma_weak (decl);
8630 /* Finish a decomposition declaration. DECL is the underlying declaration
8631 "e", FIRST is the head of a chain of decls for the individual identifiers
8632 chained through DECL_CHAIN in reverse order and COUNT is the number of
8633 those decls. */
8635 void
8636 cp_finish_decomp (tree decl, tree first, unsigned int count)
8638 if (error_operand_p (decl))
8640 error_out:
8641 while (count--)
8643 TREE_TYPE (first) = error_mark_node;
8644 if (DECL_HAS_VALUE_EXPR_P (first))
8646 SET_DECL_VALUE_EXPR (first, NULL_TREE);
8647 DECL_HAS_VALUE_EXPR_P (first) = 0;
8649 first = DECL_CHAIN (first);
8651 if (DECL_P (decl) && DECL_NAMESPACE_SCOPE_P (decl))
8652 SET_DECL_ASSEMBLER_NAME (decl, get_identifier ("<decomp>"));
8653 return;
8656 location_t loc = DECL_SOURCE_LOCATION (decl);
8657 if (type_dependent_expression_p (decl)
8658 /* This happens for range for when not in templates.
8659 Still add the DECL_VALUE_EXPRs for later processing. */
8660 || (!processing_template_decl
8661 && type_uses_auto (TREE_TYPE (decl))))
8663 for (unsigned int i = 0; i < count; i++)
8665 if (!DECL_HAS_VALUE_EXPR_P (first))
8667 tree v = build_nt (ARRAY_REF, decl,
8668 size_int (count - i - 1),
8669 NULL_TREE, NULL_TREE);
8670 SET_DECL_VALUE_EXPR (first, v);
8671 DECL_HAS_VALUE_EXPR_P (first) = 1;
8673 if (processing_template_decl)
8674 fit_decomposition_lang_decl (first, decl);
8675 first = DECL_CHAIN (first);
8677 return;
8680 auto_vec<tree, 16> v;
8681 v.safe_grow (count, true);
8682 tree d = first;
8683 for (unsigned int i = 0; i < count; i++, d = DECL_CHAIN (d))
8685 v[count - i - 1] = d;
8686 fit_decomposition_lang_decl (d, decl);
8689 tree type = TREE_TYPE (decl);
8690 tree dexp = decl;
8692 if (TYPE_REF_P (type))
8694 dexp = convert_from_reference (dexp);
8695 type = complete_type (TREE_TYPE (type));
8696 if (type == error_mark_node)
8697 goto error_out;
8698 if (!COMPLETE_TYPE_P (type))
8700 error_at (loc, "structured binding refers to incomplete type %qT",
8701 type);
8702 goto error_out;
8706 tree eltype = NULL_TREE;
8707 unsigned HOST_WIDE_INT eltscnt = 0;
8708 if (TREE_CODE (type) == ARRAY_TYPE)
8710 tree nelts;
8711 nelts = array_type_nelts_top (type);
8712 if (nelts == error_mark_node)
8713 goto error_out;
8714 if (!tree_fits_uhwi_p (nelts))
8716 error_at (loc, "cannot decompose variable length array %qT", type);
8717 goto error_out;
8719 eltscnt = tree_to_uhwi (nelts);
8720 if (count != eltscnt)
8722 cnt_mismatch:
8723 if (count > eltscnt)
8724 error_n (loc, count,
8725 "%u name provided for structured binding",
8726 "%u names provided for structured binding", count);
8727 else
8728 error_n (loc, count,
8729 "only %u name provided for structured binding",
8730 "only %u names provided for structured binding", count);
8731 inform_n (loc, eltscnt,
8732 "while %qT decomposes into %wu element",
8733 "while %qT decomposes into %wu elements",
8734 type, eltscnt);
8735 goto error_out;
8737 eltype = TREE_TYPE (type);
8738 for (unsigned int i = 0; i < count; i++)
8740 TREE_TYPE (v[i]) = eltype;
8741 layout_decl (v[i], 0);
8742 if (processing_template_decl)
8743 continue;
8744 tree t = unshare_expr (dexp);
8745 t = build4_loc (DECL_SOURCE_LOCATION (v[i]), ARRAY_REF,
8746 eltype, t, size_int (i), NULL_TREE,
8747 NULL_TREE);
8748 SET_DECL_VALUE_EXPR (v[i], t);
8749 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
8752 /* 2 GNU extensions. */
8753 else if (TREE_CODE (type) == COMPLEX_TYPE)
8755 eltscnt = 2;
8756 if (count != eltscnt)
8757 goto cnt_mismatch;
8758 eltype = cp_build_qualified_type (TREE_TYPE (type), TYPE_QUALS (type));
8759 for (unsigned int i = 0; i < count; i++)
8761 TREE_TYPE (v[i]) = eltype;
8762 layout_decl (v[i], 0);
8763 if (processing_template_decl)
8764 continue;
8765 tree t = unshare_expr (dexp);
8766 t = build1_loc (DECL_SOURCE_LOCATION (v[i]),
8767 i ? IMAGPART_EXPR : REALPART_EXPR, eltype,
8769 SET_DECL_VALUE_EXPR (v[i], t);
8770 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
8773 else if (TREE_CODE (type) == VECTOR_TYPE)
8775 if (!TYPE_VECTOR_SUBPARTS (type).is_constant (&eltscnt))
8777 error_at (loc, "cannot decompose variable length vector %qT", type);
8778 goto error_out;
8780 if (count != eltscnt)
8781 goto cnt_mismatch;
8782 eltype = cp_build_qualified_type (TREE_TYPE (type), TYPE_QUALS (type));
8783 for (unsigned int i = 0; i < count; i++)
8785 TREE_TYPE (v[i]) = eltype;
8786 layout_decl (v[i], 0);
8787 if (processing_template_decl)
8788 continue;
8789 tree t = unshare_expr (dexp);
8790 convert_vector_to_array_for_subscript (DECL_SOURCE_LOCATION (v[i]),
8791 &t, size_int (i));
8792 t = build4_loc (DECL_SOURCE_LOCATION (v[i]), ARRAY_REF,
8793 eltype, t, size_int (i), NULL_TREE,
8794 NULL_TREE);
8795 SET_DECL_VALUE_EXPR (v[i], t);
8796 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
8799 else if (tree tsize = get_tuple_size (type))
8801 if (tsize == error_mark_node)
8803 error_at (loc, "%<std::tuple_size<%T>::value%> is not an integral "
8804 "constant expression", type);
8805 goto error_out;
8807 if (!tree_fits_uhwi_p (tsize))
8809 error_n (loc, count,
8810 "%u name provided for structured binding",
8811 "%u names provided for structured binding", count);
8812 inform (loc, "while %qT decomposes into %E elements",
8813 type, tsize);
8814 goto error_out;
8816 eltscnt = tree_to_uhwi (tsize);
8817 if (count != eltscnt)
8818 goto cnt_mismatch;
8819 int save_read = DECL_READ_P (decl);
8820 for (unsigned i = 0; i < count; ++i)
8822 location_t sloc = input_location;
8823 location_t dloc = DECL_SOURCE_LOCATION (v[i]);
8825 input_location = dloc;
8826 tree init = get_tuple_decomp_init (decl, i);
8827 tree eltype = (init == error_mark_node ? error_mark_node
8828 : get_tuple_element_type (type, i));
8829 input_location = sloc;
8831 if (VOID_TYPE_P (eltype))
8833 error ("%<std::tuple_element<%u, %T>::type%> is %<void%>",
8834 i, type);
8835 eltype = error_mark_node;
8837 if (init == error_mark_node || eltype == error_mark_node)
8839 inform (dloc, "in initialization of structured binding "
8840 "variable %qD", v[i]);
8841 goto error_out;
8843 /* Save the decltype away before reference collapse. */
8844 hash_map_safe_put<hm_ggc> (decomp_type_table, v[i], eltype);
8845 eltype = cp_build_reference_type (eltype, !lvalue_p (init));
8846 TREE_TYPE (v[i]) = eltype;
8847 layout_decl (v[i], 0);
8848 if (DECL_HAS_VALUE_EXPR_P (v[i]))
8850 /* In this case the names are variables, not just proxies. */
8851 SET_DECL_VALUE_EXPR (v[i], NULL_TREE);
8852 DECL_HAS_VALUE_EXPR_P (v[i]) = 0;
8854 if (!processing_template_decl)
8856 copy_linkage (v[i], decl);
8857 cp_finish_decl (v[i], init, /*constexpr*/false,
8858 /*asm*/NULL_TREE, LOOKUP_NORMAL);
8861 /* Ignore reads from the underlying decl performed during initialization
8862 of the individual variables. If those will be read, we'll mark
8863 the underlying decl as read at that point. */
8864 DECL_READ_P (decl) = save_read;
8866 else if (TREE_CODE (type) == UNION_TYPE)
8868 error_at (loc, "cannot decompose union type %qT", type);
8869 goto error_out;
8871 else if (!CLASS_TYPE_P (type))
8873 error_at (loc, "cannot decompose non-array non-class type %qT", type);
8874 goto error_out;
8876 else if (LAMBDA_TYPE_P (type))
8878 error_at (loc, "cannot decompose lambda closure type %qT", type);
8879 goto error_out;
8881 else if (processing_template_decl && complete_type (type) == error_mark_node)
8882 goto error_out;
8883 else if (processing_template_decl && !COMPLETE_TYPE_P (type))
8884 pedwarn (loc, 0, "structured binding refers to incomplete class type %qT",
8885 type);
8886 else
8888 tree btype = find_decomp_class_base (loc, type, NULL_TREE);
8889 if (btype == error_mark_node)
8890 goto error_out;
8891 else if (btype == NULL_TREE)
8893 error_at (loc, "cannot decompose class type %qT without non-static "
8894 "data members", type);
8895 goto error_out;
8897 for (tree field = TYPE_FIELDS (btype); field; field = TREE_CHAIN (field))
8898 if (TREE_CODE (field) != FIELD_DECL
8899 || DECL_ARTIFICIAL (field)
8900 || DECL_UNNAMED_BIT_FIELD (field))
8901 continue;
8902 else
8903 eltscnt++;
8904 if (count != eltscnt)
8905 goto cnt_mismatch;
8906 tree t = dexp;
8907 if (type != btype)
8909 t = convert_to_base (t, btype, /*check_access*/true,
8910 /*nonnull*/false, tf_warning_or_error);
8911 type = btype;
8913 unsigned int i = 0;
8914 for (tree field = TYPE_FIELDS (btype); field; field = TREE_CHAIN (field))
8915 if (TREE_CODE (field) != FIELD_DECL
8916 || DECL_ARTIFICIAL (field)
8917 || DECL_UNNAMED_BIT_FIELD (field))
8918 continue;
8919 else
8921 tree tt = finish_non_static_data_member (field, unshare_expr (t),
8922 NULL_TREE);
8923 if (REFERENCE_REF_P (tt))
8924 tt = TREE_OPERAND (tt, 0);
8925 TREE_TYPE (v[i]) = TREE_TYPE (tt);
8926 layout_decl (v[i], 0);
8927 if (!processing_template_decl)
8929 SET_DECL_VALUE_EXPR (v[i], tt);
8930 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
8932 i++;
8935 if (processing_template_decl)
8937 for (unsigned int i = 0; i < count; i++)
8938 if (!DECL_HAS_VALUE_EXPR_P (v[i]))
8940 tree a = build_nt (ARRAY_REF, decl, size_int (i),
8941 NULL_TREE, NULL_TREE);
8942 SET_DECL_VALUE_EXPR (v[i], a);
8943 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
8948 /* Returns a declaration for a VAR_DECL as if:
8950 extern "C" TYPE NAME;
8952 had been seen. Used to create compiler-generated global
8953 variables. */
8955 static tree
8956 declare_global_var (tree name, tree type)
8958 auto cookie = push_abi_namespace (global_namespace);
8959 tree decl = build_decl (input_location, VAR_DECL, name, type);
8960 TREE_PUBLIC (decl) = 1;
8961 DECL_EXTERNAL (decl) = 1;
8962 DECL_ARTIFICIAL (decl) = 1;
8963 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
8964 /* If the user has explicitly declared this variable (perhaps
8965 because the code we are compiling is part of a low-level runtime
8966 library), then it is possible that our declaration will be merged
8967 with theirs by pushdecl. */
8968 decl = pushdecl (decl);
8969 cp_finish_decl (decl, NULL_TREE, false, NULL_TREE, 0);
8970 pop_abi_namespace (cookie, global_namespace);
8972 return decl;
8975 /* Returns the type for the argument to "__cxa_atexit" (or "atexit",
8976 if "__cxa_atexit" is not being used) corresponding to the function
8977 to be called when the program exits. */
8979 static tree
8980 get_atexit_fn_ptr_type (void)
8982 tree fn_type;
8984 if (!atexit_fn_ptr_type_node)
8986 tree arg_type;
8987 if (flag_use_cxa_atexit
8988 && !targetm.cxx.use_atexit_for_cxa_atexit ())
8989 /* The parameter to "__cxa_atexit" is "void (*)(void *)". */
8990 arg_type = ptr_type_node;
8991 else
8992 /* The parameter to "atexit" is "void (*)(void)". */
8993 arg_type = NULL_TREE;
8995 fn_type = build_function_type_list (void_type_node,
8996 arg_type, NULL_TREE);
8997 atexit_fn_ptr_type_node = build_pointer_type (fn_type);
9000 return atexit_fn_ptr_type_node;
9003 /* Returns a pointer to the `atexit' function. Note that if
9004 FLAG_USE_CXA_ATEXIT is nonzero, then this will actually be the new
9005 `__cxa_atexit' function specified in the IA64 C++ ABI. */
9007 static tree
9008 get_atexit_node (void)
9010 tree atexit_fndecl;
9011 tree fn_type;
9012 tree fn_ptr_type;
9013 const char *name;
9014 bool use_aeabi_atexit;
9015 tree ctx = global_namespace;
9017 if (atexit_node)
9018 return atexit_node;
9020 if (flag_use_cxa_atexit && !targetm.cxx.use_atexit_for_cxa_atexit ())
9022 /* The declaration for `__cxa_atexit' is:
9024 int __cxa_atexit (void (*)(void *), void *, void *)
9026 We build up the argument types and then the function type
9027 itself. */
9028 tree argtype0, argtype1, argtype2;
9030 use_aeabi_atexit = targetm.cxx.use_aeabi_atexit ();
9031 /* First, build the pointer-to-function type for the first
9032 argument. */
9033 fn_ptr_type = get_atexit_fn_ptr_type ();
9034 /* Then, build the rest of the argument types. */
9035 argtype2 = ptr_type_node;
9036 if (use_aeabi_atexit)
9038 argtype1 = fn_ptr_type;
9039 argtype0 = ptr_type_node;
9041 else
9043 argtype1 = ptr_type_node;
9044 argtype0 = fn_ptr_type;
9046 /* And the final __cxa_atexit type. */
9047 fn_type = build_function_type_list (integer_type_node,
9048 argtype0, argtype1, argtype2,
9049 NULL_TREE);
9050 /* ... which needs noexcept. */
9051 fn_type = build_exception_variant (fn_type, noexcept_true_spec);
9052 if (use_aeabi_atexit)
9054 name = "__aeabi_atexit";
9055 push_to_top_level ();
9056 int n = push_namespace (get_identifier ("__aeabiv1"), false);
9057 ctx = current_namespace;
9058 while (n--)
9059 pop_namespace ();
9060 pop_from_top_level ();
9062 else
9064 name = "__cxa_atexit";
9065 ctx = abi_node;
9068 else
9070 /* The declaration for `atexit' is:
9072 int atexit (void (*)());
9074 We build up the argument types and then the function type
9075 itself. */
9076 fn_ptr_type = get_atexit_fn_ptr_type ();
9077 /* Build the final atexit type. */
9078 fn_type = build_function_type_list (integer_type_node,
9079 fn_ptr_type, NULL_TREE);
9080 /* ... which needs noexcept. */
9081 fn_type = build_exception_variant (fn_type, noexcept_true_spec);
9082 name = "atexit";
9085 /* Now, build the function declaration. */
9086 push_lang_context (lang_name_c);
9087 auto cookie = push_abi_namespace (ctx);
9088 atexit_fndecl = build_library_fn_ptr (name, fn_type, ECF_LEAF | ECF_NOTHROW);
9089 DECL_CONTEXT (atexit_fndecl) = FROB_CONTEXT (current_namespace);
9090 /* Install as hidden builtin so we're (a) more relaxed about
9091 exception spec matching and (b) will not give a confusing location
9092 in diagnostic and (c) won't magically appear in user-visible name
9093 lookups. */
9094 DECL_SOURCE_LOCATION (atexit_fndecl) = BUILTINS_LOCATION;
9095 atexit_fndecl = pushdecl (atexit_fndecl, /*hiding=*/true);
9096 pop_abi_namespace (cookie, ctx);
9097 mark_used (atexit_fndecl);
9098 pop_lang_context ();
9099 atexit_node = decay_conversion (atexit_fndecl, tf_warning_or_error);
9101 return atexit_node;
9104 /* Like get_atexit_node, but for thread-local cleanups. */
9106 static tree
9107 get_thread_atexit_node (void)
9109 /* The declaration for `__cxa_thread_atexit' is:
9111 int __cxa_thread_atexit (void (*)(void *), void *, void *) */
9112 tree fn_type = build_function_type_list (integer_type_node,
9113 get_atexit_fn_ptr_type (),
9114 ptr_type_node, ptr_type_node,
9115 NULL_TREE);
9117 /* Now, build the function declaration. */
9118 tree atexit_fndecl = build_library_fn_ptr ("__cxa_thread_atexit", fn_type,
9119 ECF_LEAF | ECF_NOTHROW);
9120 return decay_conversion (atexit_fndecl, tf_warning_or_error);
9123 /* Returns the __dso_handle VAR_DECL. */
9125 static tree
9126 get_dso_handle_node (void)
9128 if (dso_handle_node)
9129 return dso_handle_node;
9131 /* Declare the variable. */
9132 dso_handle_node = declare_global_var (get_identifier ("__dso_handle"),
9133 ptr_type_node);
9135 #ifdef HAVE_GAS_HIDDEN
9136 if (dso_handle_node != error_mark_node)
9138 DECL_VISIBILITY (dso_handle_node) = VISIBILITY_HIDDEN;
9139 DECL_VISIBILITY_SPECIFIED (dso_handle_node) = 1;
9141 #endif
9143 return dso_handle_node;
9146 /* Begin a new function with internal linkage whose job will be simply
9147 to destroy some particular variable. */
9149 static GTY(()) int start_cleanup_cnt;
9151 static tree
9152 start_cleanup_fn (void)
9154 char name[32];
9156 push_to_top_level ();
9158 /* No need to mangle this. */
9159 push_lang_context (lang_name_c);
9161 /* Build the name of the function. */
9162 sprintf (name, "__tcf_%d", start_cleanup_cnt++);
9163 /* Build the function declaration. */
9164 tree fntype = TREE_TYPE (get_atexit_fn_ptr_type ());
9165 tree fndecl = build_lang_decl (FUNCTION_DECL, get_identifier (name), fntype);
9166 DECL_CONTEXT (fndecl) = FROB_CONTEXT (current_namespace);
9167 /* It's a function with internal linkage, generated by the
9168 compiler. */
9169 TREE_PUBLIC (fndecl) = 0;
9170 DECL_ARTIFICIAL (fndecl) = 1;
9171 /* Make the function `inline' so that it is only emitted if it is
9172 actually needed. It is unlikely that it will be inlined, since
9173 it is only called via a function pointer, but we avoid unnecessary
9174 emissions this way. */
9175 DECL_DECLARED_INLINE_P (fndecl) = 1;
9176 DECL_INTERFACE_KNOWN (fndecl) = 1;
9177 if (flag_use_cxa_atexit && !targetm.cxx.use_atexit_for_cxa_atexit ())
9179 /* Build the parameter. */
9180 tree parmdecl = cp_build_parm_decl (fndecl, NULL_TREE, ptr_type_node);
9181 TREE_USED (parmdecl) = 1;
9182 DECL_READ_P (parmdecl) = 1;
9183 DECL_ARGUMENTS (fndecl) = parmdecl;
9186 fndecl = pushdecl (fndecl, /*hidden=*/true);
9187 start_preparsed_function (fndecl, NULL_TREE, SF_PRE_PARSED);
9189 pop_lang_context ();
9191 return current_function_decl;
9194 /* Finish the cleanup function begun by start_cleanup_fn. */
9196 static void
9197 end_cleanup_fn (void)
9199 expand_or_defer_fn (finish_function (/*inline_p=*/false));
9201 pop_from_top_level ();
9204 /* Generate code to handle the destruction of DECL, an object with
9205 static storage duration. */
9207 tree
9208 register_dtor_fn (tree decl)
9210 tree cleanup;
9211 tree addr;
9212 tree compound_stmt;
9213 tree fcall;
9214 tree type;
9215 bool ob_parm, dso_parm, use_dtor;
9216 tree arg0, arg1, arg2;
9217 tree atex_node;
9219 type = TREE_TYPE (decl);
9220 if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
9221 return void_node;
9223 if (decl_maybe_constant_destruction (decl, type)
9224 && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
9226 cxx_maybe_build_cleanup (decl, tf_warning_or_error);
9227 return void_node;
9230 /* If we're using "__cxa_atexit" (or "__cxa_thread_atexit" or
9231 "__aeabi_atexit"), and DECL is a class object, we can just pass the
9232 destructor to "__cxa_atexit"; we don't have to build a temporary
9233 function to do the cleanup. */
9234 dso_parm = (flag_use_cxa_atexit
9235 && !targetm.cxx.use_atexit_for_cxa_atexit ());
9236 ob_parm = (CP_DECL_THREAD_LOCAL_P (decl) || dso_parm);
9237 use_dtor = ob_parm && CLASS_TYPE_P (type);
9238 if (use_dtor)
9240 cleanup = get_class_binding (type, complete_dtor_identifier);
9242 /* Make sure it is accessible. */
9243 perform_or_defer_access_check (TYPE_BINFO (type), cleanup, cleanup,
9244 tf_warning_or_error);
9246 else
9248 /* Call build_cleanup before we enter the anonymous function so
9249 that any access checks will be done relative to the current
9250 scope, rather than the scope of the anonymous function. */
9251 build_cleanup (decl);
9253 /* Now start the function. */
9254 cleanup = start_cleanup_fn ();
9256 /* Now, recompute the cleanup. It may contain SAVE_EXPRs that refer
9257 to the original function, rather than the anonymous one. That
9258 will make the back end think that nested functions are in use,
9259 which causes confusion. */
9260 push_deferring_access_checks (dk_no_check);
9261 fcall = build_cleanup (decl);
9262 pop_deferring_access_checks ();
9264 /* Create the body of the anonymous function. */
9265 compound_stmt = begin_compound_stmt (BCS_FN_BODY);
9266 finish_expr_stmt (fcall);
9267 finish_compound_stmt (compound_stmt);
9268 end_cleanup_fn ();
9271 /* Call atexit with the cleanup function. */
9272 mark_used (cleanup);
9273 cleanup = build_address (cleanup);
9275 if (CP_DECL_THREAD_LOCAL_P (decl))
9276 atex_node = get_thread_atexit_node ();
9277 else
9278 atex_node = get_atexit_node ();
9280 if (use_dtor)
9282 /* We must convert CLEANUP to the type that "__cxa_atexit"
9283 expects. */
9284 cleanup = build_nop (get_atexit_fn_ptr_type (), cleanup);
9285 /* "__cxa_atexit" will pass the address of DECL to the
9286 cleanup function. */
9287 mark_used (decl);
9288 addr = build_address (decl);
9289 /* The declared type of the parameter to "__cxa_atexit" is
9290 "void *". For plain "T*", we could just let the
9291 machinery in cp_build_function_call convert it -- but if the
9292 type is "cv-qualified T *", then we need to convert it
9293 before passing it in, to avoid spurious errors. */
9294 addr = build_nop (ptr_type_node, addr);
9296 else
9297 /* Since the cleanup functions we build ignore the address
9298 they're given, there's no reason to pass the actual address
9299 in, and, in general, it's cheaper to pass NULL than any
9300 other value. */
9301 addr = null_pointer_node;
9303 if (dso_parm)
9304 arg2 = cp_build_addr_expr (get_dso_handle_node (),
9305 tf_warning_or_error);
9306 else if (ob_parm)
9307 /* Just pass NULL to the dso handle parm if we don't actually
9308 have a DSO handle on this target. */
9309 arg2 = null_pointer_node;
9310 else
9311 arg2 = NULL_TREE;
9313 if (ob_parm)
9315 if (!CP_DECL_THREAD_LOCAL_P (decl)
9316 && targetm.cxx.use_aeabi_atexit ())
9318 arg1 = cleanup;
9319 arg0 = addr;
9321 else
9323 arg1 = addr;
9324 arg0 = cleanup;
9327 else
9329 arg0 = cleanup;
9330 arg1 = NULL_TREE;
9332 return cp_build_function_call_nary (atex_node, tf_warning_or_error,
9333 arg0, arg1, arg2, NULL_TREE);
9336 /* DECL is a VAR_DECL with static storage duration. INIT, if present,
9337 is its initializer. Generate code to handle the construction
9338 and destruction of DECL. */
9340 static void
9341 expand_static_init (tree decl, tree init)
9343 gcc_assert (VAR_P (decl));
9344 gcc_assert (TREE_STATIC (decl));
9346 /* Some variables require no dynamic initialization. */
9347 if (decl_maybe_constant_destruction (decl, TREE_TYPE (decl)))
9349 /* Make sure the destructor is callable. */
9350 cxx_maybe_build_cleanup (decl, tf_warning_or_error);
9351 if (!init)
9352 return;
9355 if (CP_DECL_THREAD_LOCAL_P (decl) && DECL_GNU_TLS_P (decl)
9356 && !DECL_FUNCTION_SCOPE_P (decl))
9358 location_t dloc = DECL_SOURCE_LOCATION (decl);
9359 if (init)
9360 error_at (dloc, "non-local variable %qD declared %<__thread%> "
9361 "needs dynamic initialization", decl);
9362 else
9363 error_at (dloc, "non-local variable %qD declared %<__thread%> "
9364 "has a non-trivial destructor", decl);
9365 static bool informed;
9366 if (!informed)
9368 inform (dloc, "C++11 %<thread_local%> allows dynamic "
9369 "initialization and destruction");
9370 informed = true;
9372 return;
9375 if (DECL_FUNCTION_SCOPE_P (decl))
9377 /* Emit code to perform this initialization but once. */
9378 tree if_stmt = NULL_TREE, inner_if_stmt = NULL_TREE;
9379 tree then_clause = NULL_TREE, inner_then_clause = NULL_TREE;
9380 tree guard, guard_addr;
9381 tree flag, begin;
9382 /* We don't need thread-safety code for thread-local vars. */
9383 bool thread_guard = (flag_threadsafe_statics
9384 && !CP_DECL_THREAD_LOCAL_P (decl));
9386 /* Emit code to perform this initialization but once. This code
9387 looks like:
9389 static <type> guard;
9390 if (!__atomic_load (guard.first_byte)) {
9391 if (__cxa_guard_acquire (&guard)) {
9392 bool flag = false;
9393 try {
9394 // Do initialization.
9395 flag = true; __cxa_guard_release (&guard);
9396 // Register variable for destruction at end of program.
9397 } catch {
9398 if (!flag) __cxa_guard_abort (&guard);
9403 Note that the `flag' variable is only set to 1 *after* the
9404 initialization is complete. This ensures that an exception,
9405 thrown during the construction, will cause the variable to
9406 reinitialized when we pass through this code again, as per:
9408 [stmt.dcl]
9410 If the initialization exits by throwing an exception, the
9411 initialization is not complete, so it will be tried again
9412 the next time control enters the declaration.
9414 This process should be thread-safe, too; multiple threads
9415 should not be able to initialize the variable more than
9416 once. */
9418 /* Create the guard variable. */
9419 guard = get_guard (decl);
9421 /* Begin the conditional initialization. */
9422 if_stmt = begin_if_stmt ();
9424 finish_if_stmt_cond (get_guard_cond (guard, thread_guard), if_stmt);
9425 then_clause = begin_compound_stmt (BCS_NO_SCOPE);
9427 if (thread_guard)
9429 tree vfntype = NULL_TREE;
9430 tree acquire_name, release_name, abort_name;
9431 tree acquire_fn, release_fn, abort_fn;
9432 guard_addr = build_address (guard);
9434 acquire_name = get_identifier ("__cxa_guard_acquire");
9435 release_name = get_identifier ("__cxa_guard_release");
9436 abort_name = get_identifier ("__cxa_guard_abort");
9437 acquire_fn = get_global_binding (acquire_name);
9438 release_fn = get_global_binding (release_name);
9439 abort_fn = get_global_binding (abort_name);
9440 if (!acquire_fn)
9441 acquire_fn = push_library_fn
9442 (acquire_name, build_function_type_list (integer_type_node,
9443 TREE_TYPE (guard_addr),
9444 NULL_TREE),
9445 NULL_TREE, ECF_NOTHROW);
9446 if (!release_fn || !abort_fn)
9447 vfntype = build_function_type_list (void_type_node,
9448 TREE_TYPE (guard_addr),
9449 NULL_TREE);
9450 if (!release_fn)
9451 release_fn = push_library_fn (release_name, vfntype, NULL_TREE,
9452 ECF_NOTHROW);
9453 if (!abort_fn)
9454 abort_fn = push_library_fn (abort_name, vfntype, NULL_TREE,
9455 ECF_NOTHROW | ECF_LEAF);
9457 inner_if_stmt = begin_if_stmt ();
9458 finish_if_stmt_cond (build_call_n (acquire_fn, 1, guard_addr),
9459 inner_if_stmt);
9461 inner_then_clause = begin_compound_stmt (BCS_NO_SCOPE);
9462 begin = get_target_expr (boolean_false_node);
9463 flag = TARGET_EXPR_SLOT (begin);
9465 TARGET_EXPR_CLEANUP (begin)
9466 = build3 (COND_EXPR, void_type_node, flag,
9467 void_node,
9468 build_call_n (abort_fn, 1, guard_addr));
9469 CLEANUP_EH_ONLY (begin) = 1;
9471 /* Do the initialization itself. */
9472 init = add_stmt_to_compound (begin, init);
9473 init = add_stmt_to_compound (init,
9474 build2 (MODIFY_EXPR, void_type_node,
9475 flag, boolean_true_node));
9477 /* Use atexit to register a function for destroying this static
9478 variable. Do this before calling __cxa_guard_release. */
9479 init = add_stmt_to_compound (init, register_dtor_fn (decl));
9481 init = add_stmt_to_compound (init, build_call_n (release_fn, 1,
9482 guard_addr));
9484 else
9486 init = add_stmt_to_compound (init, set_guard (guard));
9488 /* Use atexit to register a function for destroying this static
9489 variable. */
9490 init = add_stmt_to_compound (init, register_dtor_fn (decl));
9493 finish_expr_stmt (init);
9495 if (thread_guard)
9497 finish_compound_stmt (inner_then_clause);
9498 finish_then_clause (inner_if_stmt);
9499 finish_if_stmt (inner_if_stmt);
9502 finish_compound_stmt (then_clause);
9503 finish_then_clause (if_stmt);
9504 finish_if_stmt (if_stmt);
9506 else if (CP_DECL_THREAD_LOCAL_P (decl))
9507 tls_aggregates = tree_cons (init, decl, tls_aggregates);
9508 else
9509 static_aggregates = tree_cons (init, decl, static_aggregates);
9513 /* Make TYPE a complete type based on INITIAL_VALUE.
9514 Return 0 if successful, 1 if INITIAL_VALUE can't be deciphered,
9515 2 if there was no information (in which case assume 0 if DO_DEFAULT),
9516 3 if the initializer list is empty (in pedantic mode). */
9519 cp_complete_array_type (tree *ptype, tree initial_value, bool do_default)
9521 int failure;
9522 tree type, elt_type;
9524 /* Don't get confused by a CONSTRUCTOR for some other type. */
9525 if (initial_value && TREE_CODE (initial_value) == CONSTRUCTOR
9526 && !BRACE_ENCLOSED_INITIALIZER_P (initial_value)
9527 && TREE_CODE (TREE_TYPE (initial_value)) != ARRAY_TYPE)
9528 return 1;
9530 if (initial_value)
9532 /* An array of character type can be initialized from a
9533 brace-enclosed string constant.
9535 FIXME: this code is duplicated from reshape_init. Probably
9536 we should just call reshape_init here? */
9537 if (char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (*ptype)))
9538 && TREE_CODE (initial_value) == CONSTRUCTOR
9539 && !vec_safe_is_empty (CONSTRUCTOR_ELTS (initial_value)))
9541 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (initial_value);
9542 tree value = (*v)[0].value;
9543 STRIP_ANY_LOCATION_WRAPPER (value);
9545 if (TREE_CODE (value) == STRING_CST
9546 && v->length () == 1)
9547 initial_value = value;
9550 /* If any of the elements are parameter packs, we can't actually
9551 complete this type now because the array size is dependent. */
9552 if (TREE_CODE (initial_value) == CONSTRUCTOR)
9553 for (auto &e: CONSTRUCTOR_ELTS (initial_value))
9554 if (PACK_EXPANSION_P (e.value))
9555 return 0;
9558 failure = complete_array_type (ptype, initial_value, do_default);
9560 /* We can create the array before the element type is complete, which
9561 means that we didn't have these two bits set in the original type
9562 either. In completing the type, we are expected to propagate these
9563 bits. See also complete_type which does the same thing for arrays
9564 of fixed size. */
9565 type = *ptype;
9566 if (type != error_mark_node && TYPE_DOMAIN (type))
9568 elt_type = TREE_TYPE (type);
9569 TYPE_NEEDS_CONSTRUCTING (type) = TYPE_NEEDS_CONSTRUCTING (elt_type);
9570 TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
9571 = TYPE_HAS_NONTRIVIAL_DESTRUCTOR (elt_type);
9574 return failure;
9577 /* As above, but either give an error or reject zero-size arrays, depending
9578 on COMPLAIN. */
9581 cp_complete_array_type_or_error (tree *ptype, tree initial_value,
9582 bool do_default, tsubst_flags_t complain)
9584 int failure;
9585 bool sfinae = !(complain & tf_error);
9586 /* In SFINAE context we can't be lenient about zero-size arrays. */
9587 if (sfinae)
9588 ++pedantic;
9589 failure = cp_complete_array_type (ptype, initial_value, do_default);
9590 if (sfinae)
9591 --pedantic;
9592 if (failure)
9594 if (sfinae)
9595 /* Not an error. */;
9596 else if (failure == 1)
9597 error ("initializer fails to determine size of %qT", *ptype);
9598 else if (failure == 2)
9600 if (do_default)
9601 error ("array size missing in %qT", *ptype);
9603 else if (failure == 3)
9604 error ("zero-size array %qT", *ptype);
9605 *ptype = error_mark_node;
9607 return failure;
9610 /* Return zero if something is declared to be a member of type
9611 CTYPE when in the context of CUR_TYPE. STRING is the error
9612 message to print in that case. Otherwise, quietly return 1. */
9614 static int
9615 member_function_or_else (tree ctype, tree cur_type, enum overload_flags flags)
9617 if (ctype && ctype != cur_type)
9619 if (flags == DTOR_FLAG)
9620 error ("destructor for alien class %qT cannot be a member", ctype);
9621 else
9622 error ("constructor for alien class %qT cannot be a member", ctype);
9623 return 0;
9625 return 1;
9628 /* Subroutine of `grokdeclarator'. */
9630 /* Generate errors possibly applicable for a given set of specifiers.
9631 This is for ARM $7.1.2. */
9633 static void
9634 bad_specifiers (tree object,
9635 enum bad_spec_place type,
9636 int virtualp,
9637 int quals,
9638 int inlinep,
9639 int friendp,
9640 int raises,
9641 const location_t* locations)
9643 switch (type)
9645 case BSP_VAR:
9646 if (virtualp)
9647 error_at (locations[ds_virtual],
9648 "%qD declared as a %<virtual%> variable", object);
9649 if (quals)
9650 error ("%<const%> and %<volatile%> function specifiers on "
9651 "%qD invalid in variable declaration", object);
9652 break;
9653 case BSP_PARM:
9654 if (virtualp)
9655 error_at (locations[ds_virtual],
9656 "%qD declared as a %<virtual%> parameter", object);
9657 if (inlinep)
9658 error_at (locations[ds_inline],
9659 "%qD declared as an %<inline%> parameter", object);
9660 if (quals)
9661 error ("%<const%> and %<volatile%> function specifiers on "
9662 "%qD invalid in parameter declaration", object);
9663 break;
9664 case BSP_TYPE:
9665 if (virtualp)
9666 error_at (locations[ds_virtual],
9667 "%qD declared as a %<virtual%> type", object);
9668 if (inlinep)
9669 error_at (locations[ds_inline],
9670 "%qD declared as an %<inline%> type", object);
9671 if (quals)
9672 error ("%<const%> and %<volatile%> function specifiers on "
9673 "%qD invalid in type declaration", object);
9674 break;
9675 case BSP_FIELD:
9676 if (virtualp)
9677 error_at (locations[ds_virtual],
9678 "%qD declared as a %<virtual%> field", object);
9679 if (inlinep)
9680 error_at (locations[ds_inline],
9681 "%qD declared as an %<inline%> field", object);
9682 if (quals)
9683 error ("%<const%> and %<volatile%> function specifiers on "
9684 "%qD invalid in field declaration", object);
9685 break;
9686 default:
9687 gcc_unreachable();
9689 if (friendp)
9690 error ("%q+D declared as a friend", object);
9691 if (raises
9692 && !flag_noexcept_type
9693 && (TREE_CODE (object) == TYPE_DECL
9694 || (!TYPE_PTRFN_P (TREE_TYPE (object))
9695 && !TYPE_REFFN_P (TREE_TYPE (object))
9696 && !TYPE_PTRMEMFUNC_P (TREE_TYPE (object)))))
9697 error ("%q+D declared with an exception specification", object);
9700 /* DECL is a member function or static data member and is presently
9701 being defined. Check that the definition is taking place in a
9702 valid namespace. */
9704 static void
9705 check_class_member_definition_namespace (tree decl)
9707 /* These checks only apply to member functions and static data
9708 members. */
9709 gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
9710 /* We check for problems with specializations in pt.c in
9711 check_specialization_namespace, where we can issue better
9712 diagnostics. */
9713 if (processing_specialization)
9714 return;
9715 /* We check this in check_explicit_instantiation_namespace. */
9716 if (processing_explicit_instantiation)
9717 return;
9718 /* [class.mfct]
9720 A member function definition that appears outside of the
9721 class definition shall appear in a namespace scope enclosing
9722 the class definition.
9724 [class.static.data]
9726 The definition for a static data member shall appear in a
9727 namespace scope enclosing the member's class definition. */
9728 if (!is_ancestor (current_namespace, DECL_CONTEXT (decl)))
9729 permerror (input_location, "definition of %qD is not in namespace enclosing %qT",
9730 decl, DECL_CONTEXT (decl));
9733 /* Build a PARM_DECL for the "this" parameter of FN. TYPE is the
9734 METHOD_TYPE for a non-static member function; QUALS are the
9735 cv-qualifiers that apply to the function. */
9737 tree
9738 build_this_parm (tree fn, tree type, cp_cv_quals quals)
9740 tree this_type;
9741 tree qual_type;
9742 tree parm;
9743 cp_cv_quals this_quals;
9745 if (CLASS_TYPE_P (type))
9747 this_type
9748 = cp_build_qualified_type (type, quals & ~TYPE_QUAL_RESTRICT);
9749 this_type = build_pointer_type (this_type);
9751 else
9752 this_type = type_of_this_parm (type);
9753 /* The `this' parameter is implicitly `const'; it cannot be
9754 assigned to. */
9755 this_quals = (quals & TYPE_QUAL_RESTRICT) | TYPE_QUAL_CONST;
9756 qual_type = cp_build_qualified_type (this_type, this_quals);
9757 parm = build_artificial_parm (fn, this_identifier, qual_type);
9758 cp_apply_type_quals_to_decl (this_quals, parm);
9759 return parm;
9762 /* DECL is a static member function. Complain if it was declared
9763 with function-cv-quals. */
9765 static void
9766 check_static_quals (tree decl, cp_cv_quals quals)
9768 if (quals != TYPE_UNQUALIFIED)
9769 error ("static member function %q#D declared with type qualifiers",
9770 decl);
9773 // Check that FN takes no arguments and returns bool.
9774 static void
9775 check_concept_fn (tree fn)
9777 // A constraint is nullary.
9778 if (DECL_ARGUMENTS (fn))
9779 error_at (DECL_SOURCE_LOCATION (fn),
9780 "concept %q#D declared with function parameters", fn);
9782 // The declared return type of the concept shall be bool, and
9783 // it shall not be deduced from it definition.
9784 tree type = TREE_TYPE (TREE_TYPE (fn));
9785 if (is_auto (type))
9786 error_at (DECL_SOURCE_LOCATION (fn),
9787 "concept %q#D declared with a deduced return type", fn);
9788 else if (type != boolean_type_node)
9789 error_at (DECL_SOURCE_LOCATION (fn),
9790 "concept %q#D with non-%<bool%> return type %qT", fn, type);
9793 /* Helper function. Replace the temporary this parameter injected
9794 during cp_finish_omp_declare_simd with the real this parameter. */
9796 static tree
9797 declare_simd_adjust_this (tree *tp, int *walk_subtrees, void *data)
9799 tree this_parm = (tree) data;
9800 if (TREE_CODE (*tp) == PARM_DECL
9801 && DECL_NAME (*tp) == this_identifier
9802 && *tp != this_parm)
9803 *tp = this_parm;
9804 else if (TYPE_P (*tp))
9805 *walk_subtrees = 0;
9806 return NULL_TREE;
9809 /* CTYPE is class type, or null if non-class.
9810 TYPE is type this FUNCTION_DECL should have, either FUNCTION_TYPE
9811 or METHOD_TYPE.
9812 DECLARATOR is the function's name.
9813 PARMS is a chain of PARM_DECLs for the function.
9814 VIRTUALP is truthvalue of whether the function is virtual or not.
9815 FLAGS are to be passed through to `grokclassfn'.
9816 QUALS are qualifiers indicating whether the function is `const'
9817 or `volatile'.
9818 RAISES is a list of exceptions that this function can raise.
9819 CHECK is 1 if we must find this method in CTYPE, 0 if we should
9820 not look, and -1 if we should not call `grokclassfn' at all.
9822 SFK is the kind of special function (if any) for the new function.
9824 Returns `NULL_TREE' if something goes wrong, after issuing
9825 applicable error messages. */
9827 static tree
9828 grokfndecl (tree ctype,
9829 tree type,
9830 tree declarator,
9831 tree parms,
9832 tree orig_declarator,
9833 const cp_decl_specifier_seq *declspecs,
9834 tree decl_reqs,
9835 int virtualp,
9836 enum overload_flags flags,
9837 cp_cv_quals quals,
9838 cp_ref_qualifier rqual,
9839 tree raises,
9840 int check,
9841 int friendp,
9842 int publicp,
9843 int inlinep,
9844 bool deletedp,
9845 special_function_kind sfk,
9846 bool funcdef_flag,
9847 bool late_return_type_p,
9848 int template_count,
9849 tree in_namespace,
9850 tree* attrlist,
9851 location_t location)
9853 tree decl;
9854 int staticp = ctype && TREE_CODE (type) == FUNCTION_TYPE;
9855 tree t;
9857 if (location == UNKNOWN_LOCATION)
9858 location = input_location;
9860 /* Was the concept specifier present? */
9861 bool concept_p = inlinep & 4;
9863 /* Concept declarations must have a corresponding definition. */
9864 if (concept_p && !funcdef_flag)
9866 error_at (location, "concept %qD has no definition", declarator);
9867 return NULL_TREE;
9870 type = build_cp_fntype_variant (type, rqual, raises, late_return_type_p);
9872 decl = build_lang_decl_loc (location, FUNCTION_DECL, declarator, type);
9874 /* Set the constraints on the declaration. */
9875 if (flag_concepts)
9877 tree tmpl_reqs = NULL_TREE;
9878 tree ctx = friendp ? current_class_type : ctype;
9879 bool block_local = TREE_CODE (current_scope ()) == FUNCTION_DECL;
9880 bool memtmpl = (!block_local
9881 && (current_template_depth
9882 > template_class_depth (ctx)));
9883 if (memtmpl)
9885 if (!current_template_parms)
9886 /* If there are no template parameters, something must have
9887 gone wrong. */
9888 gcc_assert (seen_error ());
9889 else
9890 tmpl_reqs = TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
9892 tree ci = build_constraints (tmpl_reqs, decl_reqs);
9893 if (concept_p && ci)
9895 error_at (location, "a function concept cannot be constrained");
9896 ci = NULL_TREE;
9898 /* C++20 CA378: Remove non-templated constrained functions. */
9899 if (ci
9900 && (block_local
9901 || (!flag_concepts_ts
9902 && (!processing_template_decl
9903 || (friendp && !memtmpl && !funcdef_flag)))))
9905 error_at (location, "constraints on a non-templated function");
9906 ci = NULL_TREE;
9908 set_constraints (decl, ci);
9911 if (TREE_CODE (type) == METHOD_TYPE)
9913 tree parm = build_this_parm (decl, type, quals);
9914 DECL_CHAIN (parm) = parms;
9915 parms = parm;
9917 /* Allocate space to hold the vptr bit if needed. */
9918 SET_DECL_ALIGN (decl, MINIMUM_METHOD_BOUNDARY);
9921 DECL_ARGUMENTS (decl) = parms;
9922 for (t = parms; t; t = DECL_CHAIN (t))
9923 DECL_CONTEXT (t) = decl;
9925 /* Propagate volatile out from type to decl. */
9926 if (TYPE_VOLATILE (type))
9927 TREE_THIS_VOLATILE (decl) = 1;
9929 /* Setup decl according to sfk. */
9930 switch (sfk)
9932 case sfk_constructor:
9933 case sfk_copy_constructor:
9934 case sfk_move_constructor:
9935 DECL_CXX_CONSTRUCTOR_P (decl) = 1;
9936 DECL_NAME (decl) = ctor_identifier;
9937 break;
9938 case sfk_destructor:
9939 DECL_CXX_DESTRUCTOR_P (decl) = 1;
9940 DECL_NAME (decl) = dtor_identifier;
9941 break;
9942 default:
9943 break;
9946 if (friendp && TREE_CODE (orig_declarator) == TEMPLATE_ID_EXPR)
9948 if (funcdef_flag)
9949 error_at (location,
9950 "defining explicit specialization %qD in friend declaration",
9951 orig_declarator);
9952 else
9954 tree fns = TREE_OPERAND (orig_declarator, 0);
9955 tree args = TREE_OPERAND (orig_declarator, 1);
9957 if (PROCESSING_REAL_TEMPLATE_DECL_P ())
9959 /* Something like `template <class T> friend void f<T>()'. */
9960 error_at (location,
9961 "invalid use of template-id %qD in declaration "
9962 "of primary template",
9963 orig_declarator);
9964 return NULL_TREE;
9968 /* A friend declaration of the form friend void f<>(). Record
9969 the information in the TEMPLATE_ID_EXPR. */
9970 SET_DECL_IMPLICIT_INSTANTIATION (decl);
9972 gcc_assert (identifier_p (fns) || OVL_P (fns));
9973 DECL_TEMPLATE_INFO (decl) = build_template_info (fns, args);
9975 for (t = TYPE_ARG_TYPES (TREE_TYPE (decl)); t; t = TREE_CHAIN (t))
9976 if (TREE_PURPOSE (t)
9977 && TREE_CODE (TREE_PURPOSE (t)) == DEFERRED_PARSE)
9979 error_at (defparse_location (TREE_PURPOSE (t)),
9980 "default arguments are not allowed in declaration "
9981 "of friend template specialization %qD",
9982 decl);
9983 return NULL_TREE;
9986 if (inlinep & 1)
9988 error_at (declspecs->locations[ds_inline],
9989 "%<inline%> is not allowed in declaration of friend "
9990 "template specialization %qD",
9991 decl);
9992 return NULL_TREE;
9997 /* C++17 11.3.6/4: "If a friend declaration specifies a default argument
9998 expression, that declaration shall be a definition..." */
9999 if (friendp && !funcdef_flag)
10001 for (tree t = FUNCTION_FIRST_USER_PARMTYPE (decl);
10002 t && t != void_list_node; t = TREE_CHAIN (t))
10003 if (TREE_PURPOSE (t))
10005 permerror (DECL_SOURCE_LOCATION (decl),
10006 "friend declaration of %qD specifies default "
10007 "arguments and isn%'t a definition", decl);
10008 break;
10012 /* If this decl has namespace scope, set that up. */
10013 if (in_namespace)
10014 set_decl_namespace (decl, in_namespace, friendp);
10015 else if (ctype)
10016 DECL_CONTEXT (decl) = ctype;
10017 else
10018 DECL_CONTEXT (decl) = FROB_CONTEXT (current_decl_namespace ());
10020 /* `main' and builtins have implicit 'C' linkage. */
10021 if (ctype == NULL_TREE
10022 && DECL_FILE_SCOPE_P (decl)
10023 && current_lang_name == lang_name_cplusplus
10024 && (MAIN_NAME_P (declarator)
10025 || (IDENTIFIER_LENGTH (declarator) > 10
10026 && IDENTIFIER_POINTER (declarator)[0] == '_'
10027 && IDENTIFIER_POINTER (declarator)[1] == '_'
10028 && startswith (IDENTIFIER_POINTER (declarator) + 2,
10029 "builtin_"))
10030 || (targetcm.cxx_implicit_extern_c
10031 && (targetcm.cxx_implicit_extern_c
10032 (IDENTIFIER_POINTER (declarator))))))
10033 SET_DECL_LANGUAGE (decl, lang_c);
10035 /* Should probably propagate const out from type to decl I bet (mrs). */
10036 if (staticp)
10038 DECL_STATIC_FUNCTION_P (decl) = 1;
10039 DECL_CONTEXT (decl) = ctype;
10042 if (deletedp)
10043 DECL_DELETED_FN (decl) = 1;
10045 if (ctype && funcdef_flag)
10046 check_class_member_definition_namespace (decl);
10048 if (ctype == NULL_TREE && DECL_MAIN_P (decl))
10050 if (PROCESSING_REAL_TEMPLATE_DECL_P())
10051 error_at (location, "cannot declare %<::main%> to be a template");
10052 if (inlinep & 1)
10053 error_at (declspecs->locations[ds_inline],
10054 "cannot declare %<::main%> to be inline");
10055 if (inlinep & 2)
10056 error_at (declspecs->locations[ds_constexpr],
10057 "cannot declare %<::main%> to be %qs", "constexpr");
10058 if (inlinep & 8)
10059 error_at (declspecs->locations[ds_consteval],
10060 "cannot declare %<::main%> to be %qs", "consteval");
10061 if (!publicp)
10062 error_at (location, "cannot declare %<::main%> to be static");
10063 inlinep = 0;
10064 publicp = 1;
10067 /* Members of anonymous types and local classes have no linkage; make
10068 them internal. If a typedef is made later, this will be changed. */
10069 if (ctype && (!TREE_PUBLIC (TYPE_MAIN_DECL (ctype))
10070 || decl_function_context (TYPE_MAIN_DECL (ctype))))
10071 publicp = 0;
10073 if (publicp && cxx_dialect == cxx98)
10075 /* [basic.link]: A name with no linkage (notably, the name of a class
10076 or enumeration declared in a local scope) shall not be used to
10077 declare an entity with linkage.
10079 DR 757 relaxes this restriction for C++0x. */
10080 no_linkage_error (decl);
10083 TREE_PUBLIC (decl) = publicp;
10084 if (! publicp)
10086 DECL_INTERFACE_KNOWN (decl) = 1;
10087 DECL_NOT_REALLY_EXTERN (decl) = 1;
10090 /* If the declaration was declared inline, mark it as such. */
10091 if (inlinep)
10093 DECL_DECLARED_INLINE_P (decl) = 1;
10094 if (publicp)
10095 DECL_COMDAT (decl) = 1;
10097 if (inlinep & 2)
10098 DECL_DECLARED_CONSTEXPR_P (decl) = true;
10099 else if (inlinep & 8)
10101 DECL_DECLARED_CONSTEXPR_P (decl) = true;
10102 SET_DECL_IMMEDIATE_FUNCTION_P (decl);
10105 // If the concept declaration specifier was found, check
10106 // that the declaration satisfies the necessary requirements.
10107 if (concept_p)
10109 DECL_DECLARED_CONCEPT_P (decl) = true;
10110 check_concept_fn (decl);
10113 DECL_EXTERNAL (decl) = 1;
10114 if (TREE_CODE (type) == FUNCTION_TYPE)
10116 if (quals || rqual)
10117 TREE_TYPE (decl) = apply_memfn_quals (TREE_TYPE (decl),
10118 TYPE_UNQUALIFIED,
10119 REF_QUAL_NONE);
10121 if (quals)
10123 error (ctype
10124 ? G_("static member function %qD cannot have cv-qualifier")
10125 : G_("non-member function %qD cannot have cv-qualifier"),
10126 decl);
10127 quals = TYPE_UNQUALIFIED;
10130 if (rqual)
10132 error (ctype
10133 ? G_("static member function %qD cannot have ref-qualifier")
10134 : G_("non-member function %qD cannot have ref-qualifier"),
10135 decl);
10136 rqual = REF_QUAL_NONE;
10140 if (deduction_guide_p (decl))
10142 tree type = TREE_TYPE (DECL_NAME (decl));
10143 if (in_namespace == NULL_TREE
10144 && CP_DECL_CONTEXT (decl) != CP_TYPE_CONTEXT (type))
10146 error_at (location, "deduction guide %qD must be declared in the "
10147 "same scope as %qT", decl, type);
10148 inform (location_of (type), " declared here");
10149 return NULL_TREE;
10151 if (DECL_CLASS_SCOPE_P (decl)
10152 && current_access_specifier != declared_access (TYPE_NAME (type)))
10154 error_at (location, "deduction guide %qD must have the same access "
10155 "as %qT", decl, type);
10156 inform (location_of (type), " declared here");
10158 if (funcdef_flag)
10159 error_at (location,
10160 "deduction guide %qD must not have a function body", decl);
10162 else if (IDENTIFIER_ANY_OP_P (DECL_NAME (decl))
10163 && !grok_op_properties (decl, /*complain=*/true))
10164 return NULL_TREE;
10165 else if (UDLIT_OPER_P (DECL_NAME (decl)))
10167 bool long_long_unsigned_p;
10168 bool long_double_p;
10169 const char *suffix = NULL;
10170 /* [over.literal]/6: Literal operators shall not have C linkage. */
10171 if (DECL_LANGUAGE (decl) == lang_c)
10173 error_at (location, "literal operator with C linkage");
10174 maybe_show_extern_c_location ();
10175 return NULL_TREE;
10178 if (DECL_NAMESPACE_SCOPE_P (decl))
10180 if (!check_literal_operator_args (decl, &long_long_unsigned_p,
10181 &long_double_p))
10183 error_at (location, "%qD has invalid argument list", decl);
10184 return NULL_TREE;
10187 suffix = UDLIT_OP_SUFFIX (DECL_NAME (decl));
10188 if (long_long_unsigned_p)
10190 if (cpp_interpret_int_suffix (parse_in, suffix, strlen (suffix)))
10191 warning_at (location, 0, "integer suffix %qs"
10192 " shadowed by implementation", suffix);
10194 else if (long_double_p)
10196 if (cpp_interpret_float_suffix (parse_in, suffix, strlen (suffix)))
10197 warning_at (location, 0, "floating-point suffix %qs"
10198 " shadowed by implementation", suffix);
10200 /* 17.6.3.3.5 */
10201 if (suffix[0] != '_'
10202 && !current_function_decl && !(friendp && !funcdef_flag))
10203 warning_at (location, OPT_Wliteral_suffix,
10204 "literal operator suffixes not preceded by %<_%>"
10205 " are reserved for future standardization");
10207 else
10209 error_at (location, "%qD must be a non-member function", decl);
10210 return NULL_TREE;
10214 if (funcdef_flag)
10215 /* Make the init_value nonzero so pushdecl knows this is not
10216 tentative. error_mark_node is replaced later with the BLOCK. */
10217 DECL_INITIAL (decl) = error_mark_node;
10219 if (TYPE_NOTHROW_P (type) || nothrow_libfn_p (decl))
10220 TREE_NOTHROW (decl) = 1;
10222 if (flag_openmp || flag_openmp_simd)
10224 /* Adjust "omp declare simd" attributes. */
10225 tree ods = lookup_attribute ("omp declare simd", *attrlist);
10226 if (ods)
10228 tree attr;
10229 for (attr = ods; attr;
10230 attr = lookup_attribute ("omp declare simd", TREE_CHAIN (attr)))
10232 if (TREE_CODE (type) == METHOD_TYPE)
10233 walk_tree (&TREE_VALUE (attr), declare_simd_adjust_this,
10234 DECL_ARGUMENTS (decl), NULL);
10235 if (TREE_VALUE (attr) != NULL_TREE)
10237 tree cl = TREE_VALUE (TREE_VALUE (attr));
10238 cl = c_omp_declare_simd_clauses_to_numbers
10239 (DECL_ARGUMENTS (decl), cl);
10240 if (cl)
10241 TREE_VALUE (TREE_VALUE (attr)) = cl;
10242 else
10243 TREE_VALUE (attr) = NULL_TREE;
10249 /* Caller will do the rest of this. */
10250 if (check < 0)
10251 return decl;
10253 if (ctype != NULL_TREE)
10254 grokclassfn (ctype, decl, flags);
10256 /* 12.4/3 */
10257 if (cxx_dialect >= cxx11
10258 && DECL_DESTRUCTOR_P (decl)
10259 && !TYPE_BEING_DEFINED (DECL_CONTEXT (decl))
10260 && !processing_template_decl)
10261 deduce_noexcept_on_destructor (decl);
10263 set_originating_module (decl);
10265 decl = check_explicit_specialization (orig_declarator, decl,
10266 template_count,
10267 2 * funcdef_flag +
10268 4 * (friendp != 0) +
10269 8 * concept_p,
10270 *attrlist);
10271 if (decl == error_mark_node)
10272 return NULL_TREE;
10274 if (DECL_STATIC_FUNCTION_P (decl))
10275 check_static_quals (decl, quals);
10277 if (attrlist)
10279 cplus_decl_attributes (&decl, *attrlist, 0);
10280 *attrlist = NULL_TREE;
10283 /* Check main's type after attributes have been applied. */
10284 if (ctype == NULL_TREE && DECL_MAIN_P (decl))
10286 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
10287 integer_type_node))
10289 tree oldtypeargs = TYPE_ARG_TYPES (TREE_TYPE (decl));
10290 tree newtype;
10291 error_at (declspecs->locations[ds_type_spec],
10292 "%<::main%> must return %<int%>");
10293 newtype = build_function_type (integer_type_node, oldtypeargs);
10294 TREE_TYPE (decl) = newtype;
10296 if (warn_main)
10297 check_main_parameter_types (decl);
10300 if (ctype != NULL_TREE && check)
10302 tree old_decl = check_classfn (ctype, decl,
10303 (current_template_depth
10304 > template_class_depth (ctype))
10305 ? current_template_parms
10306 : NULL_TREE);
10308 if (old_decl == error_mark_node)
10309 return NULL_TREE;
10311 if (old_decl)
10313 tree ok;
10314 tree pushed_scope;
10316 if (TREE_CODE (old_decl) == TEMPLATE_DECL)
10317 /* Because grokfndecl is always supposed to return a
10318 FUNCTION_DECL, we pull out the DECL_TEMPLATE_RESULT
10319 here. We depend on our callers to figure out that its
10320 really a template that's being returned. */
10321 old_decl = DECL_TEMPLATE_RESULT (old_decl);
10323 if (DECL_STATIC_FUNCTION_P (old_decl)
10324 && TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
10326 /* Remove the `this' parm added by grokclassfn. */
10327 revert_static_member_fn (decl);
10328 check_static_quals (decl, quals);
10330 if (DECL_ARTIFICIAL (old_decl))
10332 error ("definition of implicitly-declared %qD", old_decl);
10333 return NULL_TREE;
10335 else if (DECL_DEFAULTED_FN (old_decl))
10337 error ("definition of explicitly-defaulted %q+D", decl);
10338 inform (DECL_SOURCE_LOCATION (old_decl),
10339 "%q#D explicitly defaulted here", old_decl);
10340 return NULL_TREE;
10343 /* Since we've smashed OLD_DECL to its
10344 DECL_TEMPLATE_RESULT, we must do the same to DECL. */
10345 if (TREE_CODE (decl) == TEMPLATE_DECL)
10346 decl = DECL_TEMPLATE_RESULT (decl);
10348 /* Attempt to merge the declarations. This can fail, in
10349 the case of some invalid specialization declarations. */
10350 pushed_scope = push_scope (ctype);
10351 ok = duplicate_decls (decl, old_decl);
10352 if (pushed_scope)
10353 pop_scope (pushed_scope);
10354 if (!ok)
10356 error ("no %q#D member function declared in class %qT",
10357 decl, ctype);
10358 return NULL_TREE;
10360 if (ok == error_mark_node)
10361 return NULL_TREE;
10362 return old_decl;
10366 if (DECL_CONSTRUCTOR_P (decl) && !grok_ctor_properties (ctype, decl))
10367 return NULL_TREE;
10369 if (ctype == NULL_TREE || check)
10370 return decl;
10372 if (virtualp)
10373 DECL_VIRTUAL_P (decl) = 1;
10375 return decl;
10378 /* decl is a FUNCTION_DECL.
10379 specifiers are the parsed virt-specifiers.
10381 Set flags to reflect the virt-specifiers.
10383 Returns decl. */
10385 static tree
10386 set_virt_specifiers (tree decl, cp_virt_specifiers specifiers)
10388 if (decl == NULL_TREE)
10389 return decl;
10390 if (specifiers & VIRT_SPEC_OVERRIDE)
10391 DECL_OVERRIDE_P (decl) = 1;
10392 if (specifiers & VIRT_SPEC_FINAL)
10393 DECL_FINAL_P (decl) = 1;
10394 return decl;
10397 /* DECL is a VAR_DECL for a static data member. Set flags to reflect
10398 the linkage that DECL will receive in the object file. */
10400 static void
10401 set_linkage_for_static_data_member (tree decl)
10403 /* A static data member always has static storage duration and
10404 external linkage. Note that static data members are forbidden in
10405 local classes -- the only situation in which a class has
10406 non-external linkage. */
10407 TREE_PUBLIC (decl) = 1;
10408 TREE_STATIC (decl) = 1;
10409 /* For non-template classes, static data members are always put
10410 out in exactly those files where they are defined, just as
10411 with ordinary namespace-scope variables. */
10412 if (!processing_template_decl)
10413 DECL_INTERFACE_KNOWN (decl) = 1;
10416 /* Create a VAR_DECL named NAME with the indicated TYPE.
10418 If SCOPE is non-NULL, it is the class type or namespace containing
10419 the variable. If SCOPE is NULL, the variable should is created in
10420 the innermost enclosing scope. */
10422 static tree
10423 grokvardecl (tree type,
10424 tree name,
10425 tree orig_declarator,
10426 const cp_decl_specifier_seq *declspecs,
10427 int initialized,
10428 int type_quals,
10429 int inlinep,
10430 bool conceptp,
10431 int template_count,
10432 tree scope,
10433 location_t location)
10435 tree decl;
10436 tree explicit_scope;
10438 gcc_assert (!name || identifier_p (name));
10440 bool constp = (type_quals & TYPE_QUAL_CONST) != 0;
10441 bool volatilep = (type_quals & TYPE_QUAL_VOLATILE) != 0;
10443 /* Compute the scope in which to place the variable, but remember
10444 whether or not that scope was explicitly specified by the user. */
10445 explicit_scope = scope;
10446 if (!scope)
10448 /* An explicit "extern" specifier indicates a namespace-scope
10449 variable. */
10450 if (declspecs->storage_class == sc_extern)
10451 scope = current_decl_namespace ();
10452 else if (!at_function_scope_p ())
10453 scope = current_scope ();
10456 if (scope
10457 && (/* If the variable is a namespace-scope variable declared in a
10458 template, we need DECL_LANG_SPECIFIC. */
10459 (TREE_CODE (scope) == NAMESPACE_DECL && processing_template_decl)
10460 /* Similarly for namespace-scope variables with language linkage
10461 other than C++. */
10462 || (TREE_CODE (scope) == NAMESPACE_DECL
10463 && current_lang_name != lang_name_cplusplus)
10464 /* Similarly for static data members. */
10465 || TYPE_P (scope)
10466 /* Similarly for explicit specializations. */
10467 || (orig_declarator
10468 && TREE_CODE (orig_declarator) == TEMPLATE_ID_EXPR)))
10469 decl = build_lang_decl_loc (location, VAR_DECL, name, type);
10470 else
10471 decl = build_decl (location, VAR_DECL, name, type);
10473 if (explicit_scope && TREE_CODE (explicit_scope) == NAMESPACE_DECL)
10474 set_decl_namespace (decl, explicit_scope, 0);
10475 else
10476 DECL_CONTEXT (decl) = FROB_CONTEXT (scope);
10478 if (declspecs->storage_class == sc_extern)
10480 DECL_THIS_EXTERN (decl) = 1;
10481 DECL_EXTERNAL (decl) = !initialized;
10484 if (DECL_CLASS_SCOPE_P (decl))
10486 set_linkage_for_static_data_member (decl);
10487 /* This function is only called with out-of-class definitions. */
10488 DECL_EXTERNAL (decl) = 0;
10489 check_class_member_definition_namespace (decl);
10491 /* At top level, either `static' or no s.c. makes a definition
10492 (perhaps tentative), and absence of `static' makes it public. */
10493 else if (toplevel_bindings_p ())
10495 TREE_PUBLIC (decl) = (declspecs->storage_class != sc_static
10496 && (DECL_THIS_EXTERN (decl)
10497 || ! constp
10498 || volatilep
10499 || inlinep));
10500 TREE_STATIC (decl) = ! DECL_EXTERNAL (decl);
10502 /* Not at top level, only `static' makes a static definition. */
10503 else
10505 TREE_STATIC (decl) = declspecs->storage_class == sc_static;
10506 TREE_PUBLIC (decl) = DECL_EXTERNAL (decl);
10509 set_originating_module (decl);
10511 if (decl_spec_seq_has_spec_p (declspecs, ds_thread))
10513 if (DECL_EXTERNAL (decl) || TREE_STATIC (decl))
10515 CP_DECL_THREAD_LOCAL_P (decl) = true;
10516 if (!processing_template_decl)
10517 set_decl_tls_model (decl, decl_default_tls_model (decl));
10519 if (declspecs->gnu_thread_keyword_p)
10520 SET_DECL_GNU_TLS_P (decl);
10523 /* If the type of the decl has no linkage, make sure that we'll
10524 notice that in mark_used. */
10525 if (cxx_dialect > cxx98
10526 && decl_linkage (decl) != lk_none
10527 && DECL_LANG_SPECIFIC (decl) == NULL
10528 && !DECL_EXTERN_C_P (decl)
10529 && no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false))
10530 retrofit_lang_decl (decl);
10532 if (TREE_PUBLIC (decl))
10534 /* [basic.link]: A name with no linkage (notably, the name of a class
10535 or enumeration declared in a local scope) shall not be used to
10536 declare an entity with linkage.
10538 DR 757 relaxes this restriction for C++0x. */
10539 if (cxx_dialect < cxx11)
10540 no_linkage_error (decl);
10542 else
10543 DECL_INTERFACE_KNOWN (decl) = 1;
10545 if (DECL_NAME (decl)
10546 && MAIN_NAME_P (DECL_NAME (decl))
10547 && scope == global_namespace)
10548 error_at (DECL_SOURCE_LOCATION (decl),
10549 "cannot declare %<::main%> to be a global variable");
10551 /* Check that the variable can be safely declared as a concept.
10552 Note that this also forbids explicit specializations. */
10553 if (conceptp)
10555 if (!processing_template_decl)
10557 error_at (declspecs->locations[ds_concept],
10558 "a non-template variable cannot be %<concept%>");
10559 return NULL_TREE;
10561 else if (!at_namespace_scope_p ())
10563 error_at (declspecs->locations[ds_concept],
10564 "concept must be defined at namespace scope");
10565 return NULL_TREE;
10567 else
10568 DECL_DECLARED_CONCEPT_P (decl) = true;
10569 if (!same_type_ignoring_top_level_qualifiers_p (type, boolean_type_node))
10570 error_at (declspecs->locations[ds_type_spec],
10571 "concept must have type %<bool%>");
10572 if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
10574 error_at (location, "a variable concept cannot be constrained");
10575 TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
10578 else if (flag_concepts
10579 && current_template_depth > template_class_depth (scope))
10581 tree reqs = TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
10582 tree ci = build_constraints (reqs, NULL_TREE);
10584 set_constraints (decl, ci);
10587 // Handle explicit specializations and instantiations of variable templates.
10588 if (orig_declarator)
10589 decl = check_explicit_specialization (orig_declarator, decl,
10590 template_count, conceptp * 8);
10592 return decl != error_mark_node ? decl : NULL_TREE;
10595 /* Create and return a canonical pointer to member function type, for
10596 TYPE, which is a POINTER_TYPE to a METHOD_TYPE. */
10598 tree
10599 build_ptrmemfunc_type (tree type)
10601 tree field, fields;
10602 tree t;
10604 if (type == error_mark_node)
10605 return type;
10607 /* Make sure that we always have the unqualified pointer-to-member
10608 type first. */
10609 if (cp_cv_quals quals = cp_type_quals (type))
10611 tree unqual = build_ptrmemfunc_type (TYPE_MAIN_VARIANT (type));
10612 return cp_build_qualified_type (unqual, quals);
10615 /* If a canonical type already exists for this type, use it. We use
10616 this method instead of type_hash_canon, because it only does a
10617 simple equality check on the list of field members. */
10619 t = TYPE_PTRMEMFUNC_TYPE (type);
10620 if (t)
10621 return t;
10623 t = make_node (RECORD_TYPE);
10625 /* Let the front end know this is a pointer to member function. */
10626 TYPE_PTRMEMFUNC_FLAG (t) = 1;
10628 field = build_decl (input_location, FIELD_DECL, pfn_identifier, type);
10629 DECL_NONADDRESSABLE_P (field) = 1;
10630 fields = field;
10632 field = build_decl (input_location, FIELD_DECL, delta_identifier,
10633 delta_type_node);
10634 DECL_NONADDRESSABLE_P (field) = 1;
10635 DECL_CHAIN (field) = fields;
10636 fields = field;
10638 finish_builtin_struct (t, "__ptrmemfunc_type", fields, ptr_type_node);
10640 /* Zap out the name so that the back end will give us the debugging
10641 information for this anonymous RECORD_TYPE. */
10642 TYPE_NAME (t) = NULL_TREE;
10644 /* Cache this pointer-to-member type so that we can find it again
10645 later. */
10646 TYPE_PTRMEMFUNC_TYPE (type) = t;
10648 if (TYPE_STRUCTURAL_EQUALITY_P (type))
10649 SET_TYPE_STRUCTURAL_EQUALITY (t);
10650 else if (TYPE_CANONICAL (type) != type)
10651 TYPE_CANONICAL (t) = build_ptrmemfunc_type (TYPE_CANONICAL (type));
10653 return t;
10656 /* Create and return a pointer to data member type. */
10658 tree
10659 build_ptrmem_type (tree class_type, tree member_type)
10661 if (TREE_CODE (member_type) == METHOD_TYPE)
10663 cp_cv_quals quals = type_memfn_quals (member_type);
10664 cp_ref_qualifier rqual = type_memfn_rqual (member_type);
10665 member_type = build_memfn_type (member_type, class_type, quals, rqual);
10666 return build_ptrmemfunc_type (build_pointer_type (member_type));
10668 else
10670 gcc_assert (TREE_CODE (member_type) != FUNCTION_TYPE);
10671 return build_offset_type (class_type, member_type);
10675 /* DECL is a VAR_DECL defined in-class, whose TYPE is also given.
10676 Check to see that the definition is valid. Issue appropriate error
10677 messages. */
10679 static void
10680 check_static_variable_definition (tree decl, tree type)
10682 /* Avoid redundant diagnostics on out-of-class definitions. */
10683 if (!current_class_type || !TYPE_BEING_DEFINED (current_class_type))
10685 /* Can't check yet if we don't know the type. */
10686 else if (dependent_type_p (type))
10688 /* If DECL is declared constexpr, we'll do the appropriate checks
10689 in check_initializer. Similarly for inline static data members. */
10690 else if (DECL_P (decl)
10691 && (DECL_DECLARED_CONSTEXPR_P (decl)
10692 || DECL_VAR_DECLARED_INLINE_P (decl)))
10694 else if (cxx_dialect >= cxx11 && !INTEGRAL_OR_ENUMERATION_TYPE_P (type))
10696 if (!COMPLETE_TYPE_P (type))
10697 error_at (DECL_SOURCE_LOCATION (decl),
10698 "in-class initialization of static data member %q#D of "
10699 "incomplete type", decl);
10700 else if (literal_type_p (type))
10701 permerror (DECL_SOURCE_LOCATION (decl),
10702 "%<constexpr%> needed for in-class initialization of "
10703 "static data member %q#D of non-integral type", decl);
10704 else
10705 error_at (DECL_SOURCE_LOCATION (decl),
10706 "in-class initialization of static data member %q#D of "
10707 "non-literal type", decl);
10709 /* Motion 10 at San Diego: If a static const integral data member is
10710 initialized with an integral constant expression, the initializer
10711 may appear either in the declaration (within the class), or in
10712 the definition, but not both. If it appears in the class, the
10713 member is a member constant. The file-scope definition is always
10714 required. */
10715 else if (!ARITHMETIC_TYPE_P (type) && TREE_CODE (type) != ENUMERAL_TYPE)
10716 error_at (DECL_SOURCE_LOCATION (decl),
10717 "invalid in-class initialization of static data member "
10718 "of non-integral type %qT",
10719 type);
10720 else if (!CP_TYPE_CONST_P (type))
10721 error_at (DECL_SOURCE_LOCATION (decl),
10722 "ISO C++ forbids in-class initialization of non-const "
10723 "static member %qD",
10724 decl);
10725 else if (!INTEGRAL_OR_ENUMERATION_TYPE_P (type))
10726 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wpedantic,
10727 "ISO C++ forbids initialization of member constant "
10728 "%qD of non-integral type %qT", decl, type);
10731 /* *expr_p is part of the TYPE_SIZE of a variably-sized array. If any
10732 SAVE_EXPRs in *expr_p wrap expressions with side-effects, break those
10733 expressions out into temporary variables so that walk_tree doesn't
10734 step into them (c++/15764). */
10736 static tree
10737 stabilize_save_expr_r (tree *expr_p, int *walk_subtrees, void *data)
10739 hash_set<tree> *pset = (hash_set<tree> *)data;
10740 tree expr = *expr_p;
10741 if (TREE_CODE (expr) == SAVE_EXPR)
10743 tree op = TREE_OPERAND (expr, 0);
10744 cp_walk_tree (&op, stabilize_save_expr_r, data, pset);
10745 if (TREE_SIDE_EFFECTS (op))
10746 TREE_OPERAND (expr, 0) = get_temp_regvar (TREE_TYPE (op), op);
10747 *walk_subtrees = 0;
10749 else if (!EXPR_P (expr) || !TREE_SIDE_EFFECTS (expr))
10750 *walk_subtrees = 0;
10751 return NULL;
10754 /* Entry point for the above. */
10756 static void
10757 stabilize_vla_size (tree size)
10759 hash_set<tree> pset;
10760 /* Break out any function calls into temporary variables. */
10761 cp_walk_tree (&size, stabilize_save_expr_r, &pset, &pset);
10764 /* Reduce a SIZEOF_EXPR to its value. */
10766 tree
10767 fold_sizeof_expr (tree t)
10769 tree r;
10770 if (SIZEOF_EXPR_TYPE_P (t))
10771 r = cxx_sizeof_or_alignof_type (EXPR_LOCATION (t),
10772 TREE_TYPE (TREE_OPERAND (t, 0)),
10773 SIZEOF_EXPR, false, false);
10774 else if (TYPE_P (TREE_OPERAND (t, 0)))
10775 r = cxx_sizeof_or_alignof_type (EXPR_LOCATION (t),
10776 TREE_OPERAND (t, 0), SIZEOF_EXPR,
10777 false, false);
10778 else
10779 r = cxx_sizeof_or_alignof_expr (EXPR_LOCATION (t),
10780 TREE_OPERAND (t, 0), SIZEOF_EXPR,
10781 false, false);
10782 if (r == error_mark_node)
10783 r = size_one_node;
10784 return r;
10787 /* Given the SIZE (i.e., number of elements) in an array, compute
10788 an appropriate index type for the array. If non-NULL, NAME is
10789 the name of the entity being declared. */
10791 static tree
10792 compute_array_index_type_loc (location_t name_loc, tree name, tree size,
10793 tsubst_flags_t complain)
10795 if (error_operand_p (size))
10796 return error_mark_node;
10798 /* The type of the index being computed. */
10799 tree itype;
10801 /* The original numeric size as seen in the source code before
10802 conversion to size_t. */
10803 tree origsize = size;
10805 location_t loc = cp_expr_loc_or_loc (size, name ? name_loc : input_location);
10807 if (!type_dependent_expression_p (size))
10809 origsize = size = mark_rvalue_use (size);
10811 if (cxx_dialect < cxx11 && TREE_CODE (size) == NOP_EXPR
10812 && TREE_SIDE_EFFECTS (size))
10813 /* In C++98, we mark a non-constant array bound with a magic
10814 NOP_EXPR with TREE_SIDE_EFFECTS; don't fold in that case. */;
10815 else
10817 size = build_converted_constant_expr (size_type_node, size, complain);
10818 /* Pedantically a constant expression is required here and so
10819 __builtin_is_constant_evaluated () should fold to true if it
10820 is successfully folded into a constant. */
10821 size = fold_non_dependent_expr (size, complain,
10822 /*manifestly_const_eval=*/true);
10824 if (!TREE_CONSTANT (size))
10825 size = origsize;
10828 if (error_operand_p (size))
10829 return error_mark_node;
10831 /* The array bound must be an integer type. */
10832 tree type = TREE_TYPE (size);
10833 if (!INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
10835 if (!(complain & tf_error))
10836 return error_mark_node;
10837 if (name)
10838 error_at (loc, "size of array %qD has non-integral type %qT",
10839 name, type);
10840 else
10841 error_at (loc, "size of array has non-integral type %qT", type);
10842 size = integer_one_node;
10846 /* A type is dependent if it is...an array type constructed from any
10847 dependent type or whose size is specified by a constant expression
10848 that is value-dependent. */
10849 /* We can only call value_dependent_expression_p on integral constant
10850 expressions. */
10851 if (processing_template_decl
10852 && potential_constant_expression (size)
10853 && value_dependent_expression_p (size))
10855 /* Just build the index type and mark that it requires
10856 structural equality checks. */
10857 in_template:
10858 itype = build_index_type (build_min (MINUS_EXPR, sizetype,
10859 size, size_one_node));
10860 TYPE_DEPENDENT_P (itype) = 1;
10861 TYPE_DEPENDENT_P_VALID (itype) = 1;
10862 SET_TYPE_STRUCTURAL_EQUALITY (itype);
10863 return itype;
10866 if (TREE_CODE (size) != INTEGER_CST)
10868 tree folded = cp_fully_fold (size);
10869 if (TREE_CODE (folded) == INTEGER_CST)
10871 if (name)
10872 pedwarn (loc, OPT_Wpedantic, "size of array %qD is not an "
10873 "integral constant-expression", name);
10874 else
10875 pedwarn (loc, OPT_Wpedantic,
10876 "size of array is not an integral constant-expression");
10878 if (TREE_CONSTANT (size) && !TREE_CONSTANT (folded))
10879 /* We might have lost the TREE_CONSTANT flag e.g. when we are
10880 folding a conversion from a pointer to integral type. In that
10881 case issue an error below and don't treat this as a VLA. */;
10882 else
10883 /* Use the folded result for VLAs, too; it will have resolved
10884 SIZEOF_EXPR. */
10885 size = folded;
10888 /* Normally, the array-bound will be a constant. */
10889 if (TREE_CODE (size) == INTEGER_CST)
10891 /* The size to use in diagnostics that reflects the constant
10892 size used in the source, rather than SIZE massaged above. */
10893 tree diagsize = size;
10895 /* If the original size before conversion to size_t was signed
10896 and negative, convert it to ssizetype to restore the sign. */
10897 if (!TYPE_UNSIGNED (TREE_TYPE (origsize))
10898 && TREE_CODE (size) == INTEGER_CST
10899 && tree_int_cst_sign_bit (size))
10901 diagsize = fold_convert (ssizetype, size);
10903 /* Clear the overflow bit that may have been set as a result
10904 of the conversion from the sizetype of the new size to
10905 ssizetype. */
10906 TREE_OVERFLOW (diagsize) = false;
10909 /* Verify that the array has a positive number of elements
10910 and issue the appropriate diagnostic if it doesn't. */
10911 if (!valid_array_size_p (loc, diagsize, name, (complain & tf_error)))
10913 if (!(complain & tf_error))
10914 return error_mark_node;
10915 size = integer_one_node;
10917 /* As an extension we allow zero-sized arrays. */
10918 else if (integer_zerop (size))
10920 if (!(complain & tf_error))
10921 /* We must fail if performing argument deduction (as
10922 indicated by the state of complain), so that
10923 another substitution can be found. */
10924 return error_mark_node;
10925 else if (name)
10926 pedwarn (loc, OPT_Wpedantic,
10927 "ISO C++ forbids zero-size array %qD", name);
10928 else
10929 pedwarn (loc, OPT_Wpedantic,
10930 "ISO C++ forbids zero-size array");
10933 else if (TREE_CONSTANT (size)
10934 /* We don't allow VLAs at non-function scopes, or during
10935 tentative template substitution. */
10936 || !at_function_scope_p ()
10937 || !(complain & tf_error))
10939 if (!(complain & tf_error))
10940 return error_mark_node;
10941 /* `(int) &fn' is not a valid array bound. */
10942 if (name)
10943 error_at (loc,
10944 "size of array %qD is not an integral constant-expression",
10945 name);
10946 else
10947 error_at (loc, "size of array is not an integral constant-expression");
10948 size = integer_one_node;
10950 else if (pedantic && warn_vla != 0)
10952 if (name)
10953 pedwarn (name_loc, OPT_Wvla,
10954 "ISO C++ forbids variable length array %qD", name);
10955 else
10956 pedwarn (input_location, OPT_Wvla,
10957 "ISO C++ forbids variable length array");
10959 else if (warn_vla > 0)
10961 if (name)
10962 warning_at (name_loc, OPT_Wvla,
10963 "variable length array %qD is used", name);
10964 else
10965 warning (OPT_Wvla,
10966 "variable length array is used");
10969 if (processing_template_decl && !TREE_CONSTANT (size))
10970 goto in_template;
10971 else
10973 if (!TREE_CONSTANT (size))
10975 /* A variable sized array. Arrange for the SAVE_EXPR on the inside
10976 of the MINUS_EXPR, which allows the -1 to get folded with the +1
10977 that happens when building TYPE_SIZE. */
10978 size = variable_size (size);
10979 stabilize_vla_size (size);
10982 /* Compute the index of the largest element in the array. It is
10983 one less than the number of elements in the array. We save
10984 and restore PROCESSING_TEMPLATE_DECL so that computations in
10985 cp_build_binary_op will be appropriately folded. */
10987 processing_template_decl_sentinel s;
10988 itype = cp_build_binary_op (input_location,
10989 MINUS_EXPR,
10990 cp_convert (ssizetype, size, complain),
10991 cp_convert (ssizetype, integer_one_node,
10992 complain),
10993 complain);
10994 itype = maybe_constant_value (itype, NULL_TREE, true);
10997 if (!TREE_CONSTANT (itype))
10999 if (sanitize_flags_p (SANITIZE_VLA)
11000 && current_function_decl != NULL_TREE)
11002 /* We have to add 1 -- in the ubsan routine we generate
11003 LE_EXPR rather than LT_EXPR. */
11004 tree t = fold_build2 (PLUS_EXPR, TREE_TYPE (itype), itype,
11005 build_one_cst (TREE_TYPE (itype)));
11006 t = ubsan_instrument_vla (input_location, t);
11007 finish_expr_stmt (t);
11010 /* Make sure that there was no overflow when creating to a signed
11011 index type. (For example, on a 32-bit machine, an array with
11012 size 2^32 - 1 is too big.) */
11013 else if (TREE_CODE (itype) == INTEGER_CST
11014 && TREE_OVERFLOW (itype))
11016 if (!(complain & tf_error))
11017 return error_mark_node;
11018 error ("overflow in array dimension");
11019 TREE_OVERFLOW (itype) = 0;
11023 /* Create and return the appropriate index type. */
11024 itype = build_index_type (itype);
11026 /* If the index type were dependent, we would have returned early, so
11027 remember that it isn't. */
11028 TYPE_DEPENDENT_P (itype) = 0;
11029 TYPE_DEPENDENT_P_VALID (itype) = 1;
11030 return itype;
11033 tree
11034 compute_array_index_type (tree name, tree size, tsubst_flags_t complain)
11036 return compute_array_index_type_loc (input_location, name, size, complain);
11039 /* Returns the scope (if any) in which the entity declared by
11040 DECLARATOR will be located. If the entity was declared with an
11041 unqualified name, NULL_TREE is returned. */
11043 tree
11044 get_scope_of_declarator (const cp_declarator *declarator)
11046 while (declarator && declarator->kind != cdk_id)
11047 declarator = declarator->declarator;
11049 /* If the declarator-id is a SCOPE_REF, the scope in which the
11050 declaration occurs is the first operand. */
11051 if (declarator
11052 && declarator->u.id.qualifying_scope)
11053 return declarator->u.id.qualifying_scope;
11055 /* Otherwise, the declarator is not a qualified name; the entity will
11056 be declared in the current scope. */
11057 return NULL_TREE;
11060 /* Returns an ARRAY_TYPE for an array with SIZE elements of the
11061 indicated TYPE. If non-NULL, NAME is the NAME of the declaration
11062 with this type. */
11064 static tree
11065 create_array_type_for_decl (tree name, tree type, tree size, location_t loc)
11067 tree itype = NULL_TREE;
11069 /* If things have already gone awry, bail now. */
11070 if (type == error_mark_node || size == error_mark_node)
11071 return error_mark_node;
11073 /* If there are some types which cannot be array elements,
11074 issue an error-message and return. */
11075 switch (TREE_CODE (type))
11077 case VOID_TYPE:
11078 if (name)
11079 error_at (loc, "declaration of %qD as array of void", name);
11080 else
11081 error ("creating array of void");
11082 return error_mark_node;
11084 case FUNCTION_TYPE:
11085 if (name)
11086 error_at (loc, "declaration of %qD as array of functions", name);
11087 else
11088 error ("creating array of functions");
11089 return error_mark_node;
11091 case REFERENCE_TYPE:
11092 if (name)
11093 error_at (loc, "declaration of %qD as array of references", name);
11094 else
11095 error ("creating array of references");
11096 return error_mark_node;
11098 case METHOD_TYPE:
11099 if (name)
11100 error_at (loc, "declaration of %qD as array of function members",
11101 name);
11102 else
11103 error ("creating array of function members");
11104 return error_mark_node;
11106 default:
11107 break;
11110 if (!verify_type_context (name ? loc : input_location,
11111 TCTX_ARRAY_ELEMENT, type))
11112 return error_mark_node;
11114 /* [dcl.array]
11116 The constant expressions that specify the bounds of the arrays
11117 can be omitted only for the first member of the sequence. */
11118 if (TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type))
11120 if (name)
11121 error_at (loc, "declaration of %qD as multidimensional array must "
11122 "have bounds for all dimensions except the first",
11123 name);
11124 else
11125 error ("multidimensional array must have bounds for all "
11126 "dimensions except the first");
11128 return error_mark_node;
11131 /* Figure out the index type for the array. */
11132 if (size)
11133 itype = compute_array_index_type_loc (loc, name, size,
11134 tf_warning_or_error);
11136 return build_cplus_array_type (type, itype);
11139 /* Returns the smallest location that is not UNKNOWN_LOCATION. */
11141 static location_t
11142 min_location (location_t loca, location_t locb)
11144 if (loca == UNKNOWN_LOCATION
11145 || (locb != UNKNOWN_LOCATION
11146 && linemap_location_before_p (line_table, locb, loca)))
11147 return locb;
11148 return loca;
11151 /* Returns the smallest location != UNKNOWN_LOCATION among the
11152 three stored in LOCATIONS[ds_const], LOCATIONS[ds_volatile],
11153 and LOCATIONS[ds_restrict]. */
11155 static location_t
11156 smallest_type_quals_location (int type_quals, const location_t* locations)
11158 location_t loc = UNKNOWN_LOCATION;
11160 if (type_quals & TYPE_QUAL_CONST)
11161 loc = locations[ds_const];
11163 if (type_quals & TYPE_QUAL_VOLATILE)
11164 loc = min_location (loc, locations[ds_volatile]);
11166 if (type_quals & TYPE_QUAL_RESTRICT)
11167 loc = min_location (loc, locations[ds_restrict]);
11169 return loc;
11172 /* Returns the smallest among the latter and locations[ds_type_spec]. */
11174 static location_t
11175 smallest_type_location (int type_quals, const location_t* locations)
11177 location_t loc = smallest_type_quals_location (type_quals, locations);
11178 return min_location (loc, locations[ds_type_spec]);
11181 static location_t
11182 smallest_type_location (const cp_decl_specifier_seq *declspecs)
11184 int type_quals = get_type_quals (declspecs);
11185 return smallest_type_location (type_quals, declspecs->locations);
11188 /* Check that it's OK to declare a function with the indicated TYPE
11189 and TYPE_QUALS. SFK indicates the kind of special function (if any)
11190 that this function is. OPTYPE is the type given in a conversion
11191 operator declaration, or the class type for a constructor/destructor.
11192 Returns the actual return type of the function; that may be different
11193 than TYPE if an error occurs, or for certain special functions. */
11195 static tree
11196 check_special_function_return_type (special_function_kind sfk,
11197 tree type,
11198 tree optype,
11199 int type_quals,
11200 const location_t* locations)
11202 switch (sfk)
11204 case sfk_constructor:
11205 if (type)
11206 error_at (smallest_type_location (type_quals, locations),
11207 "return type specification for constructor invalid");
11208 else if (type_quals != TYPE_UNQUALIFIED)
11209 error_at (smallest_type_quals_location (type_quals, locations),
11210 "qualifiers are not allowed on constructor declaration");
11212 if (targetm.cxx.cdtor_returns_this ())
11213 type = build_pointer_type (optype);
11214 else
11215 type = void_type_node;
11216 break;
11218 case sfk_destructor:
11219 if (type)
11220 error_at (smallest_type_location (type_quals, locations),
11221 "return type specification for destructor invalid");
11222 else if (type_quals != TYPE_UNQUALIFIED)
11223 error_at (smallest_type_quals_location (type_quals, locations),
11224 "qualifiers are not allowed on destructor declaration");
11226 /* We can't use the proper return type here because we run into
11227 problems with ambiguous bases and covariant returns. */
11228 if (targetm.cxx.cdtor_returns_this ())
11229 type = build_pointer_type (void_type_node);
11230 else
11231 type = void_type_node;
11232 break;
11234 case sfk_conversion:
11235 if (type)
11236 error_at (smallest_type_location (type_quals, locations),
11237 "return type specified for %<operator %T%>", optype);
11238 else if (type_quals != TYPE_UNQUALIFIED)
11239 error_at (smallest_type_quals_location (type_quals, locations),
11240 "qualifiers are not allowed on declaration of "
11241 "%<operator %T%>", optype);
11243 type = optype;
11244 break;
11246 case sfk_deduction_guide:
11247 if (type)
11248 error_at (smallest_type_location (type_quals, locations),
11249 "return type specified for deduction guide");
11250 else if (type_quals != TYPE_UNQUALIFIED)
11251 error_at (smallest_type_quals_location (type_quals, locations),
11252 "qualifiers are not allowed on declaration of "
11253 "deduction guide");
11254 if (TREE_CODE (optype) == TEMPLATE_TEMPLATE_PARM)
11256 error ("template template parameter %qT in declaration of "
11257 "deduction guide", optype);
11258 type = error_mark_node;
11260 else
11261 type = make_template_placeholder (CLASSTYPE_TI_TEMPLATE (optype));
11262 for (int i = 0; i < ds_last; ++i)
11263 if (i != ds_explicit && locations[i])
11264 error_at (locations[i],
11265 "%<decl-specifier%> in declaration of deduction guide");
11266 break;
11268 default:
11269 gcc_unreachable ();
11272 return type;
11275 /* A variable or data member (whose unqualified name is IDENTIFIER)
11276 has been declared with the indicated TYPE. If the TYPE is not
11277 acceptable, issue an error message and return a type to use for
11278 error-recovery purposes. */
11280 tree
11281 check_var_type (tree identifier, tree type, location_t loc)
11283 if (VOID_TYPE_P (type))
11285 if (!identifier)
11286 error_at (loc, "unnamed variable or field declared void");
11287 else if (identifier_p (identifier))
11289 gcc_assert (!IDENTIFIER_ANY_OP_P (identifier));
11290 error_at (loc, "variable or field %qE declared void",
11291 identifier);
11293 else
11294 error_at (loc, "variable or field declared void");
11295 type = error_mark_node;
11298 return type;
11301 /* Handle declaring DECL as an inline variable. */
11303 static void
11304 mark_inline_variable (tree decl, location_t loc)
11306 bool inlinep = true;
11307 if (! toplevel_bindings_p ())
11309 error_at (loc, "%<inline%> specifier invalid for variable "
11310 "%qD declared at block scope", decl);
11311 inlinep = false;
11313 else if (cxx_dialect < cxx17)
11314 pedwarn (loc, OPT_Wc__17_extensions, "inline variables are only available "
11315 "with %<-std=c++17%> or %<-std=gnu++17%>");
11316 if (inlinep)
11318 retrofit_lang_decl (decl);
11319 SET_DECL_VAR_DECLARED_INLINE_P (decl);
11324 /* Assign a typedef-given name to a class or enumeration type declared
11325 as anonymous at first. This was split out of grokdeclarator
11326 because it is also used in libcc1. */
11328 void
11329 name_unnamed_type (tree type, tree decl)
11331 gcc_assert (TYPE_UNNAMED_P (type));
11333 /* Replace the anonymous decl with the real decl. Be careful not to
11334 rename other typedefs (such as the self-reference) of type. */
11335 tree orig = TYPE_NAME (type);
11336 for (tree t = TYPE_MAIN_VARIANT (type); t; t = TYPE_NEXT_VARIANT (t))
11337 if (TYPE_NAME (t) == orig)
11338 TYPE_NAME (t) = decl;
11340 /* If this is a typedef within a template class, the nested
11341 type is a (non-primary) template. The name for the
11342 template needs updating as well. */
11343 if (TYPE_LANG_SPECIFIC (type) && CLASSTYPE_TEMPLATE_INFO (type))
11344 DECL_NAME (CLASSTYPE_TI_TEMPLATE (type)) = DECL_NAME (decl);
11346 /* Adjust linkage now that we aren't unnamed anymore. */
11347 reset_type_linkage (type);
11349 /* FIXME remangle member functions; member functions of a
11350 type with external linkage have external linkage. */
11352 /* Check that our job is done, and that it would fail if we
11353 attempted to do it again. */
11354 gcc_assert (!TYPE_UNNAMED_P (type));
11357 /* Check that decltype(auto) was well-formed: only plain decltype(auto)
11358 is allowed. TYPE might contain a decltype(auto). Returns true if
11359 there was a problem, false otherwise. */
11361 static bool
11362 check_decltype_auto (location_t loc, tree type)
11364 if (tree a = type_uses_auto (type))
11366 if (AUTO_IS_DECLTYPE (a))
11368 if (a != type)
11370 error_at (loc, "%qT as type rather than plain "
11371 "%<decltype(auto)%>", type);
11372 return true;
11374 else if (TYPE_QUALS (type) != TYPE_UNQUALIFIED)
11376 error_at (loc, "%<decltype(auto)%> cannot be cv-qualified");
11377 return true;
11381 return false;
11384 /* Given declspecs and a declarator (abstract or otherwise), determine
11385 the name and type of the object declared and construct a DECL node
11386 for it.
11388 DECLSPECS points to the representation of declaration-specifier
11389 sequence that precedes declarator.
11391 DECL_CONTEXT says which syntactic context this declaration is in:
11392 NORMAL for most contexts. Make a VAR_DECL or FUNCTION_DECL or TYPE_DECL.
11393 FUNCDEF for a function definition. Like NORMAL but a few different
11394 error messages in each case. Return value may be zero meaning
11395 this definition is too screwy to try to parse.
11396 MEMFUNCDEF for a function definition. Like FUNCDEF but prepares to
11397 handle member functions (which have FIELD context).
11398 Return value may be zero meaning this definition is too screwy to
11399 try to parse.
11400 PARM for a parameter declaration (either within a function prototype
11401 or before a function body). Make a PARM_DECL, or return void_type_node.
11402 TPARM for a template parameter declaration.
11403 CATCHPARM for a parameter declaration before a catch clause.
11404 TYPENAME if for a typename (in a cast or sizeof).
11405 Don't make a DECL node; just return the ..._TYPE node.
11406 FIELD for a struct or union field; make a FIELD_DECL.
11407 BITFIELD for a field with specified width.
11409 INITIALIZED is as for start_decl.
11411 ATTRLIST is a pointer to the list of attributes, which may be NULL
11412 if there are none; *ATTRLIST may be modified if attributes from inside
11413 the declarator should be applied to the declaration.
11415 When this function is called, scoping variables (such as
11416 CURRENT_CLASS_TYPE) should reflect the scope in which the
11417 declaration occurs, not the scope in which the new declaration will
11418 be placed. For example, on:
11420 void S::f() { ... }
11422 when grokdeclarator is called for `S::f', the CURRENT_CLASS_TYPE
11423 should not be `S'.
11425 Returns a DECL (if a declarator is present), a TYPE (if there is no
11426 declarator, in cases like "struct S;"), or the ERROR_MARK_NODE if an
11427 error occurs. */
11429 tree
11430 grokdeclarator (const cp_declarator *declarator,
11431 cp_decl_specifier_seq *declspecs,
11432 enum decl_context decl_context,
11433 int initialized,
11434 tree* attrlist)
11436 tree type = NULL_TREE;
11437 int longlong = 0;
11438 int explicit_intN = 0;
11439 int int_n_alt = 0;
11440 int virtualp, explicitp, friendp, inlinep, staticp;
11441 int explicit_int = 0;
11442 int explicit_char = 0;
11443 int defaulted_int = 0;
11445 tree typedef_decl = NULL_TREE;
11446 const char *name = NULL;
11447 tree typedef_type = NULL_TREE;
11448 /* True if this declarator is a function definition. */
11449 bool funcdef_flag = false;
11450 cp_declarator_kind innermost_code = cdk_error;
11451 int bitfield = 0;
11452 #if 0
11453 /* See the code below that used this. */
11454 tree decl_attr = NULL_TREE;
11455 #endif
11457 /* Keep track of what sort of function is being processed
11458 so that we can warn about default return values, or explicit
11459 return values which do not match prescribed defaults. */
11460 special_function_kind sfk = sfk_none;
11462 tree dname = NULL_TREE;
11463 tree ctor_return_type = NULL_TREE;
11464 enum overload_flags flags = NO_SPECIAL;
11465 /* cv-qualifiers that apply to the declarator, for a declaration of
11466 a member function. */
11467 cp_cv_quals memfn_quals = TYPE_UNQUALIFIED;
11468 /* virt-specifiers that apply to the declarator, for a declaration of
11469 a member function. */
11470 cp_virt_specifiers virt_specifiers = VIRT_SPEC_UNSPECIFIED;
11471 /* ref-qualifier that applies to the declarator, for a declaration of
11472 a member function. */
11473 cp_ref_qualifier rqual = REF_QUAL_NONE;
11474 /* cv-qualifiers that apply to the type specified by the DECLSPECS. */
11475 int type_quals = get_type_quals (declspecs);
11476 tree raises = NULL_TREE;
11477 int template_count = 0;
11478 tree returned_attrs = NULL_TREE;
11479 tree parms = NULL_TREE;
11480 const cp_declarator *id_declarator;
11481 /* The unqualified name of the declarator; either an
11482 IDENTIFIER_NODE, BIT_NOT_EXPR, or TEMPLATE_ID_EXPR. */
11483 tree unqualified_id;
11484 /* The class type, if any, in which this entity is located,
11485 or NULL_TREE if none. Note that this value may be different from
11486 the current class type; for example if an attempt is made to declare
11487 "A::f" inside "B", this value will be "A". */
11488 tree ctype = current_class_type;
11489 /* The NAMESPACE_DECL for the namespace in which this entity is
11490 located. If an unqualified name is used to declare the entity,
11491 this value will be NULL_TREE, even if the entity is located at
11492 namespace scope. */
11493 tree in_namespace = NULL_TREE;
11494 cp_storage_class storage_class;
11495 bool unsigned_p, signed_p, short_p, long_p, thread_p;
11496 bool type_was_error_mark_node = false;
11497 bool parameter_pack_p = declarator ? declarator->parameter_pack_p : false;
11498 bool template_type_arg = false;
11499 bool template_parm_flag = false;
11500 bool typedef_p = decl_spec_seq_has_spec_p (declspecs, ds_typedef);
11501 bool constexpr_p = decl_spec_seq_has_spec_p (declspecs, ds_constexpr);
11502 bool constinit_p = decl_spec_seq_has_spec_p (declspecs, ds_constinit);
11503 bool consteval_p = decl_spec_seq_has_spec_p (declspecs, ds_consteval);
11504 bool late_return_type_p = false;
11505 bool array_parameter_p = false;
11506 tree reqs = NULL_TREE;
11508 signed_p = decl_spec_seq_has_spec_p (declspecs, ds_signed);
11509 unsigned_p = decl_spec_seq_has_spec_p (declspecs, ds_unsigned);
11510 short_p = decl_spec_seq_has_spec_p (declspecs, ds_short);
11511 long_p = decl_spec_seq_has_spec_p (declspecs, ds_long);
11512 longlong = decl_spec_seq_has_spec_p (declspecs, ds_long_long);
11513 explicit_intN = declspecs->explicit_intN_p;
11514 int_n_alt = declspecs->int_n_alt;
11515 thread_p = decl_spec_seq_has_spec_p (declspecs, ds_thread);
11517 // Was concept_p specified? Note that ds_concept
11518 // implies ds_constexpr!
11519 bool concept_p = decl_spec_seq_has_spec_p (declspecs, ds_concept);
11520 if (concept_p)
11521 constexpr_p = true;
11523 if (decl_context == FUNCDEF)
11524 funcdef_flag = true, decl_context = NORMAL;
11525 else if (decl_context == MEMFUNCDEF)
11526 funcdef_flag = true, decl_context = FIELD;
11527 else if (decl_context == BITFIELD)
11528 bitfield = 1, decl_context = FIELD;
11529 else if (decl_context == TEMPLATE_TYPE_ARG)
11530 template_type_arg = true, decl_context = TYPENAME;
11531 else if (decl_context == TPARM)
11532 template_parm_flag = true, decl_context = PARM;
11534 if (initialized == SD_DEFAULTED || initialized == SD_DELETED)
11535 funcdef_flag = true;
11537 location_t typespec_loc = loc_or_input_loc (smallest_type_location
11538 (type_quals,
11539 declspecs->locations));
11540 location_t id_loc;
11541 location_t init_loc;
11542 if (declarator)
11544 id_loc = loc_or_input_loc (declarator->id_loc);
11545 init_loc = loc_or_input_loc (declarator->init_loc);
11547 else
11548 init_loc = id_loc = input_location;
11550 /* Look inside a declarator for the name being declared
11551 and get it as a string, for an error message. */
11552 for (id_declarator = declarator;
11553 id_declarator;
11554 id_declarator = id_declarator->declarator)
11556 if (id_declarator->kind != cdk_id)
11557 innermost_code = id_declarator->kind;
11559 switch (id_declarator->kind)
11561 case cdk_function:
11562 if (id_declarator->declarator
11563 && id_declarator->declarator->kind == cdk_id)
11565 sfk = id_declarator->declarator->u.id.sfk;
11566 if (sfk == sfk_destructor)
11567 flags = DTOR_FLAG;
11569 break;
11571 case cdk_id:
11573 tree qualifying_scope = id_declarator->u.id.qualifying_scope;
11574 tree decl = id_declarator->u.id.unqualified_name;
11575 if (!decl)
11576 break;
11577 if (qualifying_scope)
11579 if (check_for_bare_parameter_packs (qualifying_scope,
11580 id_declarator->id_loc))
11581 return error_mark_node;
11582 if (at_function_scope_p ())
11584 /* [dcl.meaning]
11586 A declarator-id shall not be qualified except
11587 for ...
11589 None of the cases are permitted in block
11590 scope. */
11591 if (qualifying_scope == global_namespace)
11592 error ("invalid use of qualified-name %<::%D%>",
11593 decl);
11594 else if (TYPE_P (qualifying_scope))
11595 error ("invalid use of qualified-name %<%T::%D%>",
11596 qualifying_scope, decl);
11597 else
11598 error ("invalid use of qualified-name %<%D::%D%>",
11599 qualifying_scope, decl);
11600 return error_mark_node;
11602 else if (TYPE_P (qualifying_scope))
11604 ctype = qualifying_scope;
11605 if (!MAYBE_CLASS_TYPE_P (ctype))
11607 error_at (id_declarator->id_loc,
11608 "%q#T is not a class or namespace", ctype);
11609 ctype = NULL_TREE;
11611 else if (innermost_code != cdk_function
11612 && current_class_type
11613 && !uniquely_derived_from_p (ctype,
11614 current_class_type))
11616 error_at (id_declarator->id_loc,
11617 "invalid use of qualified-name %<%T::%D%>",
11618 qualifying_scope, decl);
11619 return error_mark_node;
11622 else if (TREE_CODE (qualifying_scope) == NAMESPACE_DECL)
11623 in_namespace = qualifying_scope;
11625 switch (TREE_CODE (decl))
11627 case BIT_NOT_EXPR:
11629 if (innermost_code != cdk_function)
11631 error_at (EXPR_LOCATION (decl),
11632 "declaration of %qE as non-function", decl);
11633 return error_mark_node;
11635 else if (!qualifying_scope
11636 && !(current_class_type && at_class_scope_p ()))
11638 error_at (EXPR_LOCATION (decl),
11639 "declaration of %qE as non-member", decl);
11640 return error_mark_node;
11643 tree type = TREE_OPERAND (decl, 0);
11644 if (TYPE_P (type))
11645 type = constructor_name (type);
11646 name = identifier_to_locale (IDENTIFIER_POINTER (type));
11647 dname = decl;
11649 break;
11651 case TEMPLATE_ID_EXPR:
11653 tree fns = TREE_OPERAND (decl, 0);
11655 dname = fns;
11656 if (!identifier_p (dname))
11657 dname = OVL_NAME (dname);
11659 /* Fall through. */
11661 case IDENTIFIER_NODE:
11662 if (identifier_p (decl))
11663 dname = decl;
11665 if (IDENTIFIER_KEYWORD_P (dname))
11667 error ("declarator-id missing; using reserved word %qD",
11668 dname);
11669 name = identifier_to_locale (IDENTIFIER_POINTER (dname));
11671 else if (!IDENTIFIER_CONV_OP_P (dname))
11672 name = identifier_to_locale (IDENTIFIER_POINTER (dname));
11673 else
11675 gcc_assert (flags == NO_SPECIAL);
11676 flags = TYPENAME_FLAG;
11677 sfk = sfk_conversion;
11678 tree glob = get_global_binding (dname);
11679 if (glob && TREE_CODE (glob) == TYPE_DECL)
11680 name = identifier_to_locale (IDENTIFIER_POINTER (dname));
11681 else
11682 name = "<invalid operator>";
11684 break;
11686 default:
11687 gcc_unreachable ();
11689 break;
11692 case cdk_array:
11693 case cdk_pointer:
11694 case cdk_reference:
11695 case cdk_ptrmem:
11696 break;
11698 case cdk_decomp:
11699 name = "structured binding";
11700 break;
11702 case cdk_error:
11703 return error_mark_node;
11705 default:
11706 gcc_unreachable ();
11708 if (id_declarator->kind == cdk_id)
11709 break;
11712 /* [dcl.fct.edf]
11714 The declarator in a function-definition shall have the form
11715 D1 ( parameter-declaration-clause) ... */
11716 if (funcdef_flag && innermost_code != cdk_function)
11718 error_at (id_loc, "function definition does not declare parameters");
11719 return error_mark_node;
11722 if (flags == TYPENAME_FLAG
11723 && innermost_code != cdk_function
11724 && ! (ctype && !declspecs->any_specifiers_p))
11726 error_at (id_loc, "declaration of %qD as non-function", dname);
11727 return error_mark_node;
11730 if (dname && identifier_p (dname))
11732 if (UDLIT_OPER_P (dname)
11733 && innermost_code != cdk_function)
11735 error_at (id_loc, "declaration of %qD as non-function", dname);
11736 return error_mark_node;
11739 if (IDENTIFIER_ANY_OP_P (dname))
11741 if (typedef_p)
11743 error_at (id_loc, "declaration of %qD as %<typedef%>", dname);
11744 return error_mark_node;
11746 else if (decl_context == PARM || decl_context == CATCHPARM)
11748 error_at (id_loc, "declaration of %qD as parameter", dname);
11749 return error_mark_node;
11754 /* Anything declared one level down from the top level
11755 must be one of the parameters of a function
11756 (because the body is at least two levels down). */
11758 /* This heuristic cannot be applied to C++ nodes! Fixed, however,
11759 by not allowing C++ class definitions to specify their parameters
11760 with xdecls (must be spec.d in the parmlist).
11762 Since we now wait to push a class scope until we are sure that
11763 we are in a legitimate method context, we must set oldcname
11764 explicitly (since current_class_name is not yet alive).
11766 We also want to avoid calling this a PARM if it is in a namespace. */
11768 if (decl_context == NORMAL && !toplevel_bindings_p ())
11770 cp_binding_level *b = current_binding_level;
11771 current_binding_level = b->level_chain;
11772 if (current_binding_level != 0 && toplevel_bindings_p ())
11773 decl_context = PARM;
11774 current_binding_level = b;
11777 if (name == NULL)
11778 name = decl_context == PARM ? "parameter" : "type name";
11780 if (consteval_p && constexpr_p)
11782 error_at (declspecs->locations[ds_consteval],
11783 "both %qs and %qs specified", "constexpr", "consteval");
11784 return error_mark_node;
11787 if (concept_p && typedef_p)
11789 error_at (declspecs->locations[ds_concept],
11790 "%qs cannot appear in a typedef declaration", "concept");
11791 return error_mark_node;
11794 if (constexpr_p && typedef_p)
11796 error_at (declspecs->locations[ds_constexpr],
11797 "%qs cannot appear in a typedef declaration", "constexpr");
11798 return error_mark_node;
11801 if (consteval_p && typedef_p)
11803 error_at (declspecs->locations[ds_consteval],
11804 "%qs cannot appear in a typedef declaration", "consteval");
11805 return error_mark_node;
11808 if (constinit_p && typedef_p)
11810 error_at (declspecs->locations[ds_constinit],
11811 "%qs cannot appear in a typedef declaration", "constinit");
11812 return error_mark_node;
11815 /* [dcl.spec]/2 "At most one of the constexpr, consteval, and constinit
11816 keywords shall appear in a decl-specifier-seq." */
11817 if (constinit_p && constexpr_p)
11819 gcc_rich_location richloc (declspecs->locations[ds_constinit]);
11820 richloc.add_range (declspecs->locations[ds_constexpr]);
11821 error_at (&richloc,
11822 "can use at most one of the %<constinit%> and %<constexpr%> "
11823 "specifiers");
11824 return error_mark_node;
11827 /* If there were multiple types specified in the decl-specifier-seq,
11828 issue an error message. */
11829 if (declspecs->multiple_types_p)
11831 error_at (typespec_loc,
11832 "two or more data types in declaration of %qs", name);
11833 return error_mark_node;
11836 if (declspecs->conflicting_specifiers_p)
11838 error_at (min_location (declspecs->locations[ds_typedef],
11839 declspecs->locations[ds_storage_class]),
11840 "conflicting specifiers in declaration of %qs", name);
11841 return error_mark_node;
11844 /* Extract the basic type from the decl-specifier-seq. */
11845 type = declspecs->type;
11846 if (type == error_mark_node)
11848 type = NULL_TREE;
11849 type_was_error_mark_node = true;
11852 /* Ignore erroneous attributes. */
11853 if (attrlist && *attrlist == error_mark_node)
11854 *attrlist = NULL_TREE;
11856 /* An object declared as __attribute__((unavailable)) suppresses
11857 any reports of being declared with unavailable or deprecated
11858 items. An object declared as __attribute__((deprecated))
11859 suppresses warnings of uses of other deprecated items. */
11860 auto ds = make_temp_override (deprecated_state);
11861 if (attrlist && lookup_attribute ("unavailable", *attrlist))
11862 deprecated_state = UNAVAILABLE_DEPRECATED_SUPPRESS;
11863 else if (attrlist && lookup_attribute ("deprecated", *attrlist))
11864 deprecated_state = DEPRECATED_SUPPRESS;
11866 cp_handle_deprecated_or_unavailable (type);
11867 if (type && TREE_CODE (type) == TYPE_DECL)
11869 cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (type));
11870 typedef_decl = type;
11871 type = TREE_TYPE (typedef_decl);
11872 if (DECL_ARTIFICIAL (typedef_decl))
11873 cp_handle_deprecated_or_unavailable (type);
11875 /* No type at all: default to `int', and set DEFAULTED_INT
11876 because it was not a user-defined typedef. */
11877 if (type == NULL_TREE)
11879 if (signed_p || unsigned_p || long_p || short_p)
11881 /* These imply 'int'. */
11882 type = integer_type_node;
11883 defaulted_int = 1;
11885 /* If we just have "complex", it is equivalent to "complex double". */
11886 else if (!longlong && !explicit_intN
11887 && decl_spec_seq_has_spec_p (declspecs, ds_complex))
11889 type = double_type_node;
11890 pedwarn (declspecs->locations[ds_complex], OPT_Wpedantic,
11891 "ISO C++ does not support plain %<complex%> meaning "
11892 "%<double complex%>");
11895 /* Gather flags. */
11896 explicit_int = declspecs->explicit_int_p;
11897 explicit_char = declspecs->explicit_char_p;
11899 #if 0
11900 /* See the code below that used this. */
11901 if (typedef_decl)
11902 decl_attr = DECL_ATTRIBUTES (typedef_decl);
11903 #endif
11904 typedef_type = type;
11906 if (sfk == sfk_conversion || sfk == sfk_deduction_guide)
11907 ctor_return_type = TREE_TYPE (dname);
11908 else
11909 ctor_return_type = ctype;
11911 if (sfk != sfk_none)
11913 type = check_special_function_return_type (sfk, type,
11914 ctor_return_type,
11915 type_quals,
11916 declspecs->locations);
11917 type_quals = TYPE_UNQUALIFIED;
11919 else if (type == NULL_TREE)
11921 int is_main;
11923 explicit_int = -1;
11925 /* We handle `main' specially here, because 'main () { }' is so
11926 common. With no options, it is allowed. With -Wreturn-type,
11927 it is a warning. It is only an error with -pedantic-errors. */
11928 is_main = (funcdef_flag
11929 && dname && identifier_p (dname)
11930 && MAIN_NAME_P (dname)
11931 && ctype == NULL_TREE
11932 && in_namespace == NULL_TREE
11933 && current_namespace == global_namespace);
11935 if (type_was_error_mark_node)
11936 /* We've already issued an error, don't complain more. */;
11937 else if (in_system_header_at (id_loc) || flag_ms_extensions)
11938 /* Allow it, sigh. */;
11939 else if (! is_main)
11940 permerror (id_loc, "ISO C++ forbids declaration of %qs with no type",
11941 name);
11942 else if (pedantic)
11943 pedwarn (id_loc, OPT_Wpedantic,
11944 "ISO C++ forbids declaration of %qs with no type", name);
11945 else
11946 warning_at (id_loc, OPT_Wreturn_type,
11947 "ISO C++ forbids declaration of %qs with no type", name);
11949 if (type_was_error_mark_node && template_parm_flag)
11950 /* FIXME we should be able to propagate the error_mark_node as is
11951 for other contexts too. */
11952 type = error_mark_node;
11953 else
11954 type = integer_type_node;
11957 ctype = NULL_TREE;
11959 if (explicit_intN)
11961 if (! int_n_enabled_p[declspecs->int_n_idx])
11963 error_at (declspecs->locations[ds_type_spec],
11964 "%<__int%d%> is not supported by this target",
11965 int_n_data[declspecs->int_n_idx].bitsize);
11966 explicit_intN = false;
11968 /* Don't pedwarn if the alternate "__intN__" form has been used instead
11969 of "__intN". */
11970 else if (!int_n_alt && pedantic)
11971 pedwarn (declspecs->locations[ds_type_spec], OPT_Wpedantic,
11972 "ISO C++ does not support %<__int%d%> for %qs",
11973 int_n_data[declspecs->int_n_idx].bitsize, name);
11976 /* Now process the modifiers that were specified
11977 and check for invalid combinations. */
11979 /* Long double is a special combination. */
11980 if (long_p && !longlong && TYPE_MAIN_VARIANT (type) == double_type_node)
11982 long_p = false;
11983 type = cp_build_qualified_type (long_double_type_node,
11984 cp_type_quals (type));
11987 /* Check all other uses of type modifiers. */
11989 if (unsigned_p || signed_p || long_p || short_p)
11991 location_t loc;
11992 const char *key;
11993 if (unsigned_p)
11995 key = "unsigned";
11996 loc = declspecs->locations[ds_unsigned];
11998 else if (signed_p)
12000 key = "signed";
12001 loc = declspecs->locations[ds_signed];
12003 else if (longlong)
12005 key = "long long";
12006 loc = declspecs->locations[ds_long_long];
12008 else if (long_p)
12010 key = "long";
12011 loc = declspecs->locations[ds_long];
12013 else /* if (short_p) */
12015 key = "short";
12016 loc = declspecs->locations[ds_short];
12019 int ok = 0;
12021 if (signed_p && unsigned_p)
12023 gcc_rich_location richloc (declspecs->locations[ds_signed]);
12024 richloc.add_range (declspecs->locations[ds_unsigned]);
12025 error_at (&richloc,
12026 "%<signed%> and %<unsigned%> specified together");
12028 else if (long_p && short_p)
12030 gcc_rich_location richloc (declspecs->locations[ds_long]);
12031 richloc.add_range (declspecs->locations[ds_short]);
12032 error_at (&richloc, "%<long%> and %<short%> specified together");
12034 else if (TREE_CODE (type) != INTEGER_TYPE
12035 || type == char8_type_node
12036 || type == char16_type_node
12037 || type == char32_type_node
12038 || ((long_p || short_p)
12039 && (explicit_char || explicit_intN)))
12040 error_at (loc, "%qs specified with %qT", key, type);
12041 else if (!explicit_int && !defaulted_int
12042 && !explicit_char && !explicit_intN)
12044 if (typedef_decl)
12046 pedwarn (loc, OPT_Wpedantic, "%qs specified with %qT",
12047 key, type);
12048 ok = !flag_pedantic_errors;
12050 else if (declspecs->decltype_p)
12051 error_at (loc, "%qs specified with %<decltype%>", key);
12052 else
12053 error_at (loc, "%qs specified with %<typeof%>", key);
12055 else
12056 ok = 1;
12058 /* Discard the type modifiers if they are invalid. */
12059 if (! ok)
12061 unsigned_p = false;
12062 signed_p = false;
12063 long_p = false;
12064 short_p = false;
12065 longlong = 0;
12069 /* Decide whether an integer type is signed or not.
12070 Optionally treat bitfields as signed by default. */
12071 if (unsigned_p
12072 /* [class.bit]
12074 It is implementation-defined whether a plain (neither
12075 explicitly signed or unsigned) char, short, int, or long
12076 bit-field is signed or unsigned.
12078 Naturally, we extend this to long long as well. Note that
12079 this does not include wchar_t. */
12080 || (bitfield && !flag_signed_bitfields
12081 && !signed_p
12082 /* A typedef for plain `int' without `signed' can be
12083 controlled just like plain `int', but a typedef for
12084 `signed int' cannot be so controlled. */
12085 && !(typedef_decl
12086 && C_TYPEDEF_EXPLICITLY_SIGNED (typedef_decl))
12087 && TREE_CODE (type) == INTEGER_TYPE
12088 && !same_type_p (TYPE_MAIN_VARIANT (type), wchar_type_node)))
12090 if (explicit_intN)
12091 type = int_n_trees[declspecs->int_n_idx].unsigned_type;
12092 else if (longlong)
12093 type = long_long_unsigned_type_node;
12094 else if (long_p)
12095 type = long_unsigned_type_node;
12096 else if (short_p)
12097 type = short_unsigned_type_node;
12098 else if (type == char_type_node)
12099 type = unsigned_char_type_node;
12100 else if (typedef_decl)
12101 type = unsigned_type_for (type);
12102 else
12103 type = unsigned_type_node;
12105 else if (signed_p && type == char_type_node)
12106 type = signed_char_type_node;
12107 else if (explicit_intN)
12108 type = int_n_trees[declspecs->int_n_idx].signed_type;
12109 else if (longlong)
12110 type = long_long_integer_type_node;
12111 else if (long_p)
12112 type = long_integer_type_node;
12113 else if (short_p)
12114 type = short_integer_type_node;
12116 if (decl_spec_seq_has_spec_p (declspecs, ds_complex))
12118 if (TREE_CODE (type) != INTEGER_TYPE && TREE_CODE (type) != REAL_TYPE)
12119 error_at (declspecs->locations[ds_complex],
12120 "complex invalid for %qs", name);
12121 /* If a modifier is specified, the resulting complex is the complex
12122 form of TYPE. E.g, "complex short" is "complex short int". */
12123 else if (type == integer_type_node)
12124 type = complex_integer_type_node;
12125 else if (type == float_type_node)
12126 type = complex_float_type_node;
12127 else if (type == double_type_node)
12128 type = complex_double_type_node;
12129 else if (type == long_double_type_node)
12130 type = complex_long_double_type_node;
12131 else
12132 type = build_complex_type (type);
12135 /* If we're using the injected-class-name to form a compound type or a
12136 declaration, replace it with the underlying class so we don't get
12137 redundant typedefs in the debug output. But if we are returning the
12138 type unchanged, leave it alone so that it's available to
12139 maybe_get_template_decl_from_type_decl. */
12140 if (CLASS_TYPE_P (type)
12141 && DECL_SELF_REFERENCE_P (TYPE_NAME (type))
12142 && type == TREE_TYPE (TYPE_NAME (type))
12143 && (declarator || type_quals))
12144 type = DECL_ORIGINAL_TYPE (TYPE_NAME (type));
12146 type_quals |= cp_type_quals (type);
12147 type = cp_build_qualified_type_real
12148 (type, type_quals, ((((typedef_decl && !DECL_ARTIFICIAL (typedef_decl))
12149 || declspecs->decltype_p)
12150 ? tf_ignore_bad_quals : 0) | tf_warning_or_error));
12151 /* We might have ignored or rejected some of the qualifiers. */
12152 type_quals = cp_type_quals (type);
12154 if (cxx_dialect >= cxx17 && type && is_auto (type)
12155 && innermost_code != cdk_function
12156 && id_declarator && declarator != id_declarator)
12157 if (tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (type))
12159 error_at (typespec_loc, "template placeholder type %qT must be followed "
12160 "by a simple declarator-id", type);
12161 inform (DECL_SOURCE_LOCATION (tmpl), "%qD declared here", tmpl);
12162 type = error_mark_node;
12165 staticp = 0;
12166 inlinep = decl_spec_seq_has_spec_p (declspecs, ds_inline);
12167 virtualp = decl_spec_seq_has_spec_p (declspecs, ds_virtual);
12168 explicitp = decl_spec_seq_has_spec_p (declspecs, ds_explicit);
12170 storage_class = declspecs->storage_class;
12171 if (storage_class == sc_static)
12172 staticp = 1 + (decl_context == FIELD);
12173 else if (decl_context == FIELD && sfk == sfk_deduction_guide)
12174 /* Treat class-scope deduction guides as static member functions
12175 so that they get a FUNCTION_TYPE instead of a METHOD_TYPE. */
12176 staticp = 2;
12178 if (virtualp)
12180 if (staticp == 2)
12182 gcc_rich_location richloc (declspecs->locations[ds_virtual]);
12183 richloc.add_range (declspecs->locations[ds_storage_class]);
12184 error_at (&richloc, "member %qD cannot be declared both %<virtual%> "
12185 "and %<static%>", dname);
12186 storage_class = sc_none;
12187 staticp = 0;
12189 if (constexpr_p && pedantic && cxx_dialect < cxx20)
12191 gcc_rich_location richloc (declspecs->locations[ds_virtual]);
12192 richloc.add_range (declspecs->locations[ds_constexpr]);
12193 pedwarn (&richloc, OPT_Wc__20_extensions, "member %qD can be "
12194 "declared both %<virtual%> and %<constexpr%> only in "
12195 "%<-std=c++20%> or %<-std=gnu++20%>", dname);
12198 friendp = decl_spec_seq_has_spec_p (declspecs, ds_friend);
12200 /* Issue errors about use of storage classes for parameters. */
12201 if (decl_context == PARM)
12203 if (typedef_p)
12205 error_at (declspecs->locations[ds_typedef],
12206 "typedef declaration invalid in parameter declaration");
12207 return error_mark_node;
12209 else if (template_parm_flag && storage_class != sc_none)
12211 error_at (min_location (declspecs->locations[ds_thread],
12212 declspecs->locations[ds_storage_class]),
12213 "storage class specified for template parameter %qs",
12214 name);
12215 return error_mark_node;
12217 else if (storage_class == sc_static
12218 || storage_class == sc_extern
12219 || thread_p)
12221 error_at (min_location (declspecs->locations[ds_thread],
12222 declspecs->locations[ds_storage_class]),
12223 "storage class specified for parameter %qs", name);
12224 return error_mark_node;
12227 /* Function parameters cannot be concept. */
12228 if (concept_p)
12230 error_at (declspecs->locations[ds_concept],
12231 "a parameter cannot be declared %qs", "concept");
12232 concept_p = 0;
12233 constexpr_p = 0;
12235 /* Function parameters cannot be constexpr. If we saw one, moan
12236 and pretend it wasn't there. */
12237 else if (constexpr_p)
12239 error_at (declspecs->locations[ds_constexpr],
12240 "a parameter cannot be declared %qs", "constexpr");
12241 constexpr_p = 0;
12243 if (constinit_p)
12245 error_at (declspecs->locations[ds_constinit],
12246 "a parameter cannot be declared %qs", "constinit");
12247 constinit_p = 0;
12249 if (consteval_p)
12251 error_at (declspecs->locations[ds_consteval],
12252 "a parameter cannot be declared %qs", "consteval");
12253 consteval_p = 0;
12257 /* Give error if `virtual' is used outside of class declaration. */
12258 if (virtualp
12259 && (current_class_name == NULL_TREE || decl_context != FIELD))
12261 error_at (declspecs->locations[ds_virtual],
12262 "%<virtual%> outside class declaration");
12263 virtualp = 0;
12266 if (innermost_code == cdk_decomp)
12268 location_t loc = (declarator->kind == cdk_reference
12269 ? declarator->declarator->id_loc : declarator->id_loc);
12270 if (inlinep)
12271 error_at (declspecs->locations[ds_inline],
12272 "structured binding declaration cannot be %qs", "inline");
12273 if (typedef_p)
12274 error_at (declspecs->locations[ds_typedef],
12275 "structured binding declaration cannot be %qs", "typedef");
12276 if (constexpr_p && !concept_p)
12277 error_at (declspecs->locations[ds_constexpr], "structured "
12278 "binding declaration cannot be %qs", "constexpr");
12279 if (consteval_p)
12280 error_at (declspecs->locations[ds_consteval], "structured "
12281 "binding declaration cannot be %qs", "consteval");
12282 if (thread_p && cxx_dialect < cxx20)
12283 pedwarn (declspecs->locations[ds_thread], OPT_Wc__20_extensions,
12284 "structured binding declaration can be %qs only in "
12285 "%<-std=c++20%> or %<-std=gnu++20%>",
12286 declspecs->gnu_thread_keyword_p
12287 ? "__thread" : "thread_local");
12288 if (concept_p)
12289 error_at (declspecs->locations[ds_concept],
12290 "structured binding declaration cannot be %qs", "concept");
12291 /* [dcl.struct.bind] "A cv that includes volatile is deprecated." */
12292 if (type_quals & TYPE_QUAL_VOLATILE)
12293 warning_at (declspecs->locations[ds_volatile], OPT_Wvolatile,
12294 "%<volatile%>-qualified structured binding is deprecated");
12295 switch (storage_class)
12297 case sc_none:
12298 break;
12299 case sc_register:
12300 error_at (loc, "structured binding declaration cannot be %qs",
12301 "register");
12302 break;
12303 case sc_static:
12304 if (cxx_dialect < cxx20)
12305 pedwarn (loc, OPT_Wc__20_extensions,
12306 "structured binding declaration can be %qs only in "
12307 "%<-std=c++20%> or %<-std=gnu++20%>", "static");
12308 break;
12309 case sc_extern:
12310 error_at (loc, "structured binding declaration cannot be %qs",
12311 "extern");
12312 break;
12313 case sc_mutable:
12314 error_at (loc, "structured binding declaration cannot be %qs",
12315 "mutable");
12316 break;
12317 case sc_auto:
12318 error_at (loc, "structured binding declaration cannot be "
12319 "C++98 %<auto%>");
12320 break;
12321 default:
12322 gcc_unreachable ();
12324 if (TREE_CODE (type) != TEMPLATE_TYPE_PARM
12325 || TYPE_IDENTIFIER (type) != auto_identifier)
12327 if (type != error_mark_node)
12329 error_at (loc, "structured binding declaration cannot have "
12330 "type %qT", type);
12331 inform (loc,
12332 "type must be cv-qualified %<auto%> or reference to "
12333 "cv-qualified %<auto%>");
12335 type = build_qualified_type (make_auto (), type_quals);
12336 declspecs->type = type;
12338 inlinep = 0;
12339 typedef_p = 0;
12340 constexpr_p = 0;
12341 consteval_p = 0;
12342 concept_p = 0;
12343 if (storage_class != sc_static)
12345 storage_class = sc_none;
12346 declspecs->storage_class = sc_none;
12350 /* Static anonymous unions are dealt with here. */
12351 if (staticp && decl_context == TYPENAME
12352 && declspecs->type
12353 && ANON_AGGR_TYPE_P (declspecs->type))
12354 decl_context = FIELD;
12356 /* Warn about storage classes that are invalid for certain
12357 kinds of declarations (parameters, typenames, etc.). */
12358 if (thread_p
12359 && ((storage_class
12360 && storage_class != sc_extern
12361 && storage_class != sc_static)
12362 || typedef_p))
12364 location_t loc
12365 = min_location (declspecs->locations[ds_thread],
12366 declspecs->locations[ds_storage_class]);
12367 error_at (loc, "multiple storage classes in declaration of %qs", name);
12368 thread_p = false;
12370 if (decl_context != NORMAL
12371 && ((storage_class != sc_none
12372 && storage_class != sc_mutable)
12373 || thread_p))
12375 if ((decl_context == PARM || decl_context == CATCHPARM)
12376 && (storage_class == sc_register
12377 || storage_class == sc_auto))
12379 else if (typedef_p)
12381 else if (decl_context == FIELD
12382 /* C++ allows static class elements. */
12383 && storage_class == sc_static)
12384 /* C++ also allows inlines and signed and unsigned elements,
12385 but in those cases we don't come in here. */
12387 else
12389 location_t loc
12390 = min_location (declspecs->locations[ds_thread],
12391 declspecs->locations[ds_storage_class]);
12392 if (decl_context == FIELD)
12393 error_at (loc, "storage class specified for %qs", name);
12394 else if (decl_context == PARM || decl_context == CATCHPARM)
12395 error_at (loc, "storage class specified for parameter %qs", name);
12396 else
12397 error_at (loc, "storage class specified for typename");
12398 if (storage_class == sc_register
12399 || storage_class == sc_auto
12400 || storage_class == sc_extern
12401 || thread_p)
12402 storage_class = sc_none;
12405 else if (storage_class == sc_extern && funcdef_flag
12406 && ! toplevel_bindings_p ())
12407 error ("nested function %qs declared %<extern%>", name);
12408 else if (toplevel_bindings_p ())
12410 if (storage_class == sc_auto)
12411 error_at (declspecs->locations[ds_storage_class],
12412 "top-level declaration of %qs specifies %<auto%>", name);
12414 else if (thread_p
12415 && storage_class != sc_extern
12416 && storage_class != sc_static)
12418 if (declspecs->gnu_thread_keyword_p)
12419 pedwarn (declspecs->locations[ds_thread],
12420 0, "function-scope %qs implicitly auto and "
12421 "declared %<__thread%>", name);
12423 /* When thread_local is applied to a variable of block scope the
12424 storage-class-specifier static is implied if it does not appear
12425 explicitly. */
12426 storage_class = declspecs->storage_class = sc_static;
12427 staticp = 1;
12430 if (storage_class && friendp)
12432 error_at (min_location (declspecs->locations[ds_thread],
12433 declspecs->locations[ds_storage_class]),
12434 "storage class specifiers invalid in friend function "
12435 "declarations");
12436 storage_class = sc_none;
12437 staticp = 0;
12440 if (!id_declarator)
12441 unqualified_id = NULL_TREE;
12442 else
12444 unqualified_id = id_declarator->u.id.unqualified_name;
12445 switch (TREE_CODE (unqualified_id))
12447 case BIT_NOT_EXPR:
12448 unqualified_id = TREE_OPERAND (unqualified_id, 0);
12449 if (TYPE_P (unqualified_id))
12450 unqualified_id = constructor_name (unqualified_id);
12451 break;
12453 case IDENTIFIER_NODE:
12454 case TEMPLATE_ID_EXPR:
12455 break;
12457 default:
12458 gcc_unreachable ();
12462 if (declspecs->std_attributes)
12464 location_t attr_loc = declspecs->locations[ds_std_attribute];
12465 if (warning_at (attr_loc, OPT_Wattributes, "attribute ignored"))
12466 inform (attr_loc, "an attribute that appertains to a type-specifier "
12467 "is ignored");
12470 /* Determine the type of the entity declared by recurring on the
12471 declarator. */
12472 for (; declarator; declarator = declarator->declarator)
12474 const cp_declarator *inner_declarator;
12475 tree attrs;
12477 if (type == error_mark_node)
12478 return error_mark_node;
12480 attrs = declarator->attributes;
12481 if (attrs)
12483 int attr_flags;
12485 attr_flags = 0;
12486 if (declarator->kind == cdk_id)
12487 attr_flags |= (int) ATTR_FLAG_DECL_NEXT;
12488 if (declarator->kind == cdk_function)
12489 attr_flags |= (int) ATTR_FLAG_FUNCTION_NEXT;
12490 if (declarator->kind == cdk_array)
12491 attr_flags |= (int) ATTR_FLAG_ARRAY_NEXT;
12492 tree late_attrs = NULL_TREE;
12493 if (decl_context != PARM && decl_context != TYPENAME)
12494 /* Assume that any attributes that get applied late to
12495 templates will DTRT when applied to the declaration
12496 as a whole. */
12497 late_attrs = splice_template_attributes (&attrs, type);
12498 returned_attrs = decl_attributes (&type,
12499 chainon (returned_attrs, attrs),
12500 attr_flags);
12501 returned_attrs = chainon (late_attrs, returned_attrs);
12504 inner_declarator = declarator->declarator;
12506 /* We don't want to warn in parameter context because we don't
12507 yet know if the parse will succeed, and this might turn out
12508 to be a constructor call. */
12509 if (decl_context != PARM
12510 && decl_context != TYPENAME
12511 && !typedef_p
12512 && declarator->parenthesized != UNKNOWN_LOCATION
12513 /* If the type is class-like and the inner name used a
12514 global namespace qualifier, we need the parens.
12515 Unfortunately all we can tell is whether a qualified name
12516 was used or not. */
12517 && !(inner_declarator
12518 && inner_declarator->kind == cdk_id
12519 && inner_declarator->u.id.qualifying_scope
12520 && (MAYBE_CLASS_TYPE_P (type)
12521 || TREE_CODE (type) == ENUMERAL_TYPE)))
12523 if (warning_at (declarator->parenthesized, OPT_Wparentheses,
12524 "unnecessary parentheses in declaration of %qs",
12525 name))
12527 gcc_rich_location iloc (declarator->parenthesized);
12528 iloc.add_fixit_remove (get_start (declarator->parenthesized));
12529 iloc.add_fixit_remove (get_finish (declarator->parenthesized));
12530 inform (&iloc, "remove parentheses");
12533 if (declarator->kind == cdk_id || declarator->kind == cdk_decomp)
12534 break;
12536 switch (declarator->kind)
12538 case cdk_array:
12539 type = create_array_type_for_decl (dname, type,
12540 declarator->u.array.bounds,
12541 declarator->id_loc);
12542 if (!valid_array_size_p (dname
12543 ? declarator->id_loc : input_location,
12544 type, dname))
12545 type = error_mark_node;
12547 if (declarator->std_attributes)
12548 /* [dcl.array]/1:
12550 The optional attribute-specifier-seq appertains to the
12551 array. */
12552 returned_attrs = chainon (returned_attrs,
12553 declarator->std_attributes);
12554 break;
12556 case cdk_function:
12558 tree arg_types;
12559 int funcdecl_p;
12561 /* Declaring a function type. */
12563 /* Pick up type qualifiers which should be applied to `this'. */
12564 memfn_quals = declarator->u.function.qualifiers;
12565 /* Pick up virt-specifiers. */
12566 virt_specifiers = declarator->u.function.virt_specifiers;
12567 /* And ref-qualifier, too */
12568 rqual = declarator->u.function.ref_qualifier;
12569 /* And tx-qualifier. */
12570 tree tx_qual = declarator->u.function.tx_qualifier;
12571 /* Pick up the exception specifications. */
12572 raises = declarator->u.function.exception_specification;
12573 /* If the exception-specification is ill-formed, let's pretend
12574 there wasn't one. */
12575 if (raises == error_mark_node)
12576 raises = NULL_TREE;
12578 if (reqs)
12579 error_at (location_of (reqs), "requires-clause on return type");
12580 reqs = declarator->u.function.requires_clause;
12582 /* Say it's a definition only for the CALL_EXPR
12583 closest to the identifier. */
12584 funcdecl_p = inner_declarator && inner_declarator->kind == cdk_id;
12586 /* Handle a late-specified return type. */
12587 tree late_return_type = declarator->u.function.late_return_type;
12588 if (tree auto_node = type_uses_auto (type))
12590 if (!late_return_type)
12592 if (!funcdecl_p)
12593 /* auto (*fp)() = f; is OK. */;
12594 else if (current_class_type
12595 && LAMBDA_TYPE_P (current_class_type))
12596 /* OK for C++11 lambdas. */;
12597 else if (cxx_dialect < cxx14)
12599 error_at (typespec_loc, "%qs function uses "
12600 "%<auto%> type specifier without "
12601 "trailing return type", name);
12602 inform (typespec_loc,
12603 "deduced return type only available "
12604 "with %<-std=c++14%> or %<-std=gnu++14%>");
12606 else if (virtualp)
12608 error_at (typespec_loc, "virtual function "
12609 "cannot have deduced return type");
12610 virtualp = false;
12613 else if (!is_auto (type) && sfk != sfk_conversion)
12615 error_at (typespec_loc, "%qs function with trailing "
12616 "return type has %qT as its type rather "
12617 "than plain %<auto%>", name, type);
12618 return error_mark_node;
12620 else if (is_auto (type) && AUTO_IS_DECLTYPE (type))
12622 if (funcdecl_p)
12623 error_at (typespec_loc,
12624 "%qs function with trailing return type "
12625 "has %<decltype(auto)%> as its type "
12626 "rather than plain %<auto%>", name);
12627 else
12628 error_at (typespec_loc,
12629 "invalid use of %<decltype(auto)%>");
12630 return error_mark_node;
12632 tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node);
12633 if (!tmpl)
12634 if (tree late_auto = type_uses_auto (late_return_type))
12635 tmpl = CLASS_PLACEHOLDER_TEMPLATE (late_auto);
12636 if (tmpl && funcdecl_p)
12638 if (!dguide_name_p (unqualified_id))
12640 error_at (declarator->id_loc, "deduced class "
12641 "type %qD in function return type",
12642 DECL_NAME (tmpl));
12643 inform (DECL_SOURCE_LOCATION (tmpl),
12644 "%qD declared here", tmpl);
12645 return error_mark_node;
12647 else if (!late_return_type)
12649 error_at (declarator->id_loc, "deduction guide "
12650 "for %qT must have trailing return "
12651 "type", TREE_TYPE (tmpl));
12652 inform (DECL_SOURCE_LOCATION (tmpl),
12653 "%qD declared here", tmpl);
12654 return error_mark_node;
12656 else if (CLASS_TYPE_P (late_return_type)
12657 && CLASSTYPE_TEMPLATE_INFO (late_return_type)
12658 && (CLASSTYPE_TI_TEMPLATE (late_return_type)
12659 == tmpl))
12660 /* OK */;
12661 else
12662 error ("trailing return type %qT of deduction guide "
12663 "is not a specialization of %qT",
12664 late_return_type, TREE_TYPE (tmpl));
12667 else if (late_return_type
12668 && sfk != sfk_conversion)
12670 if (late_return_type == error_mark_node)
12671 return error_mark_node;
12672 if (cxx_dialect < cxx11)
12673 /* Not using maybe_warn_cpp0x because this should
12674 always be an error. */
12675 error_at (typespec_loc,
12676 "trailing return type only available "
12677 "with %<-std=c++11%> or %<-std=gnu++11%>");
12678 else
12679 error_at (typespec_loc, "%qs function with trailing "
12680 "return type not declared with %<auto%> "
12681 "type specifier", name);
12682 return error_mark_node;
12684 type = splice_late_return_type (type, late_return_type);
12685 if (type == error_mark_node)
12686 return error_mark_node;
12688 if (late_return_type)
12690 late_return_type_p = true;
12691 type_quals = cp_type_quals (type);
12694 if (type_quals != TYPE_UNQUALIFIED)
12696 if (SCALAR_TYPE_P (type) || VOID_TYPE_P (type))
12697 warning_at (typespec_loc, OPT_Wignored_qualifiers, "type "
12698 "qualifiers ignored on function return type");
12699 /* [dcl.fct] "A volatile-qualified return type is
12700 deprecated." */
12701 if (type_quals & TYPE_QUAL_VOLATILE)
12702 warning_at (typespec_loc, OPT_Wvolatile,
12703 "%<volatile%>-qualified return type is "
12704 "deprecated");
12706 /* We now know that the TYPE_QUALS don't apply to the
12707 decl, but to its return type. */
12708 type_quals = TYPE_UNQUALIFIED;
12711 /* Error about some types functions can't return. */
12713 if (TREE_CODE (type) == FUNCTION_TYPE)
12715 error_at (typespec_loc, "%qs declared as function returning "
12716 "a function", name);
12717 return error_mark_node;
12719 if (TREE_CODE (type) == ARRAY_TYPE)
12721 error_at (typespec_loc, "%qs declared as function returning "
12722 "an array", name);
12723 return error_mark_node;
12725 if (constinit_p)
12727 error_at (declspecs->locations[ds_constinit],
12728 "%<constinit%> on function return type is not "
12729 "allowed");
12730 return error_mark_node;
12733 if (check_decltype_auto (typespec_loc, type))
12734 return error_mark_node;
12736 if (ctype == NULL_TREE
12737 && decl_context == FIELD
12738 && funcdecl_p
12739 && friendp == 0)
12740 ctype = current_class_type;
12742 if (ctype && (sfk == sfk_constructor
12743 || sfk == sfk_destructor))
12745 /* We are within a class's scope. If our declarator name
12746 is the same as the class name, and we are defining
12747 a function, then it is a constructor/destructor, and
12748 therefore returns a void type. */
12750 /* ISO C++ 12.4/2. A destructor may not be declared
12751 const or volatile. A destructor may not be static.
12752 A destructor may not be declared with ref-qualifier.
12754 ISO C++ 12.1. A constructor may not be declared
12755 const or volatile. A constructor may not be
12756 virtual. A constructor may not be static.
12757 A constructor may not be declared with ref-qualifier. */
12758 if (staticp == 2)
12759 error_at (declspecs->locations[ds_storage_class],
12760 (flags == DTOR_FLAG)
12761 ? G_("destructor cannot be static member "
12762 "function")
12763 : G_("constructor cannot be static member "
12764 "function"));
12765 if (memfn_quals)
12767 error ((flags == DTOR_FLAG)
12768 ? G_("destructors may not be cv-qualified")
12769 : G_("constructors may not be cv-qualified"));
12770 memfn_quals = TYPE_UNQUALIFIED;
12773 if (rqual)
12775 maybe_warn_cpp0x (CPP0X_REF_QUALIFIER);
12776 error ((flags == DTOR_FLAG)
12777 ? G_("destructors may not be ref-qualified")
12778 : G_("constructors may not be ref-qualified"));
12779 rqual = REF_QUAL_NONE;
12782 if (decl_context == FIELD
12783 && !member_function_or_else (ctype,
12784 current_class_type,
12785 flags))
12786 return error_mark_node;
12788 if (flags != DTOR_FLAG)
12790 /* It's a constructor. */
12791 if (explicitp == 1)
12792 explicitp = 2;
12793 if (virtualp)
12795 permerror (declspecs->locations[ds_virtual],
12796 "constructors cannot be declared %<virtual%>");
12797 virtualp = 0;
12799 if (decl_context == FIELD
12800 && sfk != sfk_constructor)
12801 return error_mark_node;
12803 if (decl_context == FIELD)
12804 staticp = 0;
12806 else if (friendp)
12808 if (virtualp)
12810 /* Cannot be both friend and virtual. */
12811 gcc_rich_location richloc (declspecs->locations[ds_virtual]);
12812 richloc.add_range (declspecs->locations[ds_friend]);
12813 error_at (&richloc, "virtual functions cannot be friends");
12814 friendp = 0;
12816 if (decl_context == NORMAL)
12817 error_at (declarator->id_loc,
12818 "friend declaration not in class definition");
12819 if (current_function_decl && funcdef_flag)
12821 error_at (declarator->id_loc,
12822 "cannot define friend function %qs in a local "
12823 "class definition", name);
12824 friendp = 0;
12826 /* [class.friend]/6: A function can be defined in a friend
12827 declaration if the function name is unqualified. */
12828 if (funcdef_flag && in_namespace)
12830 if (in_namespace == global_namespace)
12831 error_at (declarator->id_loc,
12832 "friend function definition %qs cannot have "
12833 "a name qualified with %<::%>", name);
12834 else
12835 error_at (declarator->id_loc,
12836 "friend function definition %qs cannot have "
12837 "a name qualified with %<%D::%>", name,
12838 in_namespace);
12841 else if (ctype && sfk == sfk_conversion)
12843 if (explicitp == 1)
12845 maybe_warn_cpp0x (CPP0X_EXPLICIT_CONVERSION);
12846 explicitp = 2;
12848 if (late_return_type_p)
12849 error ("a conversion function cannot have a trailing return type");
12851 else if (sfk == sfk_deduction_guide)
12853 if (explicitp == 1)
12854 explicitp = 2;
12857 tree pushed_scope = NULL_TREE;
12858 if (funcdecl_p
12859 && decl_context != FIELD
12860 && inner_declarator->u.id.qualifying_scope
12861 && CLASS_TYPE_P (inner_declarator->u.id.qualifying_scope))
12862 pushed_scope
12863 = push_scope (inner_declarator->u.id.qualifying_scope);
12865 arg_types = grokparms (declarator->u.function.parameters, &parms);
12867 if (pushed_scope)
12868 pop_scope (pushed_scope);
12870 if (inner_declarator
12871 && inner_declarator->kind == cdk_id
12872 && inner_declarator->u.id.sfk == sfk_destructor
12873 && arg_types != void_list_node)
12875 error_at (declarator->id_loc,
12876 "destructors may not have parameters");
12877 arg_types = void_list_node;
12878 parms = NULL_TREE;
12881 type = build_function_type (type, arg_types);
12883 tree attrs = declarator->std_attributes;
12884 if (tx_qual)
12886 tree att = build_tree_list (tx_qual, NULL_TREE);
12887 /* transaction_safe applies to the type, but
12888 transaction_safe_dynamic applies to the function. */
12889 if (is_attribute_p ("transaction_safe", tx_qual))
12890 attrs = chainon (attrs, att);
12891 else
12892 returned_attrs = chainon (returned_attrs, att);
12894 if (attrs)
12895 /* [dcl.fct]/2:
12897 The optional attribute-specifier-seq appertains to
12898 the function type. */
12899 cplus_decl_attributes (&type, attrs, 0);
12901 if (raises)
12902 type = build_exception_variant (type, raises);
12904 break;
12906 case cdk_pointer:
12907 case cdk_reference:
12908 case cdk_ptrmem:
12909 /* Filter out pointers-to-references and references-to-references.
12910 We can get these if a TYPE_DECL is used. */
12912 if (TYPE_REF_P (type))
12914 if (declarator->kind != cdk_reference)
12916 error ("cannot declare pointer to %q#T", type);
12917 type = TREE_TYPE (type);
12920 /* In C++0x, we allow reference to reference declarations
12921 that occur indirectly through typedefs [7.1.3/8 dcl.typedef]
12922 and template type arguments [14.3.1/4 temp.arg.type]. The
12923 check for direct reference to reference declarations, which
12924 are still forbidden, occurs below. Reasoning behind the change
12925 can be found in DR106, DR540, and the rvalue reference
12926 proposals. */
12927 else if (cxx_dialect == cxx98)
12929 error ("cannot declare reference to %q#T", type);
12930 type = TREE_TYPE (type);
12933 else if (VOID_TYPE_P (type))
12935 if (declarator->kind == cdk_reference)
12936 error ("cannot declare reference to %q#T", type);
12937 else if (declarator->kind == cdk_ptrmem)
12938 error ("cannot declare pointer to %q#T member", type);
12941 /* We now know that the TYPE_QUALS don't apply to the decl,
12942 but to the target of the pointer. */
12943 type_quals = TYPE_UNQUALIFIED;
12945 /* This code used to handle METHOD_TYPE, but I don't think it's
12946 possible to get it here anymore. */
12947 gcc_assert (TREE_CODE (type) != METHOD_TYPE);
12948 if (declarator->kind == cdk_ptrmem
12949 && TREE_CODE (type) == FUNCTION_TYPE)
12951 memfn_quals |= type_memfn_quals (type);
12952 type = build_memfn_type (type,
12953 declarator->u.pointer.class_type,
12954 memfn_quals,
12955 rqual);
12956 if (type == error_mark_node)
12957 return error_mark_node;
12959 rqual = REF_QUAL_NONE;
12960 memfn_quals = TYPE_UNQUALIFIED;
12963 if (TREE_CODE (type) == FUNCTION_TYPE
12964 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
12965 || type_memfn_rqual (type) != REF_QUAL_NONE))
12966 error (declarator->kind == cdk_reference
12967 ? G_("cannot declare reference to qualified function type %qT")
12968 : G_("cannot declare pointer to qualified function type %qT"),
12969 type);
12971 /* When the pointed-to type involves components of variable size,
12972 care must be taken to ensure that the size evaluation code is
12973 emitted early enough to dominate all the possible later uses
12974 and late enough for the variables on which it depends to have
12975 been assigned.
12977 This is expected to happen automatically when the pointed-to
12978 type has a name/declaration of it's own, but special attention
12979 is required if the type is anonymous.
12981 We handle the NORMAL and FIELD contexts here by inserting a
12982 dummy statement that just evaluates the size at a safe point
12983 and ensures it is not deferred until e.g. within a deeper
12984 conditional context (c++/43555).
12986 We expect nothing to be needed here for PARM or TYPENAME.
12987 Evaluating the size at this point for TYPENAME would
12988 actually be incorrect, as we might be in the middle of an
12989 expression with side effects on the pointed-to type size
12990 "arguments" prior to the pointer declaration point and the
12991 size evaluation could end up prior to the side effects. */
12993 if (!TYPE_NAME (type)
12994 && (decl_context == NORMAL || decl_context == FIELD)
12995 && at_function_scope_p ()
12996 && variably_modified_type_p (type, NULL_TREE))
12998 TYPE_NAME (type) = build_decl (UNKNOWN_LOCATION, TYPE_DECL,
12999 NULL_TREE, type);
13000 add_decl_expr (TYPE_NAME (type));
13003 if (declarator->kind == cdk_reference)
13005 /* In C++0x, the type we are creating a reference to might be
13006 a typedef which is itself a reference type. In that case,
13007 we follow the reference collapsing rules in
13008 [7.1.3/8 dcl.typedef] to create the final reference type:
13010 "If a typedef TD names a type that is a reference to a type
13011 T, an attempt to create the type 'lvalue reference to cv TD'
13012 creates the type 'lvalue reference to T,' while an attempt
13013 to create the type "rvalue reference to cv TD' creates the
13014 type TD."
13016 if (VOID_TYPE_P (type))
13017 /* We already gave an error. */;
13018 else if (TYPE_REF_P (type))
13020 if (declarator->u.reference.rvalue_ref)
13021 /* Leave type alone. */;
13022 else
13023 type = cp_build_reference_type (TREE_TYPE (type), false);
13025 else
13026 type = cp_build_reference_type
13027 (type, declarator->u.reference.rvalue_ref);
13029 /* In C++0x, we need this check for direct reference to
13030 reference declarations, which are forbidden by
13031 [8.3.2/5 dcl.ref]. Reference to reference declarations
13032 are only allowed indirectly through typedefs and template
13033 type arguments. Example:
13035 void foo(int & &); // invalid ref-to-ref decl
13037 typedef int & int_ref;
13038 void foo(int_ref &); // valid ref-to-ref decl
13040 if (inner_declarator && inner_declarator->kind == cdk_reference)
13041 error ("cannot declare reference to %q#T, which is not "
13042 "a typedef or a template type argument", type);
13044 else if (TREE_CODE (type) == METHOD_TYPE)
13045 type = build_ptrmemfunc_type (build_pointer_type (type));
13046 else if (declarator->kind == cdk_ptrmem)
13048 gcc_assert (TREE_CODE (declarator->u.pointer.class_type)
13049 != NAMESPACE_DECL);
13050 if (declarator->u.pointer.class_type == error_mark_node)
13051 /* We will already have complained. */
13052 type = error_mark_node;
13053 else
13054 type = build_ptrmem_type (declarator->u.pointer.class_type,
13055 type);
13057 else
13058 type = build_pointer_type (type);
13060 /* Process a list of type modifier keywords (such as
13061 const or volatile) that were given inside the `*' or `&'. */
13063 if (declarator->u.pointer.qualifiers)
13065 type
13066 = cp_build_qualified_type (type,
13067 declarator->u.pointer.qualifiers);
13068 type_quals = cp_type_quals (type);
13071 /* Apply C++11 attributes to the pointer, and not to the
13072 type pointed to. This is unlike what is done for GNU
13073 attributes above. It is to comply with [dcl.ptr]/1:
13075 [the optional attribute-specifier-seq (7.6.1) appertains
13076 to the pointer and not to the object pointed to]. */
13077 if (declarator->std_attributes)
13078 decl_attributes (&type, declarator->std_attributes,
13081 ctype = NULL_TREE;
13082 break;
13084 case cdk_error:
13085 break;
13087 default:
13088 gcc_unreachable ();
13092 id_loc = declarator ? declarator->id_loc : input_location;
13094 if (innermost_code != cdk_function
13095 /* Don't check this if it can be the artifical decltype(auto)
13096 we created when building a constraint in a compound-requirement:
13097 that the type-constraint is plain is going to be checked in
13098 cp_parser_compound_requirement. */
13099 && decl_context != TYPENAME
13100 && check_decltype_auto (id_loc, type))
13101 return error_mark_node;
13103 /* A `constexpr' specifier used in an object declaration declares
13104 the object as `const'. */
13105 if (constexpr_p && innermost_code != cdk_function)
13107 /* DR1688 says that a `constexpr' specifier in combination with
13108 `volatile' is valid. */
13110 if (!TYPE_REF_P (type))
13112 type_quals |= TYPE_QUAL_CONST;
13113 type = cp_build_qualified_type (type, type_quals);
13117 if (unqualified_id && TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR
13118 && !FUNC_OR_METHOD_TYPE_P (type)
13119 && !variable_template_p (TREE_OPERAND (unqualified_id, 0)))
13121 error ("template-id %qD used as a declarator",
13122 unqualified_id);
13123 unqualified_id = dname;
13126 /* If TYPE is a FUNCTION_TYPE, but the function name was explicitly
13127 qualified with a class-name, turn it into a METHOD_TYPE, unless
13128 we know that the function is static. We take advantage of this
13129 opportunity to do other processing that pertains to entities
13130 explicitly declared to be class members. Note that if DECLARATOR
13131 is non-NULL, we know it is a cdk_id declarator; otherwise, we
13132 would not have exited the loop above. */
13133 if (declarator
13134 && declarator->kind == cdk_id
13135 && declarator->u.id.qualifying_scope
13136 && MAYBE_CLASS_TYPE_P (declarator->u.id.qualifying_scope))
13138 ctype = declarator->u.id.qualifying_scope;
13139 ctype = TYPE_MAIN_VARIANT (ctype);
13140 template_count = num_template_headers_for_class (ctype);
13142 if (ctype == current_class_type)
13144 if (friendp)
13146 permerror (declspecs->locations[ds_friend],
13147 "member functions are implicitly "
13148 "friends of their class");
13149 friendp = 0;
13151 else
13152 permerror (id_loc, "extra qualification %<%T::%> on member %qs",
13153 ctype, name);
13155 else if (/* If the qualifying type is already complete, then we
13156 can skip the following checks. */
13157 !COMPLETE_TYPE_P (ctype)
13158 && (/* If the function is being defined, then
13159 qualifying type must certainly be complete. */
13160 funcdef_flag
13161 /* A friend declaration of "T::f" is OK, even if
13162 "T" is a template parameter. But, if this
13163 function is not a friend, the qualifying type
13164 must be a class. */
13165 || (!friendp && !CLASS_TYPE_P (ctype))
13166 /* For a declaration, the type need not be
13167 complete, if either it is dependent (since there
13168 is no meaningful definition of complete in that
13169 case) or the qualifying class is currently being
13170 defined. */
13171 || !(dependent_type_p (ctype)
13172 || currently_open_class (ctype)))
13173 /* Check that the qualifying type is complete. */
13174 && !complete_type_or_else (ctype, NULL_TREE))
13175 return error_mark_node;
13176 else if (TREE_CODE (type) == FUNCTION_TYPE)
13178 if (current_class_type
13179 && (!friendp || funcdef_flag || initialized))
13181 error_at (id_loc, funcdef_flag || initialized
13182 ? G_("cannot define member function %<%T::%s%> "
13183 "within %qT")
13184 : G_("cannot declare member function %<%T::%s%> "
13185 "within %qT"),
13186 ctype, name, current_class_type);
13187 return error_mark_node;
13190 else if (typedef_p && current_class_type)
13192 error_at (id_loc, "cannot declare member %<%T::%s%> within %qT",
13193 ctype, name, current_class_type);
13194 return error_mark_node;
13198 if (ctype == NULL_TREE && decl_context == FIELD && friendp == 0)
13199 ctype = current_class_type;
13201 /* Now TYPE has the actual type. */
13203 if (returned_attrs)
13205 if (attrlist)
13206 *attrlist = chainon (returned_attrs, *attrlist);
13207 else
13208 attrlist = &returned_attrs;
13211 if (declarator
13212 && declarator->kind == cdk_id
13213 && declarator->std_attributes
13214 && attrlist != NULL)
13216 /* [dcl.meaning]/1: The optional attribute-specifier-seq following
13217 a declarator-id appertains to the entity that is declared. */
13218 if (declarator->std_attributes != error_mark_node)
13219 *attrlist = chainon (*attrlist, declarator->std_attributes);
13220 else
13221 /* We should have already diagnosed the issue (c++/78344). */
13222 gcc_assert (seen_error ());
13225 /* Handle parameter packs. */
13226 if (parameter_pack_p)
13228 if (decl_context == PARM)
13229 /* Turn the type into a pack expansion.*/
13230 type = make_pack_expansion (type);
13231 else
13232 error ("non-parameter %qs cannot be a parameter pack", name);
13235 if ((decl_context == FIELD || decl_context == PARM)
13236 && !processing_template_decl
13237 && variably_modified_type_p (type, NULL_TREE))
13239 if (decl_context == FIELD)
13240 error_at (id_loc,
13241 "data member may not have variably modified type %qT", type);
13242 else
13243 error_at (id_loc,
13244 "parameter may not have variably modified type %qT", type);
13245 type = error_mark_node;
13248 if (explicitp == 1 || (explicitp && friendp))
13250 /* [dcl.fct.spec] (C++11) The explicit specifier shall be used only
13251 in the declaration of a constructor or conversion function within
13252 a class definition. */
13253 if (!current_class_type)
13254 error_at (declspecs->locations[ds_explicit],
13255 "%<explicit%> outside class declaration");
13256 else if (friendp)
13257 error_at (declspecs->locations[ds_explicit],
13258 "%<explicit%> in friend declaration");
13259 else
13260 error_at (declspecs->locations[ds_explicit],
13261 "only declarations of constructors and conversion operators "
13262 "can be %<explicit%>");
13263 explicitp = 0;
13266 if (storage_class == sc_mutable)
13268 location_t sloc = declspecs->locations[ds_storage_class];
13269 if (decl_context != FIELD || friendp)
13271 error_at (sloc, "non-member %qs cannot be declared %<mutable%>",
13272 name);
13273 storage_class = sc_none;
13275 else if (decl_context == TYPENAME || typedef_p)
13277 error_at (sloc,
13278 "non-object member %qs cannot be declared %<mutable%>",
13279 name);
13280 storage_class = sc_none;
13282 else if (FUNC_OR_METHOD_TYPE_P (type))
13284 error_at (sloc, "function %qs cannot be declared %<mutable%>",
13285 name);
13286 storage_class = sc_none;
13288 else if (staticp)
13290 error_at (sloc, "%<static%> %qs cannot be declared %<mutable%>",
13291 name);
13292 storage_class = sc_none;
13294 else if (type_quals & TYPE_QUAL_CONST)
13296 error_at (sloc, "%<const%> %qs cannot be declared %<mutable%>",
13297 name);
13298 storage_class = sc_none;
13300 else if (TYPE_REF_P (type))
13302 permerror (sloc, "reference %qs cannot be declared %<mutable%>",
13303 name);
13304 storage_class = sc_none;
13308 /* If this is declaring a typedef name, return a TYPE_DECL. */
13309 if (typedef_p && decl_context != TYPENAME)
13311 bool alias_p = decl_spec_seq_has_spec_p (declspecs, ds_alias);
13312 tree decl;
13314 if (funcdef_flag)
13316 if (decl_context == NORMAL)
13317 error_at (id_loc,
13318 "typedef may not be a function definition");
13319 else
13320 error_at (id_loc,
13321 "typedef may not be a member function definition");
13322 return error_mark_node;
13325 /* This declaration:
13327 typedef void f(int) const;
13329 declares a function type which is not a member of any
13330 particular class, but which is cv-qualified; for
13331 example "f S::*" declares a pointer to a const-qualified
13332 member function of S. We record the cv-qualification in the
13333 function type. */
13334 if ((rqual || memfn_quals) && TREE_CODE (type) == FUNCTION_TYPE)
13336 type = apply_memfn_quals (type, memfn_quals, rqual);
13338 /* We have now dealt with these qualifiers. */
13339 memfn_quals = TYPE_UNQUALIFIED;
13340 rqual = REF_QUAL_NONE;
13343 if (type_uses_auto (type))
13345 if (alias_p)
13346 error_at (declspecs->locations[ds_type_spec],
13347 "%<auto%> not allowed in alias declaration");
13348 else
13349 error_at (declspecs->locations[ds_type_spec],
13350 "typedef declared %<auto%>");
13351 type = error_mark_node;
13354 if (reqs)
13355 error_at (location_of (reqs), "requires-clause on typedef");
13357 if (id_declarator && declarator->u.id.qualifying_scope)
13359 error_at (id_loc, "typedef name may not be a nested-name-specifier");
13360 type = error_mark_node;
13363 if (decl_context == FIELD)
13364 decl = build_lang_decl_loc (id_loc, TYPE_DECL, unqualified_id, type);
13365 else
13366 decl = build_decl (id_loc, TYPE_DECL, unqualified_id, type);
13368 if (decl_context != FIELD)
13370 if (!current_function_decl)
13371 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
13372 else if (DECL_MAYBE_IN_CHARGE_CDTOR_P (current_function_decl))
13373 /* The TYPE_DECL is "abstract" because there will be
13374 clones of this constructor/destructor, and there will
13375 be copies of this TYPE_DECL generated in those
13376 clones. The decloning optimization (for space) may
13377 revert this subsequently if it determines that
13378 the clones should share a common implementation. */
13379 DECL_ABSTRACT_P (decl) = true;
13381 set_originating_module (decl);
13383 else if (current_class_type
13384 && constructor_name_p (unqualified_id, current_class_type))
13385 permerror (id_loc, "ISO C++ forbids nested type %qD with same name "
13386 "as enclosing class",
13387 unqualified_id);
13389 /* If the user declares "typedef struct {...} foo" then the
13390 struct will have an anonymous name. Fill that name in now.
13391 Nothing can refer to it, so nothing needs know about the name
13392 change. */
13393 if (type != error_mark_node
13394 && unqualified_id
13395 && TYPE_NAME (type)
13396 && TREE_CODE (TYPE_NAME (type)) == TYPE_DECL
13397 && TYPE_UNNAMED_P (type)
13398 && declspecs->type_definition_p
13399 && attributes_naming_typedef_ok (*attrlist)
13400 && cp_type_quals (type) == TYPE_UNQUALIFIED)
13401 name_unnamed_type (type, decl);
13403 if (signed_p
13404 || (typedef_decl && C_TYPEDEF_EXPLICITLY_SIGNED (typedef_decl)))
13405 C_TYPEDEF_EXPLICITLY_SIGNED (decl) = 1;
13407 bad_specifiers (decl, BSP_TYPE, virtualp,
13408 memfn_quals != TYPE_UNQUALIFIED,
13409 inlinep, friendp, raises != NULL_TREE,
13410 declspecs->locations);
13412 if (alias_p)
13413 /* Acknowledge that this was written:
13414 `using analias = atype;'. */
13415 TYPE_DECL_ALIAS_P (decl) = 1;
13417 return decl;
13420 /* Detect the case of an array type of unspecified size
13421 which came, as such, direct from a typedef name.
13422 We must copy the type, so that the array's domain can be
13423 individually set by the object's initializer. */
13425 if (type && typedef_type
13426 && TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type)
13427 && TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (typedef_type))
13428 type = build_cplus_array_type (TREE_TYPE (type), NULL_TREE);
13430 /* Detect where we're using a typedef of function type to declare a
13431 function. PARMS will not be set, so we must create it now. */
13433 if (type == typedef_type && TREE_CODE (type) == FUNCTION_TYPE)
13435 tree decls = NULL_TREE;
13436 tree args;
13438 for (args = TYPE_ARG_TYPES (type);
13439 args && args != void_list_node;
13440 args = TREE_CHAIN (args))
13442 tree decl = cp_build_parm_decl (NULL_TREE, NULL_TREE,
13443 TREE_VALUE (args));
13445 DECL_CHAIN (decl) = decls;
13446 decls = decl;
13449 parms = nreverse (decls);
13451 if (decl_context != TYPENAME)
13453 /* The qualifiers on the function type become the qualifiers on
13454 the non-static member function. */
13455 memfn_quals |= type_memfn_quals (type);
13456 rqual = type_memfn_rqual (type);
13457 type_quals = TYPE_UNQUALIFIED;
13458 raises = TYPE_RAISES_EXCEPTIONS (type);
13462 /* If this is a type name (such as, in a cast or sizeof),
13463 compute the type and return it now. */
13465 if (decl_context == TYPENAME)
13467 /* Note that here we don't care about type_quals. */
13469 /* Special case: "friend class foo" looks like a TYPENAME context. */
13470 if (friendp)
13472 if (inlinep)
13474 error ("%<inline%> specified for friend class declaration");
13475 inlinep = 0;
13478 if (!current_aggr)
13480 /* Don't allow friend declaration without a class-key. */
13481 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
13482 permerror (input_location, "template parameters cannot be friends");
13483 else if (TREE_CODE (type) == TYPENAME_TYPE)
13484 permerror (input_location, "friend declaration requires class-key, "
13485 "i.e. %<friend class %T::%D%>",
13486 TYPE_CONTEXT (type), TYPENAME_TYPE_FULLNAME (type));
13487 else
13488 permerror (input_location, "friend declaration requires class-key, "
13489 "i.e. %<friend %#T%>",
13490 type);
13493 /* Only try to do this stuff if we didn't already give up. */
13494 if (type != integer_type_node)
13496 /* A friendly class? */
13497 if (current_class_type)
13498 make_friend_class (current_class_type, TYPE_MAIN_VARIANT (type),
13499 /*complain=*/true);
13500 else
13501 error ("trying to make class %qT a friend of global scope",
13502 type);
13504 type = void_type_node;
13507 else if (memfn_quals || rqual)
13509 if (ctype == NULL_TREE
13510 && TREE_CODE (type) == METHOD_TYPE)
13511 ctype = TYPE_METHOD_BASETYPE (type);
13513 if (ctype)
13514 type = build_memfn_type (type, ctype, memfn_quals, rqual);
13515 /* Core issue #547: need to allow this in template type args.
13516 Allow it in general in C++11 for alias-declarations. */
13517 else if ((template_type_arg || cxx_dialect >= cxx11)
13518 && TREE_CODE (type) == FUNCTION_TYPE)
13519 type = apply_memfn_quals (type, memfn_quals, rqual);
13520 else
13521 error ("invalid qualifiers on non-member function type");
13524 if (reqs)
13525 error_at (location_of (reqs), "requires-clause on type-id");
13527 return type;
13529 else if (unqualified_id == NULL_TREE && decl_context != PARM
13530 && decl_context != CATCHPARM
13531 && TREE_CODE (type) != UNION_TYPE
13532 && ! bitfield
13533 && innermost_code != cdk_decomp)
13535 error ("abstract declarator %qT used as declaration", type);
13536 return error_mark_node;
13539 if (!FUNC_OR_METHOD_TYPE_P (type))
13541 /* Only functions may be declared using an operator-function-id. */
13542 if (dname && IDENTIFIER_ANY_OP_P (dname))
13544 error_at (id_loc, "declaration of %qD as non-function", dname);
13545 return error_mark_node;
13548 if (reqs)
13549 error_at (location_of (reqs),
13550 "requires-clause on declaration of non-function type %qT",
13551 type);
13554 /* We don't check parameter types here because we can emit a better
13555 error message later. */
13556 if (decl_context != PARM)
13558 type = check_var_type (unqualified_id, type, id_loc);
13559 if (type == error_mark_node)
13560 return error_mark_node;
13563 /* Now create the decl, which may be a VAR_DECL, a PARM_DECL
13564 or a FUNCTION_DECL, depending on DECL_CONTEXT and TYPE. */
13566 if (decl_context == PARM || decl_context == CATCHPARM)
13568 if (ctype || in_namespace)
13569 error ("cannot use %<::%> in parameter declaration");
13571 tree auto_node = type_uses_auto (type);
13572 if (auto_node && !(cxx_dialect >= cxx17 && template_parm_flag))
13574 if (cxx_dialect >= cxx14)
13576 if (decl_context == PARM && AUTO_IS_DECLTYPE (auto_node))
13577 error_at (typespec_loc,
13578 "cannot declare a parameter with %<decltype(auto)%>");
13579 else if (tree c = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
13581 auto_diagnostic_group g;
13582 error_at (typespec_loc,
13583 "class template placeholder %qE not permitted "
13584 "in this context", c);
13585 if (decl_context == PARM && cxx_dialect >= cxx20)
13586 inform (typespec_loc, "use %<auto%> for an "
13587 "abbreviated function template");
13589 else
13590 error_at (typespec_loc,
13591 "%<auto%> parameter not permitted in this context");
13593 else
13594 error_at (typespec_loc, "parameter declared %<auto%>");
13595 type = error_mark_node;
13598 /* A parameter declared as an array of T is really a pointer to T.
13599 One declared as a function is really a pointer to a function.
13600 One declared as a member is really a pointer to member. */
13602 if (TREE_CODE (type) == ARRAY_TYPE)
13604 /* Transfer const-ness of array into that of type pointed to. */
13605 type = build_pointer_type (TREE_TYPE (type));
13606 type_quals = TYPE_UNQUALIFIED;
13607 array_parameter_p = true;
13609 else if (TREE_CODE (type) == FUNCTION_TYPE)
13610 type = build_pointer_type (type);
13613 if (ctype && TREE_CODE (type) == FUNCTION_TYPE && staticp < 2
13614 && !(unqualified_id
13615 && identifier_p (unqualified_id)
13616 && IDENTIFIER_NEWDEL_OP_P (unqualified_id)))
13618 cp_cv_quals real_quals = memfn_quals;
13619 if (cxx_dialect < cxx14 && constexpr_p
13620 && sfk != sfk_constructor && sfk != sfk_destructor)
13621 real_quals |= TYPE_QUAL_CONST;
13622 type = build_memfn_type (type, ctype, real_quals, rqual);
13626 tree decl = NULL_TREE;
13628 if (decl_context == PARM)
13630 decl = cp_build_parm_decl (NULL_TREE, unqualified_id, type);
13631 DECL_ARRAY_PARAMETER_P (decl) = array_parameter_p;
13633 bad_specifiers (decl, BSP_PARM, virtualp,
13634 memfn_quals != TYPE_UNQUALIFIED,
13635 inlinep, friendp, raises != NULL_TREE,
13636 declspecs->locations);
13638 else if (decl_context == FIELD)
13640 if (!staticp && !friendp && TREE_CODE (type) != METHOD_TYPE)
13641 if (tree auto_node = type_uses_auto (type))
13643 location_t tloc = declspecs->locations[ds_type_spec];
13644 if (CLASS_PLACEHOLDER_TEMPLATE (auto_node))
13645 error_at (tloc, "invalid use of template-name %qE without an "
13646 "argument list",
13647 CLASS_PLACEHOLDER_TEMPLATE (auto_node));
13648 else
13649 error_at (tloc, "non-static data member declared with "
13650 "placeholder %qT", auto_node);
13651 type = error_mark_node;
13654 /* The C99 flexible array extension. */
13655 if (!staticp && TREE_CODE (type) == ARRAY_TYPE
13656 && TYPE_DOMAIN (type) == NULL_TREE)
13658 if (ctype
13659 && (TREE_CODE (ctype) == UNION_TYPE
13660 || TREE_CODE (ctype) == QUAL_UNION_TYPE))
13662 error_at (id_loc, "flexible array member in union");
13663 type = error_mark_node;
13665 else
13667 /* Array is a flexible member. */
13668 if (name)
13669 pedwarn (id_loc, OPT_Wpedantic,
13670 "ISO C++ forbids flexible array member %qs", name);
13671 else
13672 pedwarn (input_location, OPT_Wpedantic,
13673 "ISO C++ forbids flexible array members");
13675 /* Flexible array member has a null domain. */
13676 type = build_cplus_array_type (TREE_TYPE (type), NULL_TREE);
13680 if (type == error_mark_node)
13682 /* Happens when declaring arrays of sizes which
13683 are error_mark_node, for example. */
13684 decl = NULL_TREE;
13686 else if (in_namespace && !friendp)
13688 /* Something like struct S { int N::j; }; */
13689 error_at (id_loc, "invalid use of %<::%>");
13690 return error_mark_node;
13692 else if (FUNC_OR_METHOD_TYPE_P (type) && unqualified_id)
13694 int publicp = 0;
13695 tree function_context;
13697 if (friendp == 0)
13699 /* This should never happen in pure C++ (the check
13700 could be an assert). It could happen in
13701 Objective-C++ if someone writes invalid code that
13702 uses a function declaration for an instance
13703 variable or property (instance variables and
13704 properties are parsed as FIELD_DECLs, but they are
13705 part of an Objective-C class, not a C++ class).
13706 That code is invalid and is caught by this
13707 check. */
13708 if (!ctype)
13710 error ("declaration of function %qD in invalid context",
13711 unqualified_id);
13712 return error_mark_node;
13715 /* ``A union may [ ... ] not [ have ] virtual functions.''
13716 ARM 9.5 */
13717 if (virtualp && TREE_CODE (ctype) == UNION_TYPE)
13719 error_at (declspecs->locations[ds_virtual],
13720 "function %qD declared %<virtual%> inside a union",
13721 unqualified_id);
13722 return error_mark_node;
13725 if (virtualp
13726 && identifier_p (unqualified_id)
13727 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
13729 error_at (declspecs->locations[ds_virtual],
13730 "%qD cannot be declared %<virtual%>, since it "
13731 "is always static", unqualified_id);
13732 virtualp = 0;
13736 /* Check that the name used for a destructor makes sense. */
13737 if (sfk == sfk_destructor)
13739 tree uqname = id_declarator->u.id.unqualified_name;
13741 if (!ctype)
13743 gcc_assert (friendp);
13744 error_at (id_loc, "expected qualified name in friend "
13745 "declaration for destructor %qD", uqname);
13746 return error_mark_node;
13749 if (!check_dtor_name (ctype, TREE_OPERAND (uqname, 0)))
13751 error_at (id_loc, "declaration of %qD as member of %qT",
13752 uqname, ctype);
13753 return error_mark_node;
13755 if (concept_p)
13757 error_at (declspecs->locations[ds_concept],
13758 "a destructor cannot be %qs", "concept");
13759 return error_mark_node;
13761 if (constexpr_p && cxx_dialect < cxx20)
13763 error_at (declspecs->locations[ds_constexpr],
13764 "%<constexpr%> destructors only available"
13765 " with %<-std=c++20%> or %<-std=gnu++20%>");
13766 return error_mark_node;
13768 if (consteval_p)
13770 error_at (declspecs->locations[ds_consteval],
13771 "a destructor cannot be %qs", "consteval");
13772 return error_mark_node;
13775 else if (sfk == sfk_constructor && friendp && !ctype)
13777 error ("expected qualified name in friend declaration "
13778 "for constructor %qD",
13779 id_declarator->u.id.unqualified_name);
13780 return error_mark_node;
13782 if (sfk == sfk_constructor)
13783 if (concept_p)
13785 error_at (declspecs->locations[ds_concept],
13786 "a constructor cannot be %<concept%>");
13787 return error_mark_node;
13789 if (concept_p)
13791 error_at (declspecs->locations[ds_concept],
13792 "a concept cannot be a member function");
13793 concept_p = false;
13795 else if (consteval_p
13796 && identifier_p (unqualified_id)
13797 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
13799 error_at (declspecs->locations[ds_consteval],
13800 "%qD cannot be %qs", unqualified_id, "consteval");
13801 consteval_p = false;
13804 if (TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
13806 tree tmpl = TREE_OPERAND (unqualified_id, 0);
13807 if (variable_template_p (tmpl))
13809 error_at (id_loc, "specialization of variable template "
13810 "%qD declared as function", tmpl);
13811 inform (DECL_SOURCE_LOCATION (tmpl),
13812 "variable template declared here");
13813 return error_mark_node;
13817 /* Tell grokfndecl if it needs to set TREE_PUBLIC on the node. */
13818 function_context
13819 = (ctype != NULL_TREE
13820 ? decl_function_context (TYPE_MAIN_DECL (ctype)) : NULL_TREE);
13821 publicp = ((! friendp || ! staticp)
13822 && function_context == NULL_TREE);
13824 decl = grokfndecl (ctype, type,
13825 TREE_CODE (unqualified_id) != TEMPLATE_ID_EXPR
13826 ? unqualified_id : dname,
13827 parms,
13828 unqualified_id,
13829 declspecs,
13830 reqs,
13831 virtualp, flags, memfn_quals, rqual, raises,
13832 friendp ? -1 : 0, friendp, publicp,
13833 inlinep | (2 * constexpr_p) | (4 * concept_p)
13834 | (8 * consteval_p),
13835 initialized == SD_DELETED, sfk,
13836 funcdef_flag, late_return_type_p,
13837 template_count, in_namespace,
13838 attrlist, id_loc);
13839 decl = set_virt_specifiers (decl, virt_specifiers);
13840 if (decl == NULL_TREE)
13841 return error_mark_node;
13842 #if 0
13843 /* This clobbers the attrs stored in `decl' from `attrlist'. */
13844 /* The decl and setting of decl_attr is also turned off. */
13845 decl = build_decl_attribute_variant (decl, decl_attr);
13846 #endif
13848 /* [class.conv.ctor]
13850 A constructor declared without the function-specifier
13851 explicit that can be called with a single parameter
13852 specifies a conversion from the type of its first
13853 parameter to the type of its class. Such a constructor
13854 is called a converting constructor. */
13855 if (explicitp == 2)
13856 DECL_NONCONVERTING_P (decl) = 1;
13858 if (declspecs->explicit_specifier)
13859 store_explicit_specifier (decl, declspecs->explicit_specifier);
13861 else if (!staticp
13862 && ((current_class_type
13863 && same_type_p (type, current_class_type))
13864 || (!dependent_type_p (type)
13865 && !COMPLETE_TYPE_P (complete_type (type))
13866 && (!complete_or_array_type_p (type)
13867 || initialized == SD_UNINITIALIZED))))
13869 if (TREE_CODE (type) != ARRAY_TYPE
13870 || !COMPLETE_TYPE_P (TREE_TYPE (type)))
13872 if (unqualified_id)
13874 error_at (id_loc, "field %qD has incomplete type %qT",
13875 unqualified_id, type);
13876 cxx_incomplete_type_inform (strip_array_types (type));
13878 else
13879 error ("name %qT has incomplete type", type);
13881 type = error_mark_node;
13882 decl = NULL_TREE;
13885 else if (!verify_type_context (input_location,
13886 staticp
13887 ? TCTX_STATIC_STORAGE
13888 : TCTX_FIELD, type))
13890 type = error_mark_node;
13891 decl = NULL_TREE;
13893 else
13895 if (friendp)
13897 if (unqualified_id)
13898 error_at (id_loc,
13899 "%qE is neither function nor member function; "
13900 "cannot be declared friend", unqualified_id);
13901 else
13902 error ("unnamed field is neither function nor member "
13903 "function; cannot be declared friend");
13904 return error_mark_node;
13906 decl = NULL_TREE;
13909 if (friendp)
13911 /* Packages tend to use GNU attributes on friends, so we only
13912 warn for standard attributes. */
13913 if (attrlist && !funcdef_flag && cxx11_attribute_p (*attrlist))
13915 *attrlist = NULL_TREE;
13916 if (warning_at (id_loc, OPT_Wattributes, "attribute ignored"))
13917 inform (id_loc, "an attribute that appertains to a friend "
13918 "declaration that is not a definition is ignored");
13920 /* Friends are treated specially. */
13921 if (ctype == current_class_type)
13922 ; /* We already issued a permerror. */
13923 else if (decl && DECL_NAME (decl))
13925 set_originating_module (decl, true);
13927 if (initialized)
13928 /* Kludge: We need funcdef_flag to be true in do_friend for
13929 in-class defaulted functions, but that breaks grokfndecl.
13930 So set it here. */
13931 funcdef_flag = true;
13933 if (template_class_depth (current_class_type) == 0)
13935 decl = check_explicit_specialization
13936 (unqualified_id, decl, template_count,
13937 2 * funcdef_flag + 4);
13938 if (decl == error_mark_node)
13939 return error_mark_node;
13942 decl = do_friend (ctype, unqualified_id, decl,
13943 flags, funcdef_flag);
13944 return decl;
13946 else
13947 return error_mark_node;
13950 /* Structure field. It may not be a function, except for C++. */
13952 if (decl == NULL_TREE)
13954 if (staticp)
13956 /* C++ allows static class members. All other work
13957 for this is done by grokfield. */
13958 decl = build_lang_decl_loc (id_loc, VAR_DECL,
13959 unqualified_id, type);
13960 set_linkage_for_static_data_member (decl);
13961 if (concept_p)
13962 error_at (declspecs->locations[ds_concept],
13963 "static data member %qE declared %qs",
13964 unqualified_id, "concept");
13965 else if (constexpr_p && !initialized)
13967 error_at (DECL_SOURCE_LOCATION (decl),
13968 "%<constexpr%> static data member %qD must "
13969 "have an initializer", decl);
13970 constexpr_p = false;
13972 if (consteval_p)
13973 error_at (declspecs->locations[ds_consteval],
13974 "static data member %qE declared %qs",
13975 unqualified_id, "consteval");
13977 if (inlinep)
13978 mark_inline_variable (decl, declspecs->locations[ds_inline]);
13980 if (!DECL_VAR_DECLARED_INLINE_P (decl)
13981 && !(cxx_dialect >= cxx17 && constexpr_p))
13982 /* Even if there is an in-class initialization, DECL
13983 is considered undefined until an out-of-class
13984 definition is provided, unless this is an inline
13985 variable. */
13986 DECL_EXTERNAL (decl) = 1;
13988 if (thread_p)
13990 CP_DECL_THREAD_LOCAL_P (decl) = true;
13991 if (!processing_template_decl)
13992 set_decl_tls_model (decl, decl_default_tls_model (decl));
13993 if (declspecs->gnu_thread_keyword_p)
13994 SET_DECL_GNU_TLS_P (decl);
13997 /* Set the constraints on the declaration. */
13998 bool memtmpl = (current_template_depth
13999 > template_class_depth (current_class_type));
14000 if (memtmpl)
14002 tree tmpl_reqs
14003 = TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
14004 tree ci = build_constraints (tmpl_reqs, NULL_TREE);
14005 set_constraints (decl, ci);
14008 else
14010 if (concept_p)
14012 error_at (declspecs->locations[ds_concept],
14013 "non-static data member %qE declared %qs",
14014 unqualified_id, "concept");
14015 concept_p = false;
14016 constexpr_p = false;
14018 else if (constexpr_p)
14020 error_at (declspecs->locations[ds_constexpr],
14021 "non-static data member %qE declared %qs",
14022 unqualified_id, "constexpr");
14023 constexpr_p = false;
14025 if (constinit_p)
14027 error_at (declspecs->locations[ds_constinit],
14028 "non-static data member %qE declared %qs",
14029 unqualified_id, "constinit");
14030 constinit_p = false;
14032 if (consteval_p)
14034 error_at (declspecs->locations[ds_consteval],
14035 "non-static data member %qE declared %qs",
14036 unqualified_id, "consteval");
14037 consteval_p = false;
14039 decl = build_decl (id_loc, FIELD_DECL, unqualified_id, type);
14040 DECL_NONADDRESSABLE_P (decl) = bitfield;
14041 if (bitfield && !unqualified_id)
14042 DECL_PADDING_P (decl) = 1;
14044 if (storage_class == sc_mutable)
14046 DECL_MUTABLE_P (decl) = 1;
14047 storage_class = sc_none;
14050 if (initialized)
14052 /* An attempt is being made to initialize a non-static
14053 member. This is new in C++11. */
14054 maybe_warn_cpp0x (CPP0X_NSDMI, init_loc);
14056 /* If this has been parsed with static storage class, but
14057 errors forced staticp to be cleared, ensure NSDMI is
14058 not present. */
14059 if (declspecs->storage_class == sc_static)
14060 DECL_INITIAL (decl) = error_mark_node;
14064 bad_specifiers (decl, BSP_FIELD, virtualp,
14065 memfn_quals != TYPE_UNQUALIFIED,
14066 staticp ? false : inlinep, friendp,
14067 raises != NULL_TREE,
14068 declspecs->locations);
14071 else if (FUNC_OR_METHOD_TYPE_P (type))
14073 tree original_name;
14074 int publicp = 0;
14076 if (!unqualified_id)
14077 return error_mark_node;
14079 if (TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
14080 original_name = dname;
14081 else
14082 original_name = unqualified_id;
14083 // FIXME:gcc_assert (original_name == dname);
14085 if (storage_class == sc_auto)
14086 error_at (declspecs->locations[ds_storage_class],
14087 "storage class %<auto%> invalid for function %qs", name);
14088 else if (storage_class == sc_register)
14089 error_at (declspecs->locations[ds_storage_class],
14090 "storage class %<register%> invalid for function %qs",
14091 name);
14092 else if (thread_p)
14094 if (declspecs->gnu_thread_keyword_p)
14095 error_at (declspecs->locations[ds_thread],
14096 "storage class %<__thread%> invalid for function %qs",
14097 name);
14098 else
14099 error_at (declspecs->locations[ds_thread],
14100 "storage class %<thread_local%> invalid for "
14101 "function %qs", name);
14104 if (virt_specifiers)
14105 error ("virt-specifiers in %qs not allowed outside a class "
14106 "definition", name);
14107 /* Function declaration not at top level.
14108 Storage classes other than `extern' are not allowed
14109 and `extern' makes no difference. */
14110 if (! toplevel_bindings_p ()
14111 && (storage_class == sc_static
14112 || decl_spec_seq_has_spec_p (declspecs, ds_inline))
14113 && pedantic)
14115 if (storage_class == sc_static)
14116 pedwarn (declspecs->locations[ds_storage_class], OPT_Wpedantic,
14117 "%<static%> specifier invalid for function %qs "
14118 "declared out of global scope", name);
14119 else
14120 pedwarn (declspecs->locations[ds_inline], OPT_Wpedantic,
14121 "%<inline%> specifier invalid for function %qs "
14122 "declared out of global scope", name);
14125 if (ctype == NULL_TREE)
14127 if (virtualp)
14129 error ("virtual non-class function %qs", name);
14130 virtualp = 0;
14132 else if (sfk == sfk_constructor
14133 || sfk == sfk_destructor)
14135 error (funcdef_flag
14136 ? G_("%qs defined in a non-class scope")
14137 : G_("%qs declared in a non-class scope"), name);
14138 sfk = sfk_none;
14141 if (consteval_p
14142 && identifier_p (unqualified_id)
14143 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
14145 error_at (declspecs->locations[ds_consteval],
14146 "%qD cannot be %qs", unqualified_id, "consteval");
14147 consteval_p = false;
14150 /* Record whether the function is public. */
14151 publicp = (ctype != NULL_TREE
14152 || storage_class != sc_static);
14154 decl = grokfndecl (ctype, type, original_name, parms, unqualified_id,
14155 declspecs,
14156 reqs, virtualp, flags, memfn_quals, rqual, raises,
14157 1, friendp,
14158 publicp,
14159 inlinep | (2 * constexpr_p) | (4 * concept_p)
14160 | (8 * consteval_p),
14161 initialized == SD_DELETED,
14162 sfk,
14163 funcdef_flag,
14164 late_return_type_p,
14165 template_count, in_namespace, attrlist,
14166 id_loc);
14167 if (decl == NULL_TREE)
14168 return error_mark_node;
14170 if (explicitp == 2)
14171 DECL_NONCONVERTING_P (decl) = 1;
14172 if (staticp == 1)
14174 int invalid_static = 0;
14176 /* Don't allow a static member function in a class, and forbid
14177 declaring main to be static. */
14178 if (TREE_CODE (type) == METHOD_TYPE)
14180 permerror (input_location, "cannot declare member function %qD to have "
14181 "static linkage", decl);
14182 invalid_static = 1;
14184 else if (current_function_decl)
14186 /* 7.1.1: There can be no static function declarations within a
14187 block. */
14188 error_at (declspecs->locations[ds_storage_class],
14189 "cannot declare static function inside another function");
14190 invalid_static = 1;
14193 if (invalid_static)
14195 staticp = 0;
14196 storage_class = sc_none;
14199 if (declspecs->explicit_specifier)
14200 store_explicit_specifier (decl, declspecs->explicit_specifier);
14202 else
14204 /* It's a variable. */
14206 /* An uninitialized decl with `extern' is a reference. */
14207 decl = grokvardecl (type, dname, unqualified_id,
14208 declspecs,
14209 initialized,
14210 type_quals,
14211 inlinep,
14212 concept_p,
14213 template_count,
14214 ctype ? ctype : in_namespace,
14215 id_loc);
14216 if (decl == NULL_TREE)
14217 return error_mark_node;
14219 bad_specifiers (decl, BSP_VAR, virtualp,
14220 memfn_quals != TYPE_UNQUALIFIED,
14221 inlinep, friendp, raises != NULL_TREE,
14222 declspecs->locations);
14224 if (ctype)
14226 DECL_CONTEXT (decl) = ctype;
14227 if (staticp == 1)
14229 permerror (declspecs->locations[ds_storage_class],
14230 "%<static%> may not be used when defining "
14231 "(as opposed to declaring) a static data member");
14232 staticp = 0;
14233 storage_class = sc_none;
14235 if (storage_class == sc_register && TREE_STATIC (decl))
14237 error ("static member %qD declared %<register%>", decl);
14238 storage_class = sc_none;
14240 if (storage_class == sc_extern && pedantic)
14242 pedwarn (input_location, OPT_Wpedantic,
14243 "cannot explicitly declare member %q#D to have "
14244 "extern linkage", decl);
14245 storage_class = sc_none;
14248 else if (constexpr_p && DECL_EXTERNAL (decl))
14250 error_at (DECL_SOURCE_LOCATION (decl),
14251 "declaration of %<constexpr%> variable %qD "
14252 "is not a definition", decl);
14253 constexpr_p = false;
14255 if (consteval_p)
14257 error_at (DECL_SOURCE_LOCATION (decl),
14258 "a variable cannot be declared %<consteval%>");
14259 consteval_p = false;
14262 if (inlinep)
14263 mark_inline_variable (decl, declspecs->locations[ds_inline]);
14264 if (innermost_code == cdk_decomp)
14266 gcc_assert (declarator && declarator->kind == cdk_decomp);
14267 DECL_SOURCE_LOCATION (decl) = id_loc;
14268 DECL_ARTIFICIAL (decl) = 1;
14269 fit_decomposition_lang_decl (decl, NULL_TREE);
14273 if (VAR_P (decl) && !initialized)
14274 if (tree auto_node = type_uses_auto (type))
14275 if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
14277 location_t loc = declspecs->locations[ds_type_spec];
14278 error_at (loc, "declaration of %q#D has no initializer", decl);
14279 TREE_TYPE (decl) = error_mark_node;
14282 if (storage_class == sc_extern && initialized && !funcdef_flag)
14284 if (toplevel_bindings_p ())
14286 /* It's common practice (and completely valid) to have a const
14287 be initialized and declared extern. */
14288 if (!(type_quals & TYPE_QUAL_CONST))
14289 warning_at (DECL_SOURCE_LOCATION (decl), 0,
14290 "%qs initialized and declared %<extern%>", name);
14292 else
14294 error_at (DECL_SOURCE_LOCATION (decl),
14295 "%qs has both %<extern%> and initializer", name);
14296 return error_mark_node;
14300 /* Record `register' declaration for warnings on &
14301 and in case doing stupid register allocation. */
14303 if (storage_class == sc_register)
14305 DECL_REGISTER (decl) = 1;
14306 /* Warn about register storage specifiers on PARM_DECLs. */
14307 if (TREE_CODE (decl) == PARM_DECL)
14309 if (cxx_dialect >= cxx17)
14310 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
14311 "ISO C++17 does not allow %<register%> storage "
14312 "class specifier");
14313 else
14314 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
14315 "%<register%> storage class specifier used");
14318 else if (storage_class == sc_extern)
14319 DECL_THIS_EXTERN (decl) = 1;
14320 else if (storage_class == sc_static)
14321 DECL_THIS_STATIC (decl) = 1;
14323 if (VAR_P (decl))
14325 /* Set constexpr flag on vars (functions got it in grokfndecl). */
14326 if (constexpr_p)
14327 DECL_DECLARED_CONSTEXPR_P (decl) = true;
14328 /* And the constinit flag (which only applies to variables). */
14329 else if (constinit_p)
14330 DECL_DECLARED_CONSTINIT_P (decl) = true;
14333 /* Record constancy and volatility on the DECL itself . There's
14334 no need to do this when processing a template; we'll do this
14335 for the instantiated declaration based on the type of DECL. */
14336 if (!processing_template_decl)
14337 cp_apply_type_quals_to_decl (type_quals, decl);
14339 return decl;
14343 /* Subroutine of start_function. Ensure that each of the parameter
14344 types (as listed in PARMS) is complete, as is required for a
14345 function definition. */
14347 static void
14348 require_complete_types_for_parms (tree parms)
14350 for (; parms; parms = DECL_CHAIN (parms))
14352 if (dependent_type_p (TREE_TYPE (parms)))
14353 continue;
14354 if (!VOID_TYPE_P (TREE_TYPE (parms))
14355 && complete_type_or_else (TREE_TYPE (parms), parms))
14357 relayout_decl (parms);
14358 DECL_ARG_TYPE (parms) = type_passed_as (TREE_TYPE (parms));
14360 abstract_virtuals_error (parms, TREE_TYPE (parms));
14361 maybe_warn_parm_abi (TREE_TYPE (parms),
14362 DECL_SOURCE_LOCATION (parms));
14364 else
14365 /* grokparms or complete_type_or_else will have already issued
14366 an error. */
14367 TREE_TYPE (parms) = error_mark_node;
14371 /* Returns nonzero if T is a local variable. */
14374 local_variable_p (const_tree t)
14376 if ((VAR_P (t)
14377 && (DECL_LOCAL_DECL_P (t)
14378 || !DECL_CONTEXT (t)
14379 || TREE_CODE (DECL_CONTEXT (t)) == FUNCTION_DECL))
14380 || (TREE_CODE (t) == PARM_DECL))
14381 return 1;
14383 return 0;
14386 /* Like local_variable_p, but suitable for use as a tree-walking
14387 function. */
14389 static tree
14390 local_variable_p_walkfn (tree *tp, int *walk_subtrees,
14391 void * /*data*/)
14393 if (unevaluated_p (TREE_CODE (*tp)))
14395 /* DR 2082 permits local variables in unevaluated contexts
14396 within a default argument. */
14397 *walk_subtrees = 0;
14398 return NULL_TREE;
14401 if (local_variable_p (*tp)
14402 && (!DECL_ARTIFICIAL (*tp) || DECL_NAME (*tp) == this_identifier))
14403 return *tp;
14404 else if (TYPE_P (*tp))
14405 *walk_subtrees = 0;
14407 return NULL_TREE;
14410 /* Check that ARG, which is a default-argument expression for a
14411 parameter DECL, is valid. Returns ARG, or ERROR_MARK_NODE, if
14412 something goes wrong. DECL may also be a _TYPE node, rather than a
14413 DECL, if there is no DECL available. */
14415 tree
14416 check_default_argument (tree decl, tree arg, tsubst_flags_t complain)
14418 tree var;
14419 tree decl_type;
14421 if (TREE_CODE (arg) == DEFERRED_PARSE)
14422 /* We get a DEFERRED_PARSE when looking at an in-class declaration
14423 with a default argument. Ignore the argument for now; we'll
14424 deal with it after the class is complete. */
14425 return arg;
14427 if (TYPE_P (decl))
14429 decl_type = decl;
14430 decl = NULL_TREE;
14432 else
14433 decl_type = TREE_TYPE (decl);
14435 if (arg == error_mark_node
14436 || decl == error_mark_node
14437 || TREE_TYPE (arg) == error_mark_node
14438 || decl_type == error_mark_node)
14439 /* Something already went wrong. There's no need to check
14440 further. */
14441 return error_mark_node;
14443 /* [dcl.fct.default]
14445 A default argument expression is implicitly converted to the
14446 parameter type. */
14447 ++cp_unevaluated_operand;
14448 /* Avoid digest_init clobbering the initializer. */
14449 tree carg = BRACE_ENCLOSED_INITIALIZER_P (arg) ? unshare_expr (arg): arg;
14450 perform_implicit_conversion_flags (decl_type, carg, complain,
14451 LOOKUP_IMPLICIT);
14452 --cp_unevaluated_operand;
14454 /* Avoid redundant -Wzero-as-null-pointer-constant warnings at
14455 the call sites. */
14456 if (TYPE_PTR_OR_PTRMEM_P (decl_type)
14457 && null_ptr_cst_p (arg)
14458 /* Don't lose side-effects as in PR90473. */
14459 && !TREE_SIDE_EFFECTS (arg))
14460 return nullptr_node;
14462 /* [dcl.fct.default]
14464 Local variables shall not be used in default argument
14465 expressions.
14467 The keyword `this' shall not be used in a default argument of a
14468 member function. */
14469 var = cp_walk_tree_without_duplicates (&arg, local_variable_p_walkfn, NULL);
14470 if (var)
14472 if (complain & tf_warning_or_error)
14474 if (DECL_NAME (var) == this_identifier)
14475 permerror (input_location, "default argument %qE uses %qD",
14476 arg, var);
14477 else
14478 error ("default argument %qE uses local variable %qD", arg, var);
14480 return error_mark_node;
14483 /* All is well. */
14484 return arg;
14487 /* Returns a deprecated type used within TYPE, or NULL_TREE if none. */
14489 static tree
14490 type_is_deprecated (tree type)
14492 enum tree_code code;
14493 if (TREE_DEPRECATED (type))
14494 return type;
14495 if (TYPE_NAME (type))
14497 if (TREE_DEPRECATED (TYPE_NAME (type)))
14498 return type;
14499 else
14501 cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (TYPE_NAME (type)));
14502 return NULL_TREE;
14506 /* Do warn about using typedefs to a deprecated class. */
14507 if (OVERLOAD_TYPE_P (type) && type != TYPE_MAIN_VARIANT (type))
14508 return type_is_deprecated (TYPE_MAIN_VARIANT (type));
14510 code = TREE_CODE (type);
14512 if (code == POINTER_TYPE || code == REFERENCE_TYPE
14513 || code == OFFSET_TYPE || code == FUNCTION_TYPE
14514 || code == METHOD_TYPE || code == ARRAY_TYPE)
14515 return type_is_deprecated (TREE_TYPE (type));
14517 if (TYPE_PTRMEMFUNC_P (type))
14518 return type_is_deprecated
14519 (TREE_TYPE (TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (type))));
14521 return NULL_TREE;
14524 /* Returns an unavailable type used within TYPE, or NULL_TREE if none. */
14526 static tree
14527 type_is_unavailable (tree type)
14529 enum tree_code code;
14530 if (TREE_UNAVAILABLE (type))
14531 return type;
14532 if (TYPE_NAME (type))
14534 if (TREE_UNAVAILABLE (TYPE_NAME (type)))
14535 return type;
14536 else
14538 cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (TYPE_NAME (type)));
14539 return NULL_TREE;
14543 /* Do warn about using typedefs to a deprecated class. */
14544 if (OVERLOAD_TYPE_P (type) && type != TYPE_MAIN_VARIANT (type))
14545 return type_is_deprecated (TYPE_MAIN_VARIANT (type));
14547 code = TREE_CODE (type);
14549 if (code == POINTER_TYPE || code == REFERENCE_TYPE
14550 || code == OFFSET_TYPE || code == FUNCTION_TYPE
14551 || code == METHOD_TYPE || code == ARRAY_TYPE)
14552 return type_is_unavailable (TREE_TYPE (type));
14554 if (TYPE_PTRMEMFUNC_P (type))
14555 return type_is_unavailable
14556 (TREE_TYPE (TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (type))));
14558 return NULL_TREE;
14561 /* Decode the list of parameter types for a function type.
14562 Given the list of things declared inside the parens,
14563 return a list of types.
14565 If this parameter does not end with an ellipsis, we append
14566 void_list_node.
14568 *PARMS is set to the chain of PARM_DECLs created. */
14570 tree
14571 grokparms (tree parmlist, tree *parms)
14573 tree result = NULL_TREE;
14574 tree decls = NULL_TREE;
14575 tree parm;
14576 int any_error = 0;
14578 for (parm = parmlist; parm != NULL_TREE; parm = TREE_CHAIN (parm))
14580 tree type = NULL_TREE;
14581 tree init = TREE_PURPOSE (parm);
14582 tree decl = TREE_VALUE (parm);
14584 if (parm == void_list_node || parm == explicit_void_list_node)
14585 break;
14587 if (! decl || TREE_TYPE (decl) == error_mark_node)
14589 any_error = 1;
14590 continue;
14593 type = TREE_TYPE (decl);
14594 if (VOID_TYPE_P (type))
14596 if (same_type_p (type, void_type_node)
14597 && !init
14598 && !DECL_NAME (decl) && !result
14599 && TREE_CHAIN (parm) == void_list_node)
14600 /* DR 577: A parameter list consisting of a single
14601 unnamed parameter of non-dependent type 'void'. */
14602 break;
14603 else if (cv_qualified_p (type))
14604 error_at (DECL_SOURCE_LOCATION (decl),
14605 "invalid use of cv-qualified type %qT in "
14606 "parameter declaration", type);
14607 else
14608 error_at (DECL_SOURCE_LOCATION (decl),
14609 "invalid use of type %<void%> in parameter "
14610 "declaration");
14611 /* It's not a good idea to actually create parameters of
14612 type `void'; other parts of the compiler assume that a
14613 void type terminates the parameter list. */
14614 type = error_mark_node;
14615 TREE_TYPE (decl) = error_mark_node;
14618 if (type != error_mark_node)
14620 if (deprecated_state != UNAVAILABLE_DEPRECATED_SUPPRESS)
14622 tree unavailtype = type_is_unavailable (type);
14623 if (unavailtype)
14624 cp_handle_deprecated_or_unavailable (unavailtype);
14626 if (deprecated_state != DEPRECATED_SUPPRESS
14627 && deprecated_state != UNAVAILABLE_DEPRECATED_SUPPRESS)
14629 tree deptype = type_is_deprecated (type);
14630 if (deptype)
14631 cp_handle_deprecated_or_unavailable (deptype);
14634 /* [dcl.fct] "A parameter with volatile-qualified type is
14635 deprecated." */
14636 if (CP_TYPE_VOLATILE_P (type))
14637 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wvolatile,
14638 "%<volatile%>-qualified parameter is "
14639 "deprecated");
14641 /* Top-level qualifiers on the parameters are
14642 ignored for function types. */
14643 type = cp_build_qualified_type (type, 0);
14644 if (TREE_CODE (type) == METHOD_TYPE)
14646 error ("parameter %qD invalidly declared method type", decl);
14647 type = build_pointer_type (type);
14648 TREE_TYPE (decl) = type;
14650 else if (cxx_dialect < cxx17 && INDIRECT_TYPE_P (type))
14652 /* Before C++17 DR 393:
14653 [dcl.fct]/6, parameter types cannot contain pointers
14654 (references) to arrays of unknown bound. */
14655 tree t = TREE_TYPE (type);
14656 int ptr = TYPE_PTR_P (type);
14658 while (1)
14660 if (TYPE_PTR_P (t))
14661 ptr = 1;
14662 else if (TREE_CODE (t) != ARRAY_TYPE)
14663 break;
14664 else if (!TYPE_DOMAIN (t))
14665 break;
14666 t = TREE_TYPE (t);
14668 if (TREE_CODE (t) == ARRAY_TYPE)
14669 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wpedantic,
14671 ? G_("parameter %qD includes pointer to array of "
14672 "unknown bound %qT")
14673 : G_("parameter %qD includes reference to array of "
14674 "unknown bound %qT"),
14675 decl, t);
14678 if (init && !processing_template_decl)
14679 init = check_default_argument (decl, init, tf_warning_or_error);
14682 DECL_CHAIN (decl) = decls;
14683 decls = decl;
14684 result = tree_cons (init, type, result);
14686 decls = nreverse (decls);
14687 result = nreverse (result);
14688 if (parm)
14689 result = chainon (result, void_list_node);
14690 *parms = decls;
14691 if (any_error)
14692 result = NULL_TREE;
14694 if (any_error)
14695 /* We had parm errors, recover by giving the function (...) type. */
14696 result = NULL_TREE;
14698 return result;
14702 /* D is a constructor or overloaded `operator='.
14704 Let T be the class in which D is declared. Then, this function
14705 returns:
14707 -1 if D's is an ill-formed constructor or copy assignment operator
14708 whose first parameter is of type `T'.
14709 0 if D is not a copy constructor or copy assignment
14710 operator.
14711 1 if D is a copy constructor or copy assignment operator whose
14712 first parameter is a reference to non-const qualified T.
14713 2 if D is a copy constructor or copy assignment operator whose
14714 first parameter is a reference to const qualified T.
14716 This function can be used as a predicate. Positive values indicate
14717 a copy constructor and nonzero values indicate a copy assignment
14718 operator. */
14721 copy_fn_p (const_tree d)
14723 tree args;
14724 tree arg_type;
14725 int result = 1;
14727 gcc_assert (DECL_FUNCTION_MEMBER_P (d));
14729 if (TREE_CODE (d) == TEMPLATE_DECL
14730 || (DECL_TEMPLATE_INFO (d)
14731 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (d))))
14732 /* Instantiations of template member functions are never copy
14733 functions. Note that member functions of templated classes are
14734 represented as template functions internally, and we must
14735 accept those as copy functions. */
14736 return 0;
14738 if (!DECL_CONSTRUCTOR_P (d)
14739 && DECL_NAME (d) != assign_op_identifier)
14740 return 0;
14742 args = FUNCTION_FIRST_USER_PARMTYPE (d);
14743 if (!args)
14744 return 0;
14746 arg_type = TREE_VALUE (args);
14747 if (arg_type == error_mark_node)
14748 return 0;
14750 if (TYPE_MAIN_VARIANT (arg_type) == DECL_CONTEXT (d))
14752 /* Pass by value copy assignment operator. */
14753 result = -1;
14755 else if (TYPE_REF_P (arg_type)
14756 && !TYPE_REF_IS_RVALUE (arg_type)
14757 && TYPE_MAIN_VARIANT (TREE_TYPE (arg_type)) == DECL_CONTEXT (d))
14759 if (CP_TYPE_CONST_P (TREE_TYPE (arg_type)))
14760 result = 2;
14762 else
14763 return 0;
14765 args = TREE_CHAIN (args);
14767 if (args && args != void_list_node && !TREE_PURPOSE (args))
14768 /* There are more non-optional args. */
14769 return 0;
14771 return result;
14774 /* D is a constructor or overloaded `operator='.
14776 Let T be the class in which D is declared. Then, this function
14777 returns true when D is a move constructor or move assignment
14778 operator, false otherwise. */
14780 bool
14781 move_fn_p (const_tree d)
14783 gcc_assert (DECL_FUNCTION_MEMBER_P (d));
14785 if (cxx_dialect == cxx98)
14786 /* There are no move constructors if we are in C++98 mode. */
14787 return false;
14789 if (TREE_CODE (d) == TEMPLATE_DECL
14790 || (DECL_TEMPLATE_INFO (d)
14791 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (d))))
14792 /* Instantiations of template member functions are never move
14793 functions. Note that member functions of templated classes are
14794 represented as template functions internally, and we must
14795 accept those as move functions. */
14796 return 0;
14798 return move_signature_fn_p (d);
14801 /* D is a constructor or overloaded `operator='.
14803 Then, this function returns true when D has the same signature as a move
14804 constructor or move assignment operator (because either it is such a
14805 ctor/op= or it is a template specialization with the same signature),
14806 false otherwise. */
14808 bool
14809 move_signature_fn_p (const_tree d)
14811 tree args;
14812 tree arg_type;
14813 bool result = false;
14815 if (!DECL_CONSTRUCTOR_P (d)
14816 && DECL_NAME (d) != assign_op_identifier)
14817 return 0;
14819 args = FUNCTION_FIRST_USER_PARMTYPE (d);
14820 if (!args)
14821 return 0;
14823 arg_type = TREE_VALUE (args);
14824 if (arg_type == error_mark_node)
14825 return 0;
14827 if (TYPE_REF_P (arg_type)
14828 && TYPE_REF_IS_RVALUE (arg_type)
14829 && same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (arg_type)),
14830 DECL_CONTEXT (d)))
14831 result = true;
14833 args = TREE_CHAIN (args);
14835 if (args && args != void_list_node && !TREE_PURPOSE (args))
14836 /* There are more non-optional args. */
14837 return false;
14839 return result;
14842 /* Remember any special properties of member function DECL. */
14844 void
14845 grok_special_member_properties (tree decl)
14847 tree class_type;
14849 if (TREE_CODE (decl) == USING_DECL
14850 || !DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
14851 return;
14853 class_type = DECL_CONTEXT (decl);
14854 if (IDENTIFIER_CTOR_P (DECL_NAME (decl)))
14856 int ctor = copy_fn_p (decl);
14858 if (!DECL_ARTIFICIAL (decl))
14859 TYPE_HAS_USER_CONSTRUCTOR (class_type) = 1;
14861 if (ctor > 0)
14863 /* [class.copy]
14865 A non-template constructor for class X is a copy
14866 constructor if its first parameter is of type X&, const
14867 X&, volatile X& or const volatile X&, and either there
14868 are no other parameters or else all other parameters have
14869 default arguments. */
14870 TYPE_HAS_COPY_CTOR (class_type) = 1;
14871 if (ctor > 1)
14872 TYPE_HAS_CONST_COPY_CTOR (class_type) = 1;
14875 if (sufficient_parms_p (FUNCTION_FIRST_USER_PARMTYPE (decl)))
14876 TYPE_HAS_DEFAULT_CONSTRUCTOR (class_type) = 1;
14878 if (is_list_ctor (decl))
14879 TYPE_HAS_LIST_CTOR (class_type) = 1;
14881 if (maybe_constexpr_fn (decl)
14882 && !ctor && !move_fn_p (decl))
14883 TYPE_HAS_CONSTEXPR_CTOR (class_type) = 1;
14885 else if (DECL_NAME (decl) == assign_op_identifier)
14887 /* [class.copy]
14889 A non-template assignment operator for class X is a copy
14890 assignment operator if its parameter is of type X, X&, const
14891 X&, volatile X& or const volatile X&. */
14893 int assop = copy_fn_p (decl);
14895 if (assop)
14897 TYPE_HAS_COPY_ASSIGN (class_type) = 1;
14898 if (assop != 1)
14899 TYPE_HAS_CONST_COPY_ASSIGN (class_type) = 1;
14902 else if (IDENTIFIER_CONV_OP_P (DECL_NAME (decl)))
14903 TYPE_HAS_CONVERSION (class_type) = true;
14905 /* Destructors are handled in check_methods. */
14908 /* Check a constructor DECL has the correct form. Complains
14909 if the class has a constructor of the form X(X). */
14911 bool
14912 grok_ctor_properties (const_tree ctype, const_tree decl)
14914 int ctor_parm = copy_fn_p (decl);
14916 if (ctor_parm < 0)
14918 /* [class.copy]
14920 A declaration of a constructor for a class X is ill-formed if
14921 its first parameter is of type (optionally cv-qualified) X
14922 and either there are no other parameters or else all other
14923 parameters have default arguments.
14925 We *don't* complain about member template instantiations that
14926 have this form, though; they can occur as we try to decide
14927 what constructor to use during overload resolution. Since
14928 overload resolution will never prefer such a constructor to
14929 the non-template copy constructor (which is either explicitly
14930 or implicitly defined), there's no need to worry about their
14931 existence. Theoretically, they should never even be
14932 instantiated, but that's hard to forestall. */
14933 error_at (DECL_SOURCE_LOCATION (decl),
14934 "invalid constructor; you probably meant %<%T (const %T&)%>",
14935 ctype, ctype);
14936 return false;
14939 return true;
14942 /* DECL is a declaration for an overloaded or conversion operator. If
14943 COMPLAIN is true, errors are issued for invalid declarations. */
14945 bool
14946 grok_op_properties (tree decl, bool complain)
14948 tree argtypes = TYPE_ARG_TYPES (TREE_TYPE (decl));
14949 bool methodp = TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE;
14950 tree name = DECL_NAME (decl);
14951 location_t loc = DECL_SOURCE_LOCATION (decl);
14953 tree class_type = DECL_CONTEXT (decl);
14954 if (class_type && !CLASS_TYPE_P (class_type))
14955 class_type = NULL_TREE;
14957 tree_code operator_code;
14958 unsigned op_flags;
14959 if (IDENTIFIER_CONV_OP_P (name))
14961 /* Conversion operators are TYPE_EXPR for the purposes of this
14962 function. */
14963 operator_code = TYPE_EXPR;
14964 op_flags = OVL_OP_FLAG_UNARY;
14966 else
14968 const ovl_op_info_t *ovl_op = IDENTIFIER_OVL_OP_INFO (name);
14970 operator_code = ovl_op->tree_code;
14971 op_flags = ovl_op->flags;
14972 gcc_checking_assert (operator_code != ERROR_MARK);
14973 DECL_OVERLOADED_OPERATOR_CODE_RAW (decl) = ovl_op->ovl_op_code;
14976 if (op_flags & OVL_OP_FLAG_ALLOC)
14978 /* operator new and operator delete are quite special. */
14979 if (class_type)
14980 switch (op_flags)
14982 case OVL_OP_FLAG_ALLOC:
14983 TYPE_HAS_NEW_OPERATOR (class_type) = 1;
14984 break;
14986 case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_DELETE:
14987 TYPE_GETS_DELETE (class_type) |= 1;
14988 break;
14990 case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_VEC:
14991 TYPE_HAS_ARRAY_NEW_OPERATOR (class_type) = 1;
14992 break;
14994 case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_DELETE | OVL_OP_FLAG_VEC:
14995 TYPE_GETS_DELETE (class_type) |= 2;
14996 break;
14998 default:
14999 gcc_unreachable ();
15002 /* [basic.std.dynamic.allocation]/1:
15004 A program is ill-formed if an allocation function is declared
15005 in a namespace scope other than global scope or declared
15006 static in global scope.
15008 The same also holds true for deallocation functions. */
15009 if (DECL_NAMESPACE_SCOPE_P (decl))
15011 if (CP_DECL_CONTEXT (decl) != global_namespace)
15013 error_at (loc, "%qD may not be declared within a namespace",
15014 decl);
15015 return false;
15018 if (!TREE_PUBLIC (decl))
15020 error_at (loc, "%qD may not be declared as static", decl);
15021 return false;
15025 if (op_flags & OVL_OP_FLAG_DELETE)
15027 DECL_SET_IS_OPERATOR_DELETE (decl, true);
15028 coerce_delete_type (decl, loc);
15030 else
15032 DECL_SET_IS_OPERATOR_NEW (decl, true);
15033 TREE_TYPE (decl) = coerce_new_type (TREE_TYPE (decl), loc);
15036 return true;
15039 /* An operator function must either be a non-static member function
15040 or have at least one parameter of a class, a reference to a class,
15041 an enumeration, or a reference to an enumeration. 13.4.0.6 */
15042 if (! methodp || DECL_STATIC_FUNCTION_P (decl))
15044 if (operator_code == TYPE_EXPR
15045 || operator_code == CALL_EXPR
15046 || operator_code == COMPONENT_REF
15047 || operator_code == ARRAY_REF
15048 || operator_code == NOP_EXPR)
15050 error_at (loc, "%qD must be a non-static member function", decl);
15051 return false;
15054 if (DECL_STATIC_FUNCTION_P (decl))
15056 error_at (loc, "%qD must be either a non-static member "
15057 "function or a non-member function", decl);
15058 return false;
15061 for (tree arg = argtypes; ; arg = TREE_CHAIN (arg))
15063 if (!arg || arg == void_list_node)
15065 if (complain)
15066 error_at(loc, "%qD must have an argument of class or "
15067 "enumerated type", decl);
15068 return false;
15071 tree type = non_reference (TREE_VALUE (arg));
15072 if (type == error_mark_node)
15073 return false;
15075 /* MAYBE_CLASS_TYPE_P, rather than CLASS_TYPE_P, is used
15076 because these checks are performed even on template
15077 functions. */
15078 if (MAYBE_CLASS_TYPE_P (type)
15079 || TREE_CODE (type) == ENUMERAL_TYPE)
15080 break;
15084 if (operator_code == CALL_EXPR)
15085 /* There are no further restrictions on the arguments to an overloaded
15086 "operator ()". */
15087 return true;
15089 if (operator_code == COND_EXPR)
15091 /* 13.4.0.3 */
15092 error_at (loc, "ISO C++ prohibits overloading %<operator ?:%>");
15093 return false;
15096 /* Count the number of arguments and check for ellipsis. */
15097 int arity = 0;
15098 for (tree arg = argtypes; arg != void_list_node; arg = TREE_CHAIN (arg))
15100 if (!arg)
15102 /* Variadic. */
15103 error_at (loc, "%qD must not have variable number of arguments",
15104 decl);
15105 return false;
15107 ++arity;
15110 /* Verify correct number of arguments. */
15111 switch (op_flags)
15113 case OVL_OP_FLAG_AMBIARY:
15114 if (arity == 1)
15116 /* We have a unary instance of an ambi-ary op. Remap to the
15117 unary one. */
15118 unsigned alt = ovl_op_alternate[ovl_op_mapping [operator_code]];
15119 const ovl_op_info_t *ovl_op = &ovl_op_info[false][alt];
15120 gcc_checking_assert (ovl_op->flags == OVL_OP_FLAG_UNARY);
15121 operator_code = ovl_op->tree_code;
15122 DECL_OVERLOADED_OPERATOR_CODE_RAW (decl) = ovl_op->ovl_op_code;
15124 else if (arity != 2)
15126 /* This was an ambiguous operator but is invalid. */
15127 error_at (loc,
15128 methodp
15129 ? G_("%qD must have either zero or one argument")
15130 : G_("%qD must have either one or two arguments"), decl);
15131 return false;
15133 else if ((operator_code == POSTINCREMENT_EXPR
15134 || operator_code == POSTDECREMENT_EXPR)
15135 && ! processing_template_decl
15136 /* x++ and x--'s second argument must be an int. */
15137 && ! same_type_p (TREE_VALUE (TREE_CHAIN (argtypes)),
15138 integer_type_node))
15140 error_at (loc,
15141 methodp
15142 ? G_("postfix %qD must have %<int%> as its argument")
15143 : G_("postfix %qD must have %<int%> as its second argument"),
15144 decl);
15145 return false;
15147 break;
15149 case OVL_OP_FLAG_UNARY:
15150 if (arity != 1)
15152 error_at (loc,
15153 methodp
15154 ? G_("%qD must have no arguments")
15155 : G_("%qD must have exactly one argument"), decl);
15156 return false;
15158 break;
15160 case OVL_OP_FLAG_BINARY:
15161 if (arity != 2)
15163 if (operator_code == ARRAY_REF && cxx_dialect >= cxx23)
15164 break;
15165 error_at (loc,
15166 methodp
15167 ? G_("%qD must have exactly one argument")
15168 : G_("%qD must have exactly two arguments"), decl);
15169 return false;
15171 break;
15173 default:
15174 gcc_unreachable ();
15177 /* There can be no default arguments. */
15178 for (tree arg = argtypes; arg != void_list_node; arg = TREE_CHAIN (arg))
15179 if (TREE_PURPOSE (arg))
15181 TREE_PURPOSE (arg) = NULL_TREE;
15182 error_at (loc, "%qD cannot have default arguments", decl);
15183 return false;
15186 /* At this point the declaration is well-formed. It may not be
15187 sensible though. */
15189 /* Check member function warnings only on the in-class declaration.
15190 There's no point warning on an out-of-class definition. */
15191 if (class_type && class_type != current_class_type)
15192 return true;
15194 /* Warn about conversion operators that will never be used. */
15195 if (IDENTIFIER_CONV_OP_P (name)
15196 && ! DECL_TEMPLATE_INFO (decl)
15197 && warn_class_conversion)
15199 tree t = TREE_TYPE (name);
15200 int ref = TYPE_REF_P (t);
15202 if (ref)
15203 t = TYPE_MAIN_VARIANT (TREE_TYPE (t));
15205 if (VOID_TYPE_P (t))
15206 warning_at (loc, OPT_Wclass_conversion, "converting %qT to %<void%> "
15207 "will never use a type conversion operator", class_type);
15208 else if (class_type)
15210 if (same_type_ignoring_top_level_qualifiers_p (t, class_type))
15211 warning_at (loc, OPT_Wclass_conversion,
15213 ? G_("converting %qT to a reference to the same type "
15214 "will never use a type conversion operator")
15215 : G_("converting %qT to the same type "
15216 "will never use a type conversion operator"),
15217 class_type);
15218 /* Don't force t to be complete here. */
15219 else if (MAYBE_CLASS_TYPE_P (t)
15220 && COMPLETE_TYPE_P (t)
15221 && DERIVED_FROM_P (t, class_type))
15222 warning_at (loc, OPT_Wclass_conversion,
15224 ? G_("converting %qT to a reference to a base class "
15225 "%qT will never use a type conversion operator")
15226 : G_("converting %qT to a base class %qT "
15227 "will never use a type conversion operator"),
15228 class_type, t);
15232 if (!warn_ecpp)
15233 return true;
15235 /* Effective C++ rules below. */
15237 /* More Effective C++ rule 7. */
15238 if (operator_code == TRUTH_ANDIF_EXPR
15239 || operator_code == TRUTH_ORIF_EXPR
15240 || operator_code == COMPOUND_EXPR)
15241 warning_at (loc, OPT_Weffc__,
15242 "user-defined %qD always evaluates both arguments", decl);
15244 /* More Effective C++ rule 6. */
15245 if (operator_code == POSTINCREMENT_EXPR
15246 || operator_code == POSTDECREMENT_EXPR
15247 || operator_code == PREINCREMENT_EXPR
15248 || operator_code == PREDECREMENT_EXPR)
15250 tree arg = TREE_VALUE (argtypes);
15251 tree ret = TREE_TYPE (TREE_TYPE (decl));
15252 if (methodp || TYPE_REF_P (arg))
15253 arg = TREE_TYPE (arg);
15254 arg = TYPE_MAIN_VARIANT (arg);
15256 if (operator_code == PREINCREMENT_EXPR
15257 || operator_code == PREDECREMENT_EXPR)
15259 if (!TYPE_REF_P (ret)
15260 || !same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (ret)), arg))
15261 warning_at (loc, OPT_Weffc__, "prefix %qD should return %qT", decl,
15262 build_reference_type (arg));
15264 else
15266 if (!same_type_p (TYPE_MAIN_VARIANT (ret), arg))
15267 warning_at (loc, OPT_Weffc__,
15268 "postfix %qD should return %qT", decl, arg);
15272 /* Effective C++ rule 23. */
15273 if (!DECL_ASSIGNMENT_OPERATOR_P (decl)
15274 && (operator_code == PLUS_EXPR
15275 || operator_code == MINUS_EXPR
15276 || operator_code == TRUNC_DIV_EXPR
15277 || operator_code == MULT_EXPR
15278 || operator_code == TRUNC_MOD_EXPR)
15279 && TYPE_REF_P (TREE_TYPE (TREE_TYPE (decl))))
15280 warning_at (loc, OPT_Weffc__, "%qD should return by value", decl);
15282 return true;
15285 /* Return a string giving the keyword associate with CODE. */
15287 static const char *
15288 tag_name (enum tag_types code)
15290 switch (code)
15292 case record_type:
15293 return "struct";
15294 case class_type:
15295 return "class";
15296 case union_type:
15297 return "union";
15298 case enum_type:
15299 return "enum";
15300 case typename_type:
15301 return "typename";
15302 default:
15303 gcc_unreachable ();
15307 /* Name lookup in an elaborated-type-specifier (after the keyword
15308 indicated by TAG_CODE) has found the TYPE_DECL DECL. If the
15309 elaborated-type-specifier is invalid, issue a diagnostic and return
15310 error_mark_node; otherwise, return the *_TYPE to which it referred.
15311 If ALLOW_TEMPLATE_P is true, TYPE may be a class template. */
15313 tree
15314 check_elaborated_type_specifier (enum tag_types tag_code,
15315 tree decl,
15316 bool allow_template_p)
15318 tree type;
15320 /* In the case of:
15322 struct S { struct S *p; };
15324 name lookup will find the TYPE_DECL for the implicit "S::S"
15325 typedef. Adjust for that here. */
15326 if (DECL_SELF_REFERENCE_P (decl))
15327 decl = TYPE_NAME (TREE_TYPE (decl));
15329 type = TREE_TYPE (decl);
15331 /* Check TEMPLATE_TYPE_PARM first because DECL_IMPLICIT_TYPEDEF_P
15332 is false for this case as well. */
15333 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
15335 error ("using template type parameter %qT after %qs",
15336 type, tag_name (tag_code));
15337 return error_mark_node;
15339 /* Accept template template parameters. */
15340 else if (allow_template_p
15341 && (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM
15342 || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM))
15344 /* [dcl.type.elab]
15346 If the identifier resolves to a typedef-name or the
15347 simple-template-id resolves to an alias template
15348 specialization, the elaborated-type-specifier is ill-formed.
15350 In other words, the only legitimate declaration to use in the
15351 elaborated type specifier is the implicit typedef created when
15352 the type is declared. */
15353 else if (!DECL_IMPLICIT_TYPEDEF_P (decl)
15354 && !DECL_SELF_REFERENCE_P (decl)
15355 && tag_code != typename_type)
15357 if (alias_template_specialization_p (type, nt_opaque))
15358 error ("using alias template specialization %qT after %qs",
15359 type, tag_name (tag_code));
15360 else
15361 error ("using typedef-name %qD after %qs", decl, tag_name (tag_code));
15362 inform (DECL_SOURCE_LOCATION (decl),
15363 "%qD has a previous declaration here", decl);
15364 return error_mark_node;
15366 else if (TREE_CODE (type) != RECORD_TYPE
15367 && TREE_CODE (type) != UNION_TYPE
15368 && tag_code != enum_type
15369 && tag_code != typename_type)
15371 error ("%qT referred to as %qs", type, tag_name (tag_code));
15372 inform (location_of (type), "%qT has a previous declaration here", type);
15373 return error_mark_node;
15375 else if (TREE_CODE (type) != ENUMERAL_TYPE
15376 && tag_code == enum_type)
15378 error ("%qT referred to as enum", type);
15379 inform (location_of (type), "%qT has a previous declaration here", type);
15380 return error_mark_node;
15382 else if (!allow_template_p
15383 && TREE_CODE (type) == RECORD_TYPE
15384 && CLASSTYPE_IS_TEMPLATE (type))
15386 /* If a class template appears as elaborated type specifier
15387 without a template header such as:
15389 template <class T> class C {};
15390 void f(class C); // No template header here
15392 then the required template argument is missing. */
15393 error ("template argument required for %<%s %T%>",
15394 tag_name (tag_code),
15395 DECL_NAME (CLASSTYPE_TI_TEMPLATE (type)));
15396 return error_mark_node;
15399 return type;
15402 /* Lookup NAME of an elaborated type specifier according to SCOPE and
15403 issue diagnostics if necessary. Return *_TYPE node upon success,
15404 NULL_TREE when the NAME is not found, and ERROR_MARK_NODE for type
15405 error. */
15407 static tree
15408 lookup_and_check_tag (enum tag_types tag_code, tree name,
15409 TAG_how how, bool template_header_p)
15411 tree decl;
15412 if (how == TAG_how::GLOBAL)
15414 /* First try ordinary name lookup, ignoring hidden class name
15415 injected via friend declaration. */
15416 decl = lookup_name (name, LOOK_want::TYPE);
15417 decl = strip_using_decl (decl);
15418 /* If that fails, the name will be placed in the smallest
15419 non-class, non-function-prototype scope according to 3.3.1/5.
15420 We may already have a hidden name declared as friend in this
15421 scope. So lookup again but not ignoring hidden names.
15422 If we find one, that name will be made visible rather than
15423 creating a new tag. */
15424 if (!decl)
15425 decl = lookup_elaborated_type (name, TAG_how::INNERMOST_NON_CLASS);
15427 else
15428 decl = lookup_elaborated_type (name, how);
15430 if (!decl)
15431 /* We found nothing. */
15432 return NULL_TREE;
15434 if (TREE_CODE (decl) == TREE_LIST)
15436 error ("reference to %qD is ambiguous", name);
15437 print_candidates (decl);
15438 return error_mark_node;
15441 if (DECL_CLASS_TEMPLATE_P (decl)
15442 /* If scope is TAG_how::CURRENT_ONLY we're defining a class,
15443 so ignore a template template parameter. */
15444 || (how != TAG_how::CURRENT_ONLY && DECL_TEMPLATE_TEMPLATE_PARM_P (decl)))
15445 decl = DECL_TEMPLATE_RESULT (decl);
15447 if (TREE_CODE (decl) != TYPE_DECL)
15448 /* Found not-a-type. */
15449 return NULL_TREE;
15451 /* Look for invalid nested type:
15452 class C {
15453 class C {};
15454 }; */
15455 if (how == TAG_how::CURRENT_ONLY && DECL_SELF_REFERENCE_P (decl))
15457 error ("%qD has the same name as the class in which it is "
15458 "declared", decl);
15459 return error_mark_node;
15462 /* Two cases we need to consider when deciding if a class
15463 template is allowed as an elaborated type specifier:
15464 1. It is a self reference to its own class.
15465 2. It comes with a template header.
15467 For example:
15469 template <class T> class C {
15470 class C *c1; // DECL_SELF_REFERENCE_P is true
15471 class D;
15473 template <class U> class C; // template_header_p is true
15474 template <class T> class C<T>::D {
15475 class C *c2; // DECL_SELF_REFERENCE_P is true
15476 }; */
15478 tree t = check_elaborated_type_specifier (tag_code, decl,
15479 template_header_p
15480 | DECL_SELF_REFERENCE_P (decl));
15481 if (template_header_p && t && CLASS_TYPE_P (t)
15482 && (!CLASSTYPE_TEMPLATE_INFO (t)
15483 || (!PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)))))
15485 error ("%qT is not a template", t);
15486 inform (location_of (t), "previous declaration here");
15487 if (TYPE_CLASS_SCOPE_P (t)
15488 && CLASSTYPE_TEMPLATE_INFO (TYPE_CONTEXT (t)))
15489 inform (input_location,
15490 "perhaps you want to explicitly add %<%T::%>",
15491 TYPE_CONTEXT (t));
15492 return error_mark_node;
15495 return t;
15498 /* Get the struct, enum or union (TAG_CODE says which) with tag NAME.
15499 Define the tag as a forward-reference if it is not defined.
15501 If a declaration is given, process it here, and report an error if
15502 multiple declarations are not identical.
15504 SCOPE is TS_CURRENT when this is also a definition. Only look in
15505 the current frame for the name (since C++ allows new names in any
15506 scope.) It is TS_WITHIN_ENCLOSING_NON_CLASS if this is a friend
15507 declaration. Only look beginning from the current scope outward up
15508 till the nearest non-class scope. Otherwise it is TS_GLOBAL.
15510 TEMPLATE_HEADER_P is true when this declaration is preceded by
15511 a set of template parameters. */
15513 tree
15514 xref_tag (enum tag_types tag_code, tree name,
15515 TAG_how how, bool template_header_p)
15517 enum tree_code code;
15518 tree context = NULL_TREE;
15520 auto_cond_timevar tv (TV_NAME_LOOKUP);
15522 gcc_assert (identifier_p (name));
15524 switch (tag_code)
15526 case record_type:
15527 case class_type:
15528 code = RECORD_TYPE;
15529 break;
15530 case union_type:
15531 code = UNION_TYPE;
15532 break;
15533 case enum_type:
15534 code = ENUMERAL_TYPE;
15535 break;
15536 default:
15537 gcc_unreachable ();
15540 /* In case of anonymous name, xref_tag is only called to
15541 make type node and push name. Name lookup is not required. */
15542 tree t = NULL_TREE;
15543 if (!IDENTIFIER_ANON_P (name))
15544 t = lookup_and_check_tag (tag_code, name, how, template_header_p);
15546 if (t == error_mark_node)
15547 return error_mark_node;
15549 if (how != TAG_how::CURRENT_ONLY && t && current_class_type
15550 && template_class_depth (current_class_type)
15551 && template_header_p)
15553 if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
15554 return t;
15556 /* Since HOW is not TAG_how::CURRENT_ONLY, we are not looking at
15557 a definition of this tag. Since, in addition, we are
15558 currently processing a (member) template declaration of a
15559 template class, we must be very careful; consider:
15561 template <class X> struct S1
15563 template <class U> struct S2
15565 template <class V> friend struct S1;
15568 Here, the S2::S1 declaration should not be confused with the
15569 outer declaration. In particular, the inner version should
15570 have a template parameter of level 2, not level 1.
15572 On the other hand, when presented with:
15574 template <class T> struct S1
15576 template <class U> struct S2 {};
15577 template <class U> friend struct S2;
15580 the friend must find S1::S2 eventually. We accomplish this
15581 by making sure that the new type we create to represent this
15582 declaration has the right TYPE_CONTEXT. */
15583 context = TYPE_CONTEXT (t);
15584 t = NULL_TREE;
15587 if (! t)
15589 /* If no such tag is yet defined, create a forward-reference node
15590 and record it as the "definition".
15591 When a real declaration of this type is found,
15592 the forward-reference will be altered into a real type. */
15593 if (code == ENUMERAL_TYPE)
15595 error ("use of enum %q#D without previous declaration", name);
15596 return error_mark_node;
15599 t = make_class_type (code);
15600 TYPE_CONTEXT (t) = context;
15601 if (IDENTIFIER_LAMBDA_P (name))
15602 /* Mark it as a lambda type right now. Our caller will
15603 correct the value. */
15604 CLASSTYPE_LAMBDA_EXPR (t) = error_mark_node;
15605 t = pushtag (name, t, how);
15607 else
15609 if (template_header_p && MAYBE_CLASS_TYPE_P (t))
15611 /* Check that we aren't trying to overload a class with different
15612 constraints. */
15613 tree constr = NULL_TREE;
15614 if (current_template_parms)
15616 tree reqs = TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
15617 constr = build_constraints (reqs, NULL_TREE);
15619 if (!redeclare_class_template (t, current_template_parms, constr))
15620 return error_mark_node;
15622 else if (!processing_template_decl
15623 && CLASS_TYPE_P (t)
15624 && CLASSTYPE_IS_TEMPLATE (t))
15626 error ("redeclaration of %qT as a non-template", t);
15627 inform (location_of (t), "previous declaration %qD", t);
15628 return error_mark_node;
15631 if (modules_p ()
15632 && how == TAG_how::CURRENT_ONLY)
15634 tree decl = TYPE_NAME (t);
15635 if (!module_may_redeclare (decl))
15637 error ("cannot declare %qD in a different module", decl);
15638 inform (DECL_SOURCE_LOCATION (decl), "declared here");
15639 return error_mark_node;
15642 tree maybe_tmpl = decl;
15643 if (CLASS_TYPE_P (t) && CLASSTYPE_IS_TEMPLATE (t))
15644 maybe_tmpl = CLASSTYPE_TI_TEMPLATE (t);
15646 if (DECL_LANG_SPECIFIC (decl)
15647 && DECL_MODULE_IMPORT_P (decl)
15648 && TREE_CODE (CP_DECL_CONTEXT (decl)) == NAMESPACE_DECL)
15650 /* Push it into this TU's symbol slot. */
15651 gcc_checking_assert (current_namespace == CP_DECL_CONTEXT (decl));
15652 if (maybe_tmpl != decl)
15653 /* We're in the template parm binding level.
15654 Pushtag has logic to slide under that, but we're
15655 not pushing a *new* type. */
15656 push_nested_namespace (CP_DECL_CONTEXT (decl));
15658 pushdecl (maybe_tmpl);
15659 if (maybe_tmpl != decl)
15660 pop_nested_namespace (CP_DECL_CONTEXT (decl));
15663 set_instantiating_module (maybe_tmpl);
15667 return t;
15670 /* Create the binfo hierarchy for REF with (possibly NULL) base list
15671 BASE_LIST. For each element on BASE_LIST the TREE_PURPOSE is an
15672 access_* node, and the TREE_VALUE is the type of the base-class.
15673 Non-NULL TREE_TYPE indicates virtual inheritance. */
15675 void
15676 xref_basetypes (tree ref, tree base_list)
15678 tree *basep;
15679 tree binfo, base_binfo;
15680 unsigned max_vbases = 0; /* Maximum direct & indirect virtual bases. */
15681 unsigned max_bases = 0; /* Maximum direct bases. */
15682 unsigned max_dvbases = 0; /* Maximum direct virtual bases. */
15683 int i;
15684 tree default_access;
15685 tree igo_prev; /* Track Inheritance Graph Order. */
15687 if (ref == error_mark_node)
15688 return;
15690 /* The base of a derived class is private by default, all others are
15691 public. */
15692 default_access = (TREE_CODE (ref) == RECORD_TYPE
15693 && CLASSTYPE_DECLARED_CLASS (ref)
15694 ? access_private_node : access_public_node);
15696 /* First, make sure that any templates in base-classes are
15697 instantiated. This ensures that if we call ourselves recursively
15698 we do not get confused about which classes are marked and which
15699 are not. */
15700 basep = &base_list;
15701 while (*basep)
15703 tree basetype = TREE_VALUE (*basep);
15705 /* The dependent_type_p call below should really be dependent_scope_p
15706 so that we give a hard error about using an incomplete type as a
15707 base, but we allow it with a pedwarn for backward
15708 compatibility. */
15709 if (processing_template_decl
15710 && CLASS_TYPE_P (basetype) && TYPE_BEING_DEFINED (basetype))
15711 cxx_incomplete_type_diagnostic (NULL_TREE, basetype, DK_PEDWARN);
15712 if (!dependent_type_p (basetype)
15713 && !complete_type_or_else (basetype, NULL))
15714 /* An incomplete type. Remove it from the list. */
15715 *basep = TREE_CHAIN (*basep);
15716 else
15718 max_bases++;
15719 if (TREE_TYPE (*basep))
15720 max_dvbases++;
15721 if (CLASS_TYPE_P (basetype))
15722 max_vbases += vec_safe_length (CLASSTYPE_VBASECLASSES (basetype));
15723 basep = &TREE_CHAIN (*basep);
15726 max_vbases += max_dvbases;
15728 TYPE_MARKED_P (ref) = 1;
15730 /* The binfo slot should be empty, unless this is an (ill-formed)
15731 redefinition. */
15732 gcc_assert (!TYPE_BINFO (ref) || TYPE_SIZE (ref));
15734 gcc_assert (TYPE_MAIN_VARIANT (ref) == ref);
15736 binfo = make_tree_binfo (max_bases);
15738 TYPE_BINFO (ref) = binfo;
15739 BINFO_OFFSET (binfo) = size_zero_node;
15740 BINFO_TYPE (binfo) = ref;
15742 /* Apply base-class info set up to the variants of this type. */
15743 fixup_type_variants (ref);
15745 if (max_bases)
15747 vec_alloc (BINFO_BASE_ACCESSES (binfo), max_bases);
15748 /* A C++98 POD cannot have base classes. */
15749 CLASSTYPE_NON_LAYOUT_POD_P (ref) = true;
15751 if (TREE_CODE (ref) == UNION_TYPE)
15753 error ("derived union %qT invalid", ref);
15754 return;
15758 if (max_bases > 1)
15759 warning (OPT_Wmultiple_inheritance,
15760 "%qT defined with multiple direct bases", ref);
15762 if (max_vbases)
15764 /* An aggregate can't have virtual base classes. */
15765 CLASSTYPE_NON_AGGREGATE (ref) = true;
15767 vec_alloc (CLASSTYPE_VBASECLASSES (ref), max_vbases);
15769 if (max_dvbases)
15770 warning (OPT_Wvirtual_inheritance,
15771 "%qT defined with direct virtual base", ref);
15774 for (igo_prev = binfo; base_list; base_list = TREE_CHAIN (base_list))
15776 tree access = TREE_PURPOSE (base_list);
15777 int via_virtual = TREE_TYPE (base_list) != NULL_TREE;
15778 tree basetype = TREE_VALUE (base_list);
15780 if (access == access_default_node)
15781 access = default_access;
15783 /* Before C++17, an aggregate cannot have base classes. In C++17, an
15784 aggregate can't have virtual, private, or protected base classes. */
15785 if (cxx_dialect < cxx17
15786 || access != access_public_node
15787 || via_virtual)
15788 CLASSTYPE_NON_AGGREGATE (ref) = true;
15790 if (PACK_EXPANSION_P (basetype))
15791 basetype = PACK_EXPANSION_PATTERN (basetype);
15792 if (TREE_CODE (basetype) == TYPE_DECL)
15793 basetype = TREE_TYPE (basetype);
15794 if (!MAYBE_CLASS_TYPE_P (basetype) || TREE_CODE (basetype) == UNION_TYPE)
15796 error ("base type %qT fails to be a struct or class type",
15797 basetype);
15798 goto dropped_base;
15801 base_binfo = NULL_TREE;
15802 if (CLASS_TYPE_P (basetype) && !dependent_scope_p (basetype))
15804 base_binfo = TYPE_BINFO (basetype);
15805 /* The original basetype could have been a typedef'd type. */
15806 basetype = BINFO_TYPE (base_binfo);
15808 /* Inherit flags from the base. */
15809 TYPE_HAS_NEW_OPERATOR (ref)
15810 |= TYPE_HAS_NEW_OPERATOR (basetype);
15811 TYPE_HAS_ARRAY_NEW_OPERATOR (ref)
15812 |= TYPE_HAS_ARRAY_NEW_OPERATOR (basetype);
15813 TYPE_GETS_DELETE (ref) |= TYPE_GETS_DELETE (basetype);
15814 TYPE_HAS_CONVERSION (ref) |= TYPE_HAS_CONVERSION (basetype);
15815 CLASSTYPE_DIAMOND_SHAPED_P (ref)
15816 |= CLASSTYPE_DIAMOND_SHAPED_P (basetype);
15817 CLASSTYPE_REPEATED_BASE_P (ref)
15818 |= CLASSTYPE_REPEATED_BASE_P (basetype);
15821 /* We must do this test after we've seen through a typedef
15822 type. */
15823 if (TYPE_MARKED_P (basetype))
15825 if (basetype == ref)
15826 error ("recursive type %qT undefined", basetype);
15827 else
15828 error ("duplicate base type %qT invalid", basetype);
15829 goto dropped_base;
15832 if (PACK_EXPANSION_P (TREE_VALUE (base_list)))
15833 /* Regenerate the pack expansion for the bases. */
15834 basetype = make_pack_expansion (basetype);
15836 TYPE_MARKED_P (basetype) = 1;
15838 base_binfo = copy_binfo (base_binfo, basetype, ref,
15839 &igo_prev, via_virtual);
15840 if (!BINFO_INHERITANCE_CHAIN (base_binfo))
15841 BINFO_INHERITANCE_CHAIN (base_binfo) = binfo;
15843 BINFO_BASE_APPEND (binfo, base_binfo);
15844 BINFO_BASE_ACCESS_APPEND (binfo, access);
15845 continue;
15847 dropped_base:
15848 /* Update max_vbases to reflect the reality that we are dropping
15849 this base: if it reaches zero we want to undo the vec_alloc
15850 above to avoid inconsistencies during error-recovery: eg, in
15851 build_special_member_call, CLASSTYPE_VBASECLASSES non null
15852 and vtt null (c++/27952). */
15853 if (via_virtual)
15854 max_vbases--;
15855 if (CLASS_TYPE_P (basetype))
15856 max_vbases
15857 -= vec_safe_length (CLASSTYPE_VBASECLASSES (basetype));
15860 if (CLASSTYPE_VBASECLASSES (ref)
15861 && max_vbases == 0)
15862 vec_free (CLASSTYPE_VBASECLASSES (ref));
15864 if (vec_safe_length (CLASSTYPE_VBASECLASSES (ref)) < max_vbases)
15865 /* If we didn't get max_vbases vbases, we must have shared at
15866 least one of them, and are therefore diamond shaped. */
15867 CLASSTYPE_DIAMOND_SHAPED_P (ref) = 1;
15869 /* Unmark all the types. */
15870 for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
15871 TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 0;
15872 TYPE_MARKED_P (ref) = 0;
15874 /* Now see if we have a repeated base type. */
15875 if (!CLASSTYPE_REPEATED_BASE_P (ref))
15877 for (base_binfo = binfo; base_binfo;
15878 base_binfo = TREE_CHAIN (base_binfo))
15880 if (TYPE_MARKED_P (BINFO_TYPE (base_binfo)))
15882 CLASSTYPE_REPEATED_BASE_P (ref) = 1;
15883 break;
15885 TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 1;
15887 for (base_binfo = binfo; base_binfo;
15888 base_binfo = TREE_CHAIN (base_binfo))
15889 if (TYPE_MARKED_P (BINFO_TYPE (base_binfo)))
15890 TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 0;
15891 else
15892 break;
15897 /* Copies the enum-related properties from type SRC to type DST.
15898 Used with the underlying type of an enum and the enum itself. */
15899 static void
15900 copy_type_enum (tree dst, tree src)
15902 tree t;
15903 for (t = dst; t; t = TYPE_NEXT_VARIANT (t))
15905 TYPE_MIN_VALUE (t) = TYPE_MIN_VALUE (src);
15906 TYPE_MAX_VALUE (t) = TYPE_MAX_VALUE (src);
15907 TYPE_SIZE (t) = TYPE_SIZE (src);
15908 TYPE_SIZE_UNIT (t) = TYPE_SIZE_UNIT (src);
15909 SET_TYPE_MODE (dst, TYPE_MODE (src));
15910 TYPE_PRECISION (t) = TYPE_PRECISION (src);
15911 unsigned valign = TYPE_ALIGN (src);
15912 if (TYPE_USER_ALIGN (t))
15913 valign = MAX (valign, TYPE_ALIGN (t));
15914 else
15915 TYPE_USER_ALIGN (t) = TYPE_USER_ALIGN (src);
15916 SET_TYPE_ALIGN (t, valign);
15917 TYPE_UNSIGNED (t) = TYPE_UNSIGNED (src);
15921 /* Begin compiling the definition of an enumeration type.
15922 NAME is its name,
15924 if ENUMTYPE is not NULL_TREE then the type has alredy been found.
15926 UNDERLYING_TYPE is the type that will be used as the storage for
15927 the enumeration type. This should be NULL_TREE if no storage type
15928 was specified.
15930 ATTRIBUTES are any attributes specified after the enum-key.
15932 SCOPED_ENUM_P is true if this is a scoped enumeration type.
15934 if IS_NEW is not NULL, gets TRUE iff a new type is created.
15936 Returns the type object, as yet incomplete.
15937 Also records info about it so that build_enumerator
15938 may be used to declare the individual values as they are read. */
15940 tree
15941 start_enum (tree name, tree enumtype, tree underlying_type,
15942 tree attributes, bool scoped_enum_p, bool *is_new)
15944 tree prevtype = NULL_TREE;
15945 gcc_assert (identifier_p (name));
15947 if (is_new)
15948 *is_new = false;
15949 /* [C++0x dcl.enum]p5:
15951 If not explicitly specified, the underlying type of a scoped
15952 enumeration type is int. */
15953 if (!underlying_type && scoped_enum_p)
15954 underlying_type = integer_type_node;
15956 if (underlying_type)
15957 underlying_type = cv_unqualified (underlying_type);
15959 /* If this is the real definition for a previous forward reference,
15960 fill in the contents in the same object that used to be the
15961 forward reference. */
15962 if (!enumtype)
15963 enumtype = lookup_and_check_tag (enum_type, name,
15964 /*tag_scope=*/TAG_how::CURRENT_ONLY,
15965 /*template_header_p=*/false);
15967 /* In case of a template_decl, the only check that should be deferred
15968 to instantiation time is the comparison of underlying types. */
15969 if (enumtype && TREE_CODE (enumtype) == ENUMERAL_TYPE)
15971 if (scoped_enum_p != SCOPED_ENUM_P (enumtype))
15973 error_at (input_location, "scoped/unscoped mismatch "
15974 "in enum %q#T", enumtype);
15975 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
15976 "previous definition here");
15977 enumtype = error_mark_node;
15979 else if (ENUM_FIXED_UNDERLYING_TYPE_P (enumtype) != !! underlying_type)
15981 error_at (input_location, "underlying type mismatch "
15982 "in enum %q#T", enumtype);
15983 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
15984 "previous definition here");
15985 enumtype = error_mark_node;
15987 else if (underlying_type && ENUM_UNDERLYING_TYPE (enumtype)
15988 && !same_type_p (underlying_type,
15989 ENUM_UNDERLYING_TYPE (enumtype)))
15991 error_at (input_location, "different underlying type "
15992 "in enum %q#T", enumtype);
15993 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
15994 "previous definition here");
15995 underlying_type = NULL_TREE;
15998 if (modules_p ())
16000 if (!module_may_redeclare (TYPE_NAME (enumtype)))
16002 error ("cannot define %qD in different module",
16003 TYPE_NAME (enumtype));
16004 inform (DECL_SOURCE_LOCATION (TYPE_NAME (enumtype)),
16005 "declared here");
16006 enumtype = error_mark_node;
16008 set_instantiating_module (TYPE_NAME (enumtype));
16012 if (!enumtype || TREE_CODE (enumtype) != ENUMERAL_TYPE
16013 || processing_template_decl)
16015 /* In case of error, make a dummy enum to allow parsing to
16016 continue. */
16017 if (enumtype == error_mark_node)
16019 name = make_anon_name ();
16020 enumtype = NULL_TREE;
16023 /* enumtype may be an ENUMERAL_TYPE if this is a redefinition
16024 of an opaque enum, or an opaque enum of an already defined
16025 enumeration (C++11).
16026 In any other case, it'll be NULL_TREE. */
16027 if (!enumtype)
16029 if (is_new)
16030 *is_new = true;
16032 prevtype = enumtype;
16034 /* Do not push the decl more than once. */
16035 if (!enumtype
16036 || TREE_CODE (enumtype) != ENUMERAL_TYPE)
16038 enumtype = cxx_make_type (ENUMERAL_TYPE);
16039 enumtype = pushtag (name, enumtype);
16041 /* std::byte aliases anything. */
16042 if (enumtype != error_mark_node
16043 && TYPE_CONTEXT (enumtype) == std_node
16044 && !strcmp ("byte", TYPE_NAME_STRING (enumtype)))
16045 TYPE_ALIAS_SET (enumtype) = 0;
16047 else
16048 enumtype = xref_tag (enum_type, name);
16050 if (enumtype == error_mark_node)
16051 return error_mark_node;
16053 /* The enum is considered opaque until the opening '{' of the
16054 enumerator list. */
16055 SET_OPAQUE_ENUM_P (enumtype, true);
16056 ENUM_FIXED_UNDERLYING_TYPE_P (enumtype) = !! underlying_type;
16059 SET_SCOPED_ENUM_P (enumtype, scoped_enum_p);
16061 cplus_decl_attributes (&enumtype, attributes, (int)ATTR_FLAG_TYPE_IN_PLACE);
16063 if (underlying_type)
16065 if (ENUM_UNDERLYING_TYPE (enumtype))
16066 /* We already checked that it matches, don't change it to a different
16067 typedef variant. */;
16068 else if (CP_INTEGRAL_TYPE_P (underlying_type))
16070 copy_type_enum (enumtype, underlying_type);
16071 ENUM_UNDERLYING_TYPE (enumtype) = underlying_type;
16073 else if (dependent_type_p (underlying_type))
16074 ENUM_UNDERLYING_TYPE (enumtype) = underlying_type;
16075 else
16076 error ("underlying type %qT of %qT must be an integral type",
16077 underlying_type, enumtype);
16080 /* If into a template class, the returned enum is always the first
16081 declaration (opaque or not) seen. This way all the references to
16082 this type will be to the same declaration. The following ones are used
16083 only to check for definition errors. */
16084 if (prevtype && processing_template_decl)
16085 return prevtype;
16086 else
16087 return enumtype;
16090 /* After processing and defining all the values of an enumeration type,
16091 install their decls in the enumeration type.
16092 ENUMTYPE is the type object. */
16094 void
16095 finish_enum_value_list (tree enumtype)
16097 tree values;
16098 tree underlying_type;
16099 tree decl;
16100 tree value;
16101 tree minnode, maxnode;
16102 tree t;
16104 bool fixed_underlying_type_p
16105 = ENUM_UNDERLYING_TYPE (enumtype) != NULL_TREE;
16107 /* We built up the VALUES in reverse order. */
16108 TYPE_VALUES (enumtype) = nreverse (TYPE_VALUES (enumtype));
16110 /* For an enum defined in a template, just set the type of the values;
16111 all further processing is postponed until the template is
16112 instantiated. We need to set the type so that tsubst of a CONST_DECL
16113 works. */
16114 if (processing_template_decl)
16116 for (values = TYPE_VALUES (enumtype);
16117 values;
16118 values = TREE_CHAIN (values))
16119 TREE_TYPE (TREE_VALUE (values)) = enumtype;
16120 return;
16123 /* Determine the minimum and maximum values of the enumerators. */
16124 if (TYPE_VALUES (enumtype))
16126 minnode = maxnode = NULL_TREE;
16128 for (values = TYPE_VALUES (enumtype);
16129 values;
16130 values = TREE_CHAIN (values))
16132 decl = TREE_VALUE (values);
16134 /* [dcl.enum]: Following the closing brace of an enum-specifier,
16135 each enumerator has the type of its enumeration. Prior to the
16136 closing brace, the type of each enumerator is the type of its
16137 initializing value. */
16138 TREE_TYPE (decl) = enumtype;
16140 /* Update the minimum and maximum values, if appropriate. */
16141 value = DECL_INITIAL (decl);
16142 if (value == error_mark_node)
16143 value = integer_zero_node;
16144 /* Figure out what the minimum and maximum values of the
16145 enumerators are. */
16146 if (!minnode)
16147 minnode = maxnode = value;
16148 else if (tree_int_cst_lt (maxnode, value))
16149 maxnode = value;
16150 else if (tree_int_cst_lt (value, minnode))
16151 minnode = value;
16154 else
16155 /* [dcl.enum]
16157 If the enumerator-list is empty, the underlying type is as if
16158 the enumeration had a single enumerator with value 0. */
16159 minnode = maxnode = integer_zero_node;
16161 if (!fixed_underlying_type_p)
16163 /* Compute the number of bits require to represent all values of the
16164 enumeration. We must do this before the type of MINNODE and
16165 MAXNODE are transformed, since tree_int_cst_min_precision relies
16166 on the TREE_TYPE of the value it is passed. */
16167 signop sgn = tree_int_cst_sgn (minnode) >= 0 ? UNSIGNED : SIGNED;
16168 int lowprec = tree_int_cst_min_precision (minnode, sgn);
16169 int highprec = tree_int_cst_min_precision (maxnode, sgn);
16170 int precision = MAX (lowprec, highprec);
16171 unsigned int itk;
16172 bool use_short_enum;
16174 /* Determine the underlying type of the enumeration.
16176 [dcl.enum]
16178 The underlying type of an enumeration is an integral type that
16179 can represent all the enumerator values defined in the
16180 enumeration. It is implementation-defined which integral type is
16181 used as the underlying type for an enumeration except that the
16182 underlying type shall not be larger than int unless the value of
16183 an enumerator cannot fit in an int or unsigned int.
16185 We use "int" or an "unsigned int" as the underlying type, even if
16186 a smaller integral type would work, unless the user has
16187 explicitly requested that we use the smallest possible type. The
16188 user can request that for all enumerations with a command line
16189 flag, or for just one enumeration with an attribute. */
16191 use_short_enum = flag_short_enums
16192 || lookup_attribute ("packed", TYPE_ATTRIBUTES (enumtype));
16194 /* If the precision of the type was specified with an attribute and it
16195 was too small, give an error. Otherwise, use it. */
16196 if (TYPE_PRECISION (enumtype))
16198 if (precision > TYPE_PRECISION (enumtype))
16199 error ("specified mode too small for enumerated values");
16200 else
16202 use_short_enum = true;
16203 precision = TYPE_PRECISION (enumtype);
16207 for (itk = (use_short_enum ? itk_char : itk_int);
16208 itk != itk_none;
16209 itk++)
16211 underlying_type = integer_types[itk];
16212 if (underlying_type != NULL_TREE
16213 && TYPE_PRECISION (underlying_type) >= precision
16214 && TYPE_SIGN (underlying_type) == sgn)
16215 break;
16217 if (itk == itk_none)
16219 /* DR 377
16221 IF no integral type can represent all the enumerator values, the
16222 enumeration is ill-formed. */
16223 error ("no integral type can represent all of the enumerator values "
16224 "for %qT", enumtype);
16225 precision = TYPE_PRECISION (long_long_integer_type_node);
16226 underlying_type = integer_types[itk_unsigned_long_long];
16229 /* [dcl.enum]
16231 The value of sizeof() applied to an enumeration type, an object
16232 of an enumeration type, or an enumerator, is the value of sizeof()
16233 applied to the underlying type. */
16234 copy_type_enum (enumtype, underlying_type);
16236 /* Compute the minimum and maximum values for the type.
16238 [dcl.enum]
16240 For an enumeration where emin is the smallest enumerator and emax
16241 is the largest, the values of the enumeration are the values of the
16242 underlying type in the range bmin to bmax, where bmin and bmax are,
16243 respectively, the smallest and largest values of the smallest bit-
16244 field that can store emin and emax. */
16246 /* The middle-end currently assumes that types with TYPE_PRECISION
16247 narrower than their underlying type are suitably zero or sign
16248 extended to fill their mode. Similarly, it assumes that the front
16249 end assures that a value of a particular type must be within
16250 TYPE_MIN_VALUE and TYPE_MAX_VALUE.
16252 We used to set these fields based on bmin and bmax, but that led
16253 to invalid assumptions like optimizing away bounds checking. So
16254 now we just set the TYPE_PRECISION, TYPE_MIN_VALUE, and
16255 TYPE_MAX_VALUE to the values for the mode above and only restrict
16256 the ENUM_UNDERLYING_TYPE for the benefit of diagnostics. */
16257 ENUM_UNDERLYING_TYPE (enumtype)
16258 = build_distinct_type_copy (underlying_type);
16259 TYPE_PRECISION (ENUM_UNDERLYING_TYPE (enumtype)) = precision;
16260 set_min_and_max_values_for_integral_type
16261 (ENUM_UNDERLYING_TYPE (enumtype), precision, sgn);
16263 /* If -fstrict-enums, still constrain TYPE_MIN/MAX_VALUE. */
16264 if (flag_strict_enums)
16265 set_min_and_max_values_for_integral_type (enumtype, precision, sgn);
16267 else
16268 underlying_type = ENUM_UNDERLYING_TYPE (enumtype);
16270 /* If the enum is exported, mark the consts too. */
16271 bool export_p = (UNSCOPED_ENUM_P (enumtype)
16272 && DECL_MODULE_EXPORT_P (TYPE_STUB_DECL (enumtype))
16273 && at_namespace_scope_p ());
16275 /* Convert each of the enumerators to the type of the underlying
16276 type of the enumeration. */
16277 for (values = TYPE_VALUES (enumtype); values; values = TREE_CHAIN (values))
16279 decl = TREE_VALUE (values);
16280 iloc_sentinel ils (DECL_SOURCE_LOCATION (decl));
16281 if (fixed_underlying_type_p)
16282 /* If the enumeration type has a fixed underlying type, we
16283 already checked all of the enumerator values. */
16284 value = DECL_INITIAL (decl);
16285 else
16286 value = perform_implicit_conversion (underlying_type,
16287 DECL_INITIAL (decl),
16288 tf_warning_or_error);
16289 /* Do not clobber shared ints. */
16290 if (value != error_mark_node)
16292 value = copy_node (value);
16294 TREE_TYPE (value) = enumtype;
16296 DECL_INITIAL (decl) = value;
16297 if (export_p)
16298 DECL_MODULE_EXPORT_P (decl) = true;
16301 /* Fix up all variant types of this enum type. */
16302 for (t = TYPE_MAIN_VARIANT (enumtype); t; t = TYPE_NEXT_VARIANT (t))
16303 TYPE_VALUES (t) = TYPE_VALUES (enumtype);
16305 if (at_class_scope_p ()
16306 && COMPLETE_TYPE_P (current_class_type)
16307 && UNSCOPED_ENUM_P (enumtype))
16309 insert_late_enum_def_bindings (current_class_type, enumtype);
16310 /* TYPE_FIELDS needs fixup. */
16311 fixup_type_variants (current_class_type);
16314 /* Finish debugging output for this type. */
16315 rest_of_type_compilation (enumtype, namespace_bindings_p ());
16317 /* Each enumerator now has the type of its enumeration. Clear the cache
16318 so that this change in types doesn't confuse us later on. */
16319 clear_cv_and_fold_caches ();
16322 /* Finishes the enum type. This is called only the first time an
16323 enumeration is seen, be it opaque or odinary.
16324 ENUMTYPE is the type object. */
16326 void
16327 finish_enum (tree enumtype)
16329 if (processing_template_decl)
16331 if (at_function_scope_p ())
16332 add_stmt (build_min (TAG_DEFN, enumtype));
16333 return;
16336 /* If this is a forward declaration, there should not be any variants,
16337 though we can get a variant in the middle of an enum-specifier with
16338 wacky code like 'enum E { e = sizeof(const E*) };' */
16339 gcc_assert (enumtype == TYPE_MAIN_VARIANT (enumtype)
16340 && (TYPE_VALUES (enumtype)
16341 || !TYPE_NEXT_VARIANT (enumtype)));
16344 /* Build and install a CONST_DECL for an enumeration constant of the
16345 enumeration type ENUMTYPE whose NAME and VALUE (if any) are provided.
16346 Apply ATTRIBUTES if available. LOC is the location of NAME.
16347 Assignment of sequential values by default is handled here. */
16349 void
16350 build_enumerator (tree name, tree value, tree enumtype, tree attributes,
16351 location_t loc)
16353 tree decl;
16354 tree context;
16355 tree type;
16357 /* scalar_constant_value will pull out this expression, so make sure
16358 it's folded as appropriate. */
16359 if (processing_template_decl)
16360 value = fold_non_dependent_expr (value);
16362 /* If the VALUE was erroneous, pretend it wasn't there; that will
16363 result in the enum being assigned the next value in sequence. */
16364 if (value == error_mark_node)
16365 value = NULL_TREE;
16367 /* Remove no-op casts from the value. */
16368 if (value)
16369 STRIP_TYPE_NOPS (value);
16371 if (! processing_template_decl)
16373 /* Validate and default VALUE. */
16374 if (value != NULL_TREE)
16376 if (!ENUM_UNDERLYING_TYPE (enumtype))
16378 tree tmp_value = build_expr_type_conversion (WANT_INT | WANT_ENUM,
16379 value, true);
16380 if (tmp_value)
16381 value = tmp_value;
16383 else if (! INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P
16384 (TREE_TYPE (value)))
16385 value = perform_implicit_conversion_flags
16386 (ENUM_UNDERLYING_TYPE (enumtype), value, tf_warning_or_error,
16387 LOOKUP_IMPLICIT | LOOKUP_NO_NARROWING);
16389 if (value == error_mark_node)
16390 value = NULL_TREE;
16392 if (value != NULL_TREE)
16394 if (! INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P
16395 (TREE_TYPE (value)))
16397 error_at (cp_expr_loc_or_input_loc (value),
16398 "enumerator value for %qD must have integral or "
16399 "unscoped enumeration type", name);
16400 value = NULL_TREE;
16402 else
16404 value = cxx_constant_value (value);
16406 if (TREE_CODE (value) != INTEGER_CST)
16408 error ("enumerator value for %qD is not an integer "
16409 "constant", name);
16410 value = NULL_TREE;
16416 /* Default based on previous value. */
16417 if (value == NULL_TREE)
16419 if (TYPE_VALUES (enumtype))
16421 tree prev_value;
16423 /* C++03 7.2/4: If no initializer is specified for the first
16424 enumerator, the type is an unspecified integral
16425 type. Otherwise the type is the same as the type of the
16426 initializing value of the preceding enumerator unless the
16427 incremented value is not representable in that type, in
16428 which case the type is an unspecified integral type
16429 sufficient to contain the incremented value. */
16430 prev_value = DECL_INITIAL (TREE_VALUE (TYPE_VALUES (enumtype)));
16431 if (error_operand_p (prev_value))
16432 value = error_mark_node;
16433 else
16435 wi::overflow_type overflowed;
16436 tree type = TREE_TYPE (prev_value);
16437 signop sgn = TYPE_SIGN (type);
16438 widest_int wi = wi::add (wi::to_widest (prev_value), 1, sgn,
16439 &overflowed);
16440 if (!overflowed)
16442 bool pos = !wi::neg_p (wi, sgn);
16443 if (!wi::fits_to_tree_p (wi, type))
16445 unsigned int itk;
16446 for (itk = itk_int; itk != itk_none; itk++)
16448 type = integer_types[itk];
16449 if (type != NULL_TREE
16450 && (pos || !TYPE_UNSIGNED (type))
16451 && wi::fits_to_tree_p (wi, type))
16452 break;
16454 if (type && cxx_dialect < cxx11
16455 && itk > itk_unsigned_long)
16456 pedwarn (input_location, OPT_Wlong_long,
16457 pos ? G_("\
16458 incremented enumerator value is too large for %<unsigned long%>") : G_("\
16459 incremented enumerator value is too large for %<long%>"));
16461 if (type == NULL_TREE)
16462 overflowed = wi::OVF_UNKNOWN;
16463 else
16464 value = wide_int_to_tree (type, wi);
16467 if (overflowed)
16469 error ("overflow in enumeration values at %qD", name);
16470 value = error_mark_node;
16474 else
16475 value = integer_zero_node;
16478 /* Remove no-op casts from the value. */
16479 STRIP_TYPE_NOPS (value);
16481 /* If the underlying type of the enum is fixed, check whether
16482 the enumerator values fits in the underlying type. If it
16483 does not fit, the program is ill-formed [C++0x dcl.enum]. */
16484 if (ENUM_UNDERLYING_TYPE (enumtype)
16485 && value
16486 && TREE_CODE (value) == INTEGER_CST)
16488 if (!int_fits_type_p (value, ENUM_UNDERLYING_TYPE (enumtype)))
16489 error ("enumerator value %qE is outside the range of underlying "
16490 "type %qT", value, ENUM_UNDERLYING_TYPE (enumtype));
16492 /* Convert the value to the appropriate type. */
16493 value = fold_convert (ENUM_UNDERLYING_TYPE (enumtype), value);
16497 /* C++ associates enums with global, function, or class declarations. */
16498 context = current_scope ();
16500 /* Build the actual enumeration constant. Note that the enumeration
16501 constants have the underlying type of the enum (if it is fixed)
16502 or the type of their initializer (if the underlying type of the
16503 enum is not fixed):
16505 [ C++0x dcl.enum ]
16507 If the underlying type is fixed, the type of each enumerator
16508 prior to the closing brace is the underlying type; if the
16509 initializing value of an enumerator cannot be represented by
16510 the underlying type, the program is ill-formed. If the
16511 underlying type is not fixed, the type of each enumerator is
16512 the type of its initializing value.
16514 If the underlying type is not fixed, it will be computed by
16515 finish_enum and we will reset the type of this enumerator. Of
16516 course, if we're processing a template, there may be no value. */
16517 type = value ? TREE_TYPE (value) : NULL_TREE;
16519 decl = build_decl (loc, CONST_DECL, name, type);
16521 DECL_CONTEXT (decl) = enumtype;
16522 TREE_CONSTANT (decl) = 1;
16523 TREE_READONLY (decl) = 1;
16524 DECL_INITIAL (decl) = value;
16526 if (attributes)
16527 cplus_decl_attributes (&decl, attributes, 0);
16529 if (context && context == current_class_type && !SCOPED_ENUM_P (enumtype))
16531 /* In something like `struct S { enum E { i = 7 }; };' we put `i'
16532 on the TYPE_FIELDS list for `S'. (That's so that you can say
16533 things like `S::i' later.) */
16535 /* The enumerator may be getting declared outside of its enclosing
16536 class, like so:
16538 class S { public: enum E : int; }; enum S::E : int { i = 7; };
16540 For which case we need to make sure that the access of `S::i'
16541 matches the access of `S::E'. */
16542 auto cas = make_temp_override (current_access_specifier);
16543 set_current_access_from_decl (TYPE_NAME (enumtype));
16544 finish_member_declaration (decl);
16546 else
16547 pushdecl (decl);
16549 /* Add this enumeration constant to the list for this type. */
16550 TYPE_VALUES (enumtype) = tree_cons (name, decl, TYPE_VALUES (enumtype));
16553 /* Look for an enumerator with the given NAME within the enumeration
16554 type ENUMTYPE. This routine is used primarily for qualified name
16555 lookup into an enumerator in C++0x, e.g.,
16557 enum class Color { Red, Green, Blue };
16559 Color color = Color::Red;
16561 Returns the value corresponding to the enumerator, or
16562 NULL_TREE if no such enumerator was found. */
16563 tree
16564 lookup_enumerator (tree enumtype, tree name)
16566 tree e;
16567 gcc_assert (enumtype && TREE_CODE (enumtype) == ENUMERAL_TYPE);
16569 e = purpose_member (name, TYPE_VALUES (enumtype));
16570 return e? TREE_VALUE (e) : NULL_TREE;
16573 /* Implement LANG_HOOKS_SIMULATE_ENUM_DECL. */
16575 tree
16576 cxx_simulate_enum_decl (location_t loc, const char *name,
16577 vec<string_int_pair> *values)
16579 location_t saved_loc = input_location;
16580 input_location = loc;
16582 tree enumtype = start_enum (get_identifier (name), NULL_TREE, NULL_TREE,
16583 NULL_TREE, false, NULL);
16584 if (!OPAQUE_ENUM_P (enumtype))
16586 error_at (loc, "multiple definition of %q#T", enumtype);
16587 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
16588 "previous definition here");
16589 return enumtype;
16591 SET_OPAQUE_ENUM_P (enumtype, false);
16592 DECL_SOURCE_LOCATION (TYPE_NAME (enumtype)) = loc;
16594 for (const string_int_pair &value : values)
16595 build_enumerator (get_identifier (value.first),
16596 build_int_cst (integer_type_node, value.second),
16597 enumtype, NULL_TREE, loc);
16599 finish_enum_value_list (enumtype);
16600 finish_enum (enumtype);
16602 input_location = saved_loc;
16603 return enumtype;
16606 /* Implement LANG_HOOKS_SIMULATE_RECORD_DECL. */
16608 tree
16609 cxx_simulate_record_decl (location_t loc, const char *name,
16610 array_slice<const tree> fields)
16612 iloc_sentinel ils (loc);
16614 tree ident = get_identifier (name);
16615 tree type = xref_tag (/*tag_code=*/record_type, ident);
16616 if (type != error_mark_node
16617 && (TREE_CODE (type) != RECORD_TYPE || COMPLETE_TYPE_P (type)))
16619 error ("redefinition of %q#T", type);
16620 type = error_mark_node;
16622 if (type == error_mark_node)
16623 return lhd_simulate_record_decl (loc, name, fields);
16625 xref_basetypes (type, NULL_TREE);
16626 type = begin_class_definition (type);
16627 if (type == error_mark_node)
16628 return lhd_simulate_record_decl (loc, name, fields);
16630 for (tree field : fields)
16631 finish_member_declaration (field);
16633 type = finish_struct (type, NULL_TREE);
16635 tree decl = build_decl (loc, TYPE_DECL, ident, type);
16636 set_underlying_type (decl);
16637 lang_hooks.decls.pushdecl (decl);
16639 return type;
16642 /* We're defining DECL. Make sure that its type is OK. */
16644 static void
16645 check_function_type (tree decl, tree current_function_parms)
16647 tree fntype = TREE_TYPE (decl);
16648 tree return_type = complete_type (TREE_TYPE (fntype));
16650 /* In a function definition, arg types must be complete. */
16651 require_complete_types_for_parms (current_function_parms);
16653 if (dependent_type_p (return_type)
16654 || type_uses_auto (return_type))
16655 return;
16656 if (!COMPLETE_OR_VOID_TYPE_P (return_type))
16658 tree args = TYPE_ARG_TYPES (fntype);
16660 error ("return type %q#T is incomplete", return_type);
16662 /* Make it return void instead. */
16663 if (TREE_CODE (fntype) == METHOD_TYPE)
16664 fntype = build_method_type_directly (TREE_TYPE (TREE_VALUE (args)),
16665 void_type_node,
16666 TREE_CHAIN (args));
16667 else
16668 fntype = build_function_type (void_type_node, args);
16669 fntype = (cp_build_type_attribute_variant
16670 (fntype, TYPE_ATTRIBUTES (TREE_TYPE (decl))));
16671 fntype = cxx_copy_lang_qualifiers (fntype, TREE_TYPE (decl));
16672 TREE_TYPE (decl) = fntype;
16674 else
16676 abstract_virtuals_error (decl, TREE_TYPE (fntype));
16677 maybe_warn_parm_abi (TREE_TYPE (fntype),
16678 DECL_SOURCE_LOCATION (decl));
16682 /* True iff FN is an implicitly-defined default constructor. */
16684 static bool
16685 implicit_default_ctor_p (tree fn)
16687 return (DECL_CONSTRUCTOR_P (fn)
16688 && !user_provided_p (fn)
16689 && sufficient_parms_p (FUNCTION_FIRST_USER_PARMTYPE (fn)));
16692 /* Clobber the contents of *this to let the back end know that the object
16693 storage is dead when we enter the constructor or leave the destructor. */
16695 static tree
16696 build_clobber_this ()
16698 /* Clobbering an empty base is pointless, and harmful if its one byte
16699 TYPE_SIZE overlays real data. */
16700 if (is_empty_class (current_class_type))
16701 return void_node;
16703 /* If we have virtual bases, clobber the whole object, but only if we're in
16704 charge. If we don't have virtual bases, clobber the as-base type so we
16705 don't mess with tail padding. */
16706 bool vbases = CLASSTYPE_VBASECLASSES (current_class_type);
16708 tree ctype = current_class_type;
16709 if (!vbases)
16710 ctype = CLASSTYPE_AS_BASE (ctype);
16712 tree clobber = build_clobber (ctype);
16714 tree thisref = current_class_ref;
16715 if (ctype != current_class_type)
16717 thisref = build_nop (build_reference_type (ctype), current_class_ptr);
16718 thisref = convert_from_reference (thisref);
16721 tree exprstmt = build2 (MODIFY_EXPR, void_type_node, thisref, clobber);
16722 if (vbases)
16723 exprstmt = build_if_in_charge (exprstmt);
16725 return exprstmt;
16728 /* Create the FUNCTION_DECL for a function definition.
16729 DECLSPECS and DECLARATOR are the parts of the declaration;
16730 they describe the function's name and the type it returns,
16731 but twisted together in a fashion that parallels the syntax of C.
16733 FLAGS is a bitwise or of SF_PRE_PARSED (indicating that the
16734 DECLARATOR is really the DECL for the function we are about to
16735 process and that DECLSPECS should be ignored), SF_INCLASS_INLINE
16736 indicating that the function is an inline defined in-class.
16738 This function creates a binding context for the function body
16739 as well as setting up the FUNCTION_DECL in current_function_decl.
16741 For C++, we must first check whether that datum makes any sense.
16742 For example, "class A local_a(1,2);" means that variable local_a
16743 is an aggregate of type A, which should have a constructor
16744 applied to it with the argument list [1, 2].
16746 On entry, DECL_INITIAL (decl1) should be NULL_TREE or error_mark_node,
16747 or may be a BLOCK if the function has been defined previously
16748 in this translation unit. On exit, DECL_INITIAL (decl1) will be
16749 error_mark_node if the function has never been defined, or
16750 a BLOCK if the function has been defined somewhere. */
16752 bool
16753 start_preparsed_function (tree decl1, tree attrs, int flags)
16755 tree ctype = NULL_TREE;
16756 bool doing_friend = false;
16758 /* Sanity check. */
16759 gcc_assert (VOID_TYPE_P (TREE_VALUE (void_list_node)));
16760 gcc_assert (TREE_CHAIN (void_list_node) == NULL_TREE);
16762 tree fntype = TREE_TYPE (decl1);
16763 if (TREE_CODE (fntype) == METHOD_TYPE)
16764 ctype = TYPE_METHOD_BASETYPE (fntype);
16765 else
16767 ctype = DECL_FRIEND_CONTEXT (decl1);
16769 if (ctype)
16770 doing_friend = true;
16773 if (DECL_DECLARED_INLINE_P (decl1)
16774 && lookup_attribute ("noinline", attrs))
16775 warning_at (DECL_SOURCE_LOCATION (decl1), 0,
16776 "inline function %qD given attribute %qs", decl1, "noinline");
16778 /* Handle gnu_inline attribute. */
16779 if (GNU_INLINE_P (decl1))
16781 DECL_EXTERNAL (decl1) = 1;
16782 DECL_NOT_REALLY_EXTERN (decl1) = 0;
16783 DECL_INTERFACE_KNOWN (decl1) = 1;
16784 DECL_DISREGARD_INLINE_LIMITS (decl1) = 1;
16787 if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (decl1))
16788 /* This is a constructor, we must ensure that any default args
16789 introduced by this definition are propagated to the clones
16790 now. The clones are used directly in overload resolution. */
16791 adjust_clone_args (decl1);
16793 /* Sometimes we don't notice that a function is a static member, and
16794 build a METHOD_TYPE for it. Fix that up now. */
16795 gcc_assert (!(ctype != NULL_TREE && DECL_STATIC_FUNCTION_P (decl1)
16796 && TREE_CODE (TREE_TYPE (decl1)) == METHOD_TYPE));
16798 /* Set up current_class_type, and enter the scope of the class, if
16799 appropriate. */
16800 if (ctype)
16801 push_nested_class (ctype);
16802 else if (DECL_STATIC_FUNCTION_P (decl1))
16803 push_nested_class (DECL_CONTEXT (decl1));
16805 /* Now that we have entered the scope of the class, we must restore
16806 the bindings for any template parameters surrounding DECL1, if it
16807 is an inline member template. (Order is important; consider the
16808 case where a template parameter has the same name as a field of
16809 the class.) It is not until after this point that
16810 PROCESSING_TEMPLATE_DECL is guaranteed to be set up correctly. */
16811 if (flags & SF_INCLASS_INLINE)
16812 maybe_begin_member_template_processing (decl1);
16814 /* Effective C++ rule 15. */
16815 if (warn_ecpp
16816 && DECL_ASSIGNMENT_OPERATOR_P (decl1)
16817 && DECL_OVERLOADED_OPERATOR_IS (decl1, NOP_EXPR)
16818 && VOID_TYPE_P (TREE_TYPE (fntype)))
16819 warning (OPT_Weffc__,
16820 "%<operator=%> should return a reference to %<*this%>");
16822 /* Make the init_value nonzero so pushdecl knows this is not tentative.
16823 error_mark_node is replaced below (in poplevel) with the BLOCK. */
16824 if (!DECL_INITIAL (decl1))
16825 DECL_INITIAL (decl1) = error_mark_node;
16827 /* This function exists in static storage.
16828 (This does not mean `static' in the C sense!) */
16829 TREE_STATIC (decl1) = 1;
16831 /* We must call push_template_decl after current_class_type is set
16832 up. (If we are processing inline definitions after exiting a
16833 class scope, current_class_type will be NULL_TREE until set above
16834 by push_nested_class.) */
16835 if (processing_template_decl)
16837 tree newdecl1 = push_template_decl (decl1, doing_friend);
16838 if (newdecl1 == error_mark_node)
16840 if (ctype || DECL_STATIC_FUNCTION_P (decl1))
16841 pop_nested_class ();
16842 return false;
16844 decl1 = newdecl1;
16847 /* Make sure the parameter and return types are reasonable. When
16848 you declare a function, these types can be incomplete, but they
16849 must be complete when you define the function. */
16850 check_function_type (decl1, DECL_ARGUMENTS (decl1));
16852 /* Build the return declaration for the function. */
16853 tree restype = TREE_TYPE (fntype);
16855 if (DECL_RESULT (decl1) == NULL_TREE)
16857 tree resdecl;
16859 resdecl = build_decl (input_location, RESULT_DECL, 0, restype);
16860 DECL_ARTIFICIAL (resdecl) = 1;
16861 DECL_IGNORED_P (resdecl) = 1;
16862 DECL_RESULT (decl1) = resdecl;
16864 cp_apply_type_quals_to_decl (cp_type_quals (restype), resdecl);
16867 /* Record the decl so that the function name is defined.
16868 If we already have a decl for this name, and it is a FUNCTION_DECL,
16869 use the old decl. */
16870 if (!processing_template_decl && !(flags & SF_PRE_PARSED))
16872 /* A specialization is not used to guide overload resolution. */
16873 if (!DECL_FUNCTION_MEMBER_P (decl1)
16874 && !(DECL_USE_TEMPLATE (decl1) &&
16875 PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl1))))
16877 tree olddecl = pushdecl (decl1);
16879 if (olddecl == error_mark_node)
16880 /* If something went wrong when registering the declaration,
16881 use DECL1; we have to have a FUNCTION_DECL to use when
16882 parsing the body of the function. */
16884 else
16886 /* Otherwise, OLDDECL is either a previous declaration
16887 of the same function or DECL1 itself. */
16889 if (warn_missing_declarations
16890 && olddecl == decl1
16891 && !DECL_MAIN_P (decl1)
16892 && TREE_PUBLIC (decl1)
16893 && !DECL_DECLARED_INLINE_P (decl1))
16895 tree context;
16897 /* Check whether DECL1 is in an anonymous
16898 namespace. */
16899 for (context = DECL_CONTEXT (decl1);
16900 context;
16901 context = DECL_CONTEXT (context))
16903 if (TREE_CODE (context) == NAMESPACE_DECL
16904 && DECL_NAME (context) == NULL_TREE)
16905 break;
16908 if (context == NULL)
16909 warning_at (DECL_SOURCE_LOCATION (decl1),
16910 OPT_Wmissing_declarations,
16911 "no previous declaration for %qD", decl1);
16914 decl1 = olddecl;
16917 else
16919 /* We need to set the DECL_CONTEXT. */
16920 if (!DECL_CONTEXT (decl1) && DECL_TEMPLATE_INFO (decl1))
16921 DECL_CONTEXT (decl1) = DECL_CONTEXT (DECL_TI_TEMPLATE (decl1));
16923 fntype = TREE_TYPE (decl1);
16924 restype = TREE_TYPE (fntype);
16926 /* If #pragma weak applies, mark the decl appropriately now.
16927 The pragma only applies to global functions. Because
16928 determining whether or not the #pragma applies involves
16929 computing the mangled name for the declaration, we cannot
16930 apply the pragma until after we have merged this declaration
16931 with any previous declarations; if the original declaration
16932 has a linkage specification, that specification applies to
16933 the definition as well, and may affect the mangled name. */
16934 if (DECL_FILE_SCOPE_P (decl1))
16935 maybe_apply_pragma_weak (decl1);
16938 /* We are now in the scope of the function being defined. */
16939 current_function_decl = decl1;
16941 /* Save the parm names or decls from this function's declarator
16942 where store_parm_decls will find them. */
16943 tree current_function_parms = DECL_ARGUMENTS (decl1);
16945 /* Let the user know we're compiling this function. */
16946 announce_function (decl1);
16948 gcc_assert (DECL_INITIAL (decl1));
16950 /* This function may already have been parsed, in which case just
16951 return; our caller will skip over the body without parsing. */
16952 if (DECL_INITIAL (decl1) != error_mark_node)
16953 return true;
16955 /* Initialize RTL machinery. We cannot do this until
16956 CURRENT_FUNCTION_DECL and DECL_RESULT are set up. We do this
16957 even when processing a template; this is how we get
16958 CFUN set up, and our per-function variables initialized.
16959 FIXME factor out the non-RTL stuff. */
16960 cp_binding_level *bl = current_binding_level;
16961 allocate_struct_function (decl1, processing_template_decl);
16963 /* Initialize the language data structures. Whenever we start
16964 a new function, we destroy temporaries in the usual way. */
16965 cfun->language = ggc_cleared_alloc<language_function> ();
16966 current_stmt_tree ()->stmts_are_full_exprs_p = 1;
16967 current_binding_level = bl;
16969 /* If we are (erroneously) defining a function that we have already
16970 defined before, wipe out what we knew before. */
16971 gcc_checking_assert (!DECL_PENDING_INLINE_P (decl1));
16972 FNDECL_USED_AUTO (decl1) = false;
16973 DECL_SAVED_AUTO_RETURN_TYPE (decl1) = NULL;
16975 if (!processing_template_decl && type_uses_auto (restype))
16977 FNDECL_USED_AUTO (decl1) = true;
16978 DECL_SAVED_AUTO_RETURN_TYPE (decl1) = restype;
16981 /* Start the statement-tree, start the tree now. */
16982 DECL_SAVED_TREE (decl1) = push_stmt_list ();
16984 if (ctype && !doing_friend && !DECL_STATIC_FUNCTION_P (decl1))
16986 /* We know that this was set up by `grokclassfn'. We do not
16987 wait until `store_parm_decls', since evil parse errors may
16988 never get us to that point. Here we keep the consistency
16989 between `current_class_type' and `current_class_ptr'. */
16990 tree t = DECL_ARGUMENTS (decl1);
16992 gcc_assert (t != NULL_TREE && TREE_CODE (t) == PARM_DECL);
16993 gcc_assert (TYPE_PTR_P (TREE_TYPE (t)));
16995 cp_function_chain->x_current_class_ref
16996 = cp_build_fold_indirect_ref (t);
16997 /* Set this second to avoid shortcut in cp_build_indirect_ref. */
16998 cp_function_chain->x_current_class_ptr = t;
17000 /* Constructors and destructors need to know whether they're "in
17001 charge" of initializing virtual base classes. */
17002 t = DECL_CHAIN (t);
17003 if (DECL_HAS_IN_CHARGE_PARM_P (decl1))
17005 current_in_charge_parm = t;
17006 t = DECL_CHAIN (t);
17008 if (DECL_HAS_VTT_PARM_P (decl1))
17010 gcc_assert (DECL_NAME (t) == vtt_parm_identifier);
17011 current_vtt_parm = t;
17015 bool honor_interface = (!DECL_TEMPLATE_INSTANTIATION (decl1)
17016 /* Implicitly-defined methods (like the
17017 destructor for a class in which no destructor
17018 is explicitly declared) must not be defined
17019 until their definition is needed. So, we
17020 ignore interface specifications for
17021 compiler-generated functions. */
17022 && !DECL_ARTIFICIAL (decl1));
17023 struct c_fileinfo *finfo
17024 = get_fileinfo (LOCATION_FILE (DECL_SOURCE_LOCATION (decl1)));
17026 if (processing_template_decl)
17027 /* Don't mess with interface flags. */;
17028 else if (DECL_INTERFACE_KNOWN (decl1))
17030 tree ctx = decl_function_context (decl1);
17032 if (DECL_NOT_REALLY_EXTERN (decl1))
17033 DECL_EXTERNAL (decl1) = 0;
17035 if (ctx != NULL_TREE && vague_linkage_p (ctx))
17036 /* This is a function in a local class in an extern inline
17037 or template function. */
17038 comdat_linkage (decl1);
17040 /* If this function belongs to an interface, it is public.
17041 If it belongs to someone else's interface, it is also external.
17042 This only affects inlines and template instantiations. */
17043 else if (!finfo->interface_unknown && honor_interface)
17045 if (DECL_DECLARED_INLINE_P (decl1)
17046 || DECL_TEMPLATE_INSTANTIATION (decl1))
17048 DECL_EXTERNAL (decl1)
17049 = (finfo->interface_only
17050 || (DECL_DECLARED_INLINE_P (decl1)
17051 && ! flag_implement_inlines
17052 && !DECL_VINDEX (decl1)));
17054 /* For WIN32 we also want to put these in linkonce sections. */
17055 maybe_make_one_only (decl1);
17057 else
17058 DECL_EXTERNAL (decl1) = 0;
17059 DECL_INTERFACE_KNOWN (decl1) = 1;
17060 /* If this function is in an interface implemented in this file,
17061 make sure that the back end knows to emit this function
17062 here. */
17063 if (!DECL_EXTERNAL (decl1))
17064 mark_needed (decl1);
17066 else if (finfo->interface_unknown && finfo->interface_only
17067 && honor_interface)
17069 /* If MULTIPLE_SYMBOL_SPACES is defined and we saw a #pragma
17070 interface, we will have both finfo->interface_unknown and
17071 finfo->interface_only set. In that case, we don't want to
17072 use the normal heuristics because someone will supply a
17073 #pragma implementation elsewhere, and deducing it here would
17074 produce a conflict. */
17075 comdat_linkage (decl1);
17076 DECL_EXTERNAL (decl1) = 0;
17077 DECL_INTERFACE_KNOWN (decl1) = 1;
17078 DECL_DEFER_OUTPUT (decl1) = 1;
17080 else
17082 /* This is a definition, not a reference.
17083 So clear DECL_EXTERNAL, unless this is a GNU extern inline. */
17084 if (!GNU_INLINE_P (decl1))
17085 DECL_EXTERNAL (decl1) = 0;
17087 if ((DECL_DECLARED_INLINE_P (decl1)
17088 || DECL_TEMPLATE_INSTANTIATION (decl1))
17089 && ! DECL_INTERFACE_KNOWN (decl1))
17090 DECL_DEFER_OUTPUT (decl1) = 1;
17091 else
17092 DECL_INTERFACE_KNOWN (decl1) = 1;
17095 /* Determine the ELF visibility attribute for the function. We must not
17096 do this before calling "pushdecl", as we must allow "duplicate_decls"
17097 to merge any attributes appropriately. We also need to wait until
17098 linkage is set. */
17099 if (!DECL_CLONED_FUNCTION_P (decl1))
17100 determine_visibility (decl1);
17102 if (!processing_template_decl)
17103 maybe_instantiate_noexcept (decl1);
17105 begin_scope (sk_function_parms, decl1);
17107 ++function_depth;
17109 if (DECL_DESTRUCTOR_P (decl1)
17110 || (DECL_CONSTRUCTOR_P (decl1)
17111 && targetm.cxx.cdtor_returns_this ()))
17113 cdtor_label = create_artificial_label (input_location);
17114 LABEL_DECL_CDTOR (cdtor_label) = true;
17117 start_fname_decls ();
17119 store_parm_decls (current_function_parms);
17121 push_operator_bindings ();
17123 if (!processing_template_decl
17124 && (flag_lifetime_dse > 1)
17125 && DECL_CONSTRUCTOR_P (decl1)
17126 && !DECL_CLONED_FUNCTION_P (decl1)
17127 /* Clobbering an empty base is harmful if it overlays real data. */
17128 && !is_empty_class (current_class_type)
17129 /* We can't clobber safely for an implicitly-defined default constructor
17130 because part of the initialization might happen before we enter the
17131 constructor, via AGGR_INIT_ZERO_FIRST (c++/68006). */
17132 && !implicit_default_ctor_p (decl1))
17133 finish_expr_stmt (build_clobber_this ());
17135 if (!processing_template_decl
17136 && DECL_CONSTRUCTOR_P (decl1)
17137 && sanitize_flags_p (SANITIZE_VPTR)
17138 && !DECL_CLONED_FUNCTION_P (decl1)
17139 && !implicit_default_ctor_p (decl1))
17140 cp_ubsan_maybe_initialize_vtbl_ptrs (current_class_ptr);
17142 if (!DECL_OMP_DECLARE_REDUCTION_P (decl1))
17143 start_lambda_scope (decl1);
17145 return true;
17149 /* Like start_preparsed_function, except that instead of a
17150 FUNCTION_DECL, this function takes DECLSPECS and DECLARATOR.
17152 Returns true on success. If the DECLARATOR is not suitable
17153 for a function, we return false, which tells the parser to
17154 skip the entire function. */
17156 bool
17157 start_function (cp_decl_specifier_seq *declspecs,
17158 const cp_declarator *declarator,
17159 tree attrs)
17161 tree decl1;
17163 decl1 = grokdeclarator (declarator, declspecs, FUNCDEF, 1, &attrs);
17164 invoke_plugin_callbacks (PLUGIN_START_PARSE_FUNCTION, decl1);
17165 if (decl1 == error_mark_node)
17166 return false;
17168 if (DECL_MAIN_P (decl1))
17169 /* main must return int. grokfndecl should have corrected it
17170 (and issued a diagnostic) if the user got it wrong. */
17171 gcc_assert (same_type_p (TREE_TYPE (TREE_TYPE (decl1)),
17172 integer_type_node));
17174 return start_preparsed_function (decl1, attrs, /*flags=*/SF_DEFAULT);
17177 /* Returns true iff an EH_SPEC_BLOCK should be created in the body of
17178 FN. */
17180 static bool
17181 use_eh_spec_block (tree fn)
17183 return (flag_exceptions && flag_enforce_eh_specs
17184 && !processing_template_decl
17185 /* We insert the EH_SPEC_BLOCK only in the original
17186 function; then, it is copied automatically to the
17187 clones. */
17188 && !DECL_CLONED_FUNCTION_P (fn)
17189 /* Implicitly-generated constructors and destructors have
17190 exception specifications. However, those specifications
17191 are the union of the possible exceptions specified by the
17192 constructors/destructors for bases and members, so no
17193 unallowed exception will ever reach this function. By
17194 not creating the EH_SPEC_BLOCK we save a little memory,
17195 and we avoid spurious warnings about unreachable
17196 code. */
17197 && !DECL_DEFAULTED_FN (fn)
17198 && !type_throw_all_p (TREE_TYPE (fn)));
17201 /* Helper function to push ARGS into the current lexical scope. DECL
17202 is the function declaration. NONPARMS is used to handle enum
17203 constants. */
17205 void
17206 do_push_parm_decls (tree decl, tree args, tree *nonparms)
17208 /* If we're doing semantic analysis, then we'll call pushdecl
17209 for each of these. We must do them in reverse order so that
17210 they end in the correct forward order. */
17211 args = nreverse (args);
17213 tree next;
17214 for (tree parm = args; parm; parm = next)
17216 next = DECL_CHAIN (parm);
17217 if (TREE_CODE (parm) == PARM_DECL)
17218 pushdecl (parm);
17219 else if (nonparms)
17221 /* If we find an enum constant or a type tag, put it aside for
17222 the moment. */
17223 TREE_CHAIN (parm) = NULL_TREE;
17224 *nonparms = chainon (*nonparms, parm);
17228 /* Get the decls in their original chain order and record in the
17229 function. This is all and only the PARM_DECLs that were
17230 pushed into scope by the loop above. */
17231 DECL_ARGUMENTS (decl) = get_local_decls ();
17234 /* Store the parameter declarations into the current function declaration.
17235 This is called after parsing the parameter declarations, before
17236 digesting the body of the function.
17238 Also install to binding contour return value identifier, if any. */
17240 static void
17241 store_parm_decls (tree current_function_parms)
17243 tree fndecl = current_function_decl;
17245 /* This is a chain of any other decls that came in among the parm
17246 declarations. If a parm is declared with enum {foo, bar} x;
17247 then CONST_DECLs for foo and bar are put here. */
17248 tree nonparms = NULL_TREE;
17250 if (current_function_parms)
17252 /* This case is when the function was defined with an ANSI prototype.
17253 The parms already have decls, so we need not do anything here
17254 except record them as in effect
17255 and complain if any redundant old-style parm decls were written. */
17257 tree specparms = current_function_parms;
17259 /* Must clear this because it might contain TYPE_DECLs declared
17260 at class level. */
17261 current_binding_level->names = NULL;
17263 do_push_parm_decls (fndecl, specparms, &nonparms);
17265 else
17266 DECL_ARGUMENTS (fndecl) = NULL_TREE;
17268 /* Now store the final chain of decls for the arguments
17269 as the decl-chain of the current lexical scope.
17270 Put the enumerators in as well, at the front so that
17271 DECL_ARGUMENTS is not modified. */
17272 current_binding_level->names = chainon (nonparms, DECL_ARGUMENTS (fndecl));
17274 if (use_eh_spec_block (current_function_decl))
17275 current_eh_spec_block = begin_eh_spec_block ();
17279 /* Set the return value of the constructor (if present). */
17281 static void
17282 finish_constructor_body (void)
17284 tree val;
17285 tree exprstmt;
17287 if (targetm.cxx.cdtor_returns_this ())
17289 /* Any return from a constructor will end up here. */
17290 add_stmt (build_stmt (input_location, LABEL_EXPR, cdtor_label));
17292 val = DECL_ARGUMENTS (current_function_decl);
17293 val = build2 (MODIFY_EXPR, TREE_TYPE (val),
17294 DECL_RESULT (current_function_decl), val);
17295 /* Return the address of the object. */
17296 exprstmt = build_stmt (input_location, RETURN_EXPR, val);
17297 add_stmt (exprstmt);
17301 /* Do all the processing for the beginning of a destructor; set up the
17302 vtable pointers and cleanups for bases and members. */
17304 static void
17305 begin_destructor_body (void)
17307 tree compound_stmt;
17309 /* If the CURRENT_CLASS_TYPE is incomplete, we will have already
17310 issued an error message. We still want to try to process the
17311 body of the function, but initialize_vtbl_ptrs will crash if
17312 TYPE_BINFO is NULL. */
17313 if (COMPLETE_TYPE_P (current_class_type))
17315 compound_stmt = begin_compound_stmt (0);
17316 /* Make all virtual function table pointers in non-virtual base
17317 classes point to CURRENT_CLASS_TYPE's virtual function
17318 tables. */
17319 initialize_vtbl_ptrs (current_class_ptr);
17320 finish_compound_stmt (compound_stmt);
17322 if (flag_lifetime_dse
17323 /* Clobbering an empty base is harmful if it overlays real data. */
17324 && !is_empty_class (current_class_type))
17326 if (sanitize_flags_p (SANITIZE_VPTR)
17327 && (flag_sanitize_recover & SANITIZE_VPTR) == 0
17328 && TYPE_CONTAINS_VPTR_P (current_class_type))
17330 tree binfo = TYPE_BINFO (current_class_type);
17331 tree ref
17332 = cp_build_fold_indirect_ref (current_class_ptr);
17334 tree vtbl_ptr = build_vfield_ref (ref, TREE_TYPE (binfo));
17335 tree vtbl = build_zero_cst (TREE_TYPE (vtbl_ptr));
17336 tree stmt = cp_build_modify_expr (input_location, vtbl_ptr,
17337 NOP_EXPR, vtbl,
17338 tf_warning_or_error);
17339 /* If the vptr is shared with some virtual nearly empty base,
17340 don't clear it if not in charge, the dtor of the virtual
17341 nearly empty base will do that later. */
17342 if (CLASSTYPE_VBASECLASSES (current_class_type))
17344 tree c = current_class_type;
17345 while (CLASSTYPE_PRIMARY_BINFO (c))
17347 if (BINFO_VIRTUAL_P (CLASSTYPE_PRIMARY_BINFO (c)))
17349 stmt = convert_to_void (stmt, ICV_STATEMENT,
17350 tf_warning_or_error);
17351 stmt = build_if_in_charge (stmt);
17352 break;
17354 c = BINFO_TYPE (CLASSTYPE_PRIMARY_BINFO (c));
17357 finish_decl_cleanup (NULL_TREE, stmt);
17359 else
17360 finish_decl_cleanup (NULL_TREE, build_clobber_this ());
17363 /* And insert cleanups for our bases and members so that they
17364 will be properly destroyed if we throw. */
17365 push_base_cleanups ();
17369 /* At the end of every destructor we generate code to delete the object if
17370 necessary. Do that now. */
17372 static void
17373 finish_destructor_body (void)
17375 tree exprstmt;
17377 /* Any return from a destructor will end up here; that way all base
17378 and member cleanups will be run when the function returns. */
17379 add_stmt (build_stmt (input_location, LABEL_EXPR, cdtor_label));
17381 if (targetm.cxx.cdtor_returns_this ())
17383 tree val;
17385 val = DECL_ARGUMENTS (current_function_decl);
17386 val = build2 (MODIFY_EXPR, TREE_TYPE (val),
17387 DECL_RESULT (current_function_decl), val);
17388 /* Return the address of the object. */
17389 exprstmt = build_stmt (input_location, RETURN_EXPR, val);
17390 add_stmt (exprstmt);
17394 /* Do the necessary processing for the beginning of a function body, which
17395 in this case includes member-initializers, but not the catch clauses of
17396 a function-try-block. Currently, this means opening a binding level
17397 for the member-initializers (in a ctor), member cleanups (in a dtor),
17398 and capture proxies (in a lambda operator()). */
17400 tree
17401 begin_function_body (void)
17403 if (! FUNCTION_NEEDS_BODY_BLOCK (current_function_decl))
17404 return NULL_TREE;
17406 if (processing_template_decl)
17407 /* Do nothing now. */;
17408 else
17409 /* Always keep the BLOCK node associated with the outermost pair of
17410 curly braces of a function. These are needed for correct
17411 operation of dwarfout.c. */
17412 keep_next_level (true);
17414 tree stmt = begin_compound_stmt (BCS_FN_BODY);
17416 if (processing_template_decl)
17417 /* Do nothing now. */;
17418 else if (DECL_DESTRUCTOR_P (current_function_decl))
17419 begin_destructor_body ();
17421 return stmt;
17424 /* Do the processing for the end of a function body. Currently, this means
17425 closing out the cleanups for fully-constructed bases and members, and in
17426 the case of the destructor, deleting the object if desired. Again, this
17427 is only meaningful for [cd]tors, since they are the only functions where
17428 there is a significant distinction between the main body and any
17429 function catch clauses. Handling, say, main() return semantics here
17430 would be wrong, as flowing off the end of a function catch clause for
17431 main() would also need to return 0. */
17433 void
17434 finish_function_body (tree compstmt)
17436 if (compstmt == NULL_TREE)
17437 return;
17439 /* Close the block. */
17440 finish_compound_stmt (compstmt);
17442 if (processing_template_decl)
17443 /* Do nothing now. */;
17444 else if (DECL_CONSTRUCTOR_P (current_function_decl))
17445 finish_constructor_body ();
17446 else if (DECL_DESTRUCTOR_P (current_function_decl))
17447 finish_destructor_body ();
17450 /* Given a function, returns the BLOCK corresponding to the outermost level
17451 of curly braces, skipping the artificial block created for constructor
17452 initializers. */
17454 tree
17455 outer_curly_brace_block (tree fndecl)
17457 tree block = DECL_INITIAL (fndecl);
17458 if (BLOCK_OUTER_CURLY_BRACE_P (block))
17459 return block;
17460 block = BLOCK_SUBBLOCKS (block);
17461 if (BLOCK_OUTER_CURLY_BRACE_P (block))
17462 return block;
17463 block = BLOCK_SUBBLOCKS (block);
17464 gcc_assert (BLOCK_OUTER_CURLY_BRACE_P (block));
17465 return block;
17468 /* If FNDECL is a class's key method, add the class to the list of
17469 keyed classes that should be emitted. */
17471 static void
17472 record_key_method_defined (tree fndecl)
17474 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
17475 && DECL_VIRTUAL_P (fndecl)
17476 && !processing_template_decl)
17478 tree fnclass = DECL_CONTEXT (fndecl);
17479 if (fndecl == CLASSTYPE_KEY_METHOD (fnclass))
17480 vec_safe_push (keyed_classes, fnclass);
17484 /* Attempt to add a fix-it hint to RICHLOC suggesting the insertion
17485 of "return *this;" immediately before its location, using FNDECL's
17486 first statement (if any) to give the indentation, if appropriate. */
17488 static void
17489 add_return_star_this_fixit (gcc_rich_location *richloc, tree fndecl)
17491 location_t indent = UNKNOWN_LOCATION;
17492 tree stmts = expr_first (DECL_SAVED_TREE (fndecl));
17493 if (stmts)
17494 indent = EXPR_LOCATION (stmts);
17495 richloc->add_fixit_insert_formatted ("return *this;",
17496 richloc->get_loc (),
17497 indent);
17500 /* This function carries out the subset of finish_function operations needed
17501 to emit the compiler-generated outlined helper functions used by the
17502 coroutines implementation. */
17504 static void
17505 emit_coro_helper (tree helper)
17507 /* This is a partial set of the operations done by finish_function()
17508 plus emitting the result. */
17509 set_cfun (NULL);
17510 current_function_decl = helper;
17511 begin_scope (sk_function_parms, NULL);
17512 store_parm_decls (DECL_ARGUMENTS (helper));
17513 announce_function (helper);
17514 allocate_struct_function (helper, false);
17515 cfun->language = ggc_cleared_alloc<language_function> ();
17516 poplevel (1, 0, 1);
17517 maybe_save_constexpr_fundef (helper);
17518 /* We must start each function with a clear fold cache. */
17519 clear_fold_cache ();
17520 cp_fold_function (helper);
17521 DECL_CONTEXT (DECL_RESULT (helper)) = helper;
17522 BLOCK_SUPERCONTEXT (DECL_INITIAL (helper)) = helper;
17523 /* This function has coroutine IFNs that we should handle in middle
17524 end lowering. */
17525 cfun->coroutine_component = true;
17526 cp_genericize (helper);
17527 expand_or_defer_fn (helper);
17530 /* Finish up a function declaration and compile that function
17531 all the way to assembler language output. The free the storage
17532 for the function definition. INLINE_P is TRUE if we just
17533 finished processing the body of an in-class inline function
17534 definition. (This processing will have taken place after the
17535 class definition is complete.) */
17537 tree
17538 finish_function (bool inline_p)
17540 tree fndecl = current_function_decl;
17541 tree fntype, ctype = NULL_TREE;
17542 tree resumer = NULL_TREE, destroyer = NULL_TREE;
17543 bool coro_p = flag_coroutines
17544 && !processing_template_decl
17545 && DECL_COROUTINE_P (fndecl);
17546 bool coro_emit_helpers = false;
17548 /* When we get some parse errors, we can end up without a
17549 current_function_decl, so cope. */
17550 if (fndecl == NULL_TREE)
17551 return error_mark_node;
17553 if (!DECL_OMP_DECLARE_REDUCTION_P (fndecl))
17554 finish_lambda_scope ();
17556 if (c_dialect_objc ())
17557 objc_finish_function ();
17559 record_key_method_defined (fndecl);
17561 fntype = TREE_TYPE (fndecl);
17563 /* TREE_READONLY (fndecl) = 1;
17564 This caused &foo to be of type ptr-to-const-function
17565 which then got a warning when stored in a ptr-to-function variable. */
17567 gcc_assert (building_stmt_list_p ());
17568 /* The current function is being defined, so its DECL_INITIAL should
17569 be set, and unless there's a multiple definition, it should be
17570 error_mark_node. */
17571 gcc_assert (DECL_INITIAL (fndecl) == error_mark_node);
17573 if (coro_p)
17575 /* Only try to emit the coroutine outlined helper functions if the
17576 transforms succeeded. Otherwise, treat errors in the same way as
17577 a regular function. */
17578 coro_emit_helpers = morph_fn_to_coro (fndecl, &resumer, &destroyer);
17580 /* We should handle coroutine IFNs in middle end lowering. */
17581 cfun->coroutine_component = true;
17583 /* Do not try to process the ramp's EH unless outlining succeeded. */
17584 if (coro_emit_helpers && use_eh_spec_block (fndecl))
17585 finish_eh_spec_block (TYPE_RAISES_EXCEPTIONS
17586 (TREE_TYPE (fndecl)),
17587 current_eh_spec_block);
17589 else
17590 /* For a cloned function, we've already got all the code we need;
17591 there's no need to add any extra bits. */
17592 if (!DECL_CLONED_FUNCTION_P (fndecl))
17594 /* Make it so that `main' always returns 0 by default. */
17595 if (DECL_MAIN_P (current_function_decl))
17596 finish_return_stmt (integer_zero_node);
17598 if (use_eh_spec_block (current_function_decl))
17599 finish_eh_spec_block (TYPE_RAISES_EXCEPTIONS
17600 (TREE_TYPE (current_function_decl)),
17601 current_eh_spec_block);
17604 /* If we're saving up tree structure, tie off the function now. */
17605 DECL_SAVED_TREE (fndecl) = pop_stmt_list (DECL_SAVED_TREE (fndecl));
17607 finish_fname_decls ();
17609 /* If this function can't throw any exceptions, remember that. */
17610 if (!processing_template_decl
17611 && !cp_function_chain->can_throw
17612 && !flag_non_call_exceptions
17613 && !decl_replaceable_p (fndecl,
17614 opt_for_fn (fndecl, flag_semantic_interposition)))
17615 TREE_NOTHROW (fndecl) = 1;
17617 /* This must come after expand_function_end because cleanups might
17618 have declarations (from inline functions) that need to go into
17619 this function's blocks. */
17621 /* If the current binding level isn't the outermost binding level
17622 for this function, either there is a bug, or we have experienced
17623 syntax errors and the statement tree is malformed. */
17624 if (current_binding_level->kind != sk_function_parms)
17626 /* Make sure we have already experienced errors. */
17627 gcc_assert (errorcount);
17629 /* Throw away the broken statement tree and extra binding
17630 levels. */
17631 DECL_SAVED_TREE (fndecl) = alloc_stmt_list ();
17633 while (current_binding_level->kind != sk_function_parms)
17635 if (current_binding_level->kind == sk_class)
17636 pop_nested_class ();
17637 else
17638 poplevel (0, 0, 0);
17641 poplevel (1, 0, 1);
17643 /* Statements should always be full-expressions at the outermost set
17644 of curly braces for a function. */
17645 gcc_assert (stmts_are_full_exprs_p ());
17647 /* If there are no return statements in a function with auto return type,
17648 the return type is void. But if the declared type is something like
17649 auto*, this is an error. */
17650 if (!processing_template_decl && FNDECL_USED_AUTO (fndecl)
17651 && TREE_TYPE (fntype) == DECL_SAVED_AUTO_RETURN_TYPE (fndecl))
17653 if (is_auto (DECL_SAVED_AUTO_RETURN_TYPE (fndecl))
17654 && !current_function_returns_value
17655 && !current_function_returns_null)
17657 /* We haven't applied return type deduction because we haven't
17658 seen any return statements. Do that now. */
17659 tree node = type_uses_auto (DECL_SAVED_AUTO_RETURN_TYPE (fndecl));
17660 do_auto_deduction (DECL_SAVED_AUTO_RETURN_TYPE (fndecl),
17661 void_node, node, tf_warning_or_error,
17662 adc_return_type);
17664 apply_deduced_return_type (fndecl, void_type_node);
17665 fntype = TREE_TYPE (fndecl);
17667 else if (!current_function_returns_value
17668 && !current_function_returns_null)
17670 error ("no return statements in function returning %qT",
17671 DECL_SAVED_AUTO_RETURN_TYPE (fndecl));
17672 inform (input_location, "only plain %<auto%> return type can be "
17673 "deduced to %<void%>");
17677 /* Remember that we were in class scope. */
17678 if (current_class_name)
17679 ctype = current_class_type;
17681 if (DECL_DELETED_FN (fndecl))
17683 DECL_INITIAL (fndecl) = error_mark_node;
17684 DECL_SAVED_TREE (fndecl) = NULL_TREE;
17685 goto cleanup;
17688 // If this is a concept, check that the definition is reasonable.
17689 if (DECL_DECLARED_CONCEPT_P (fndecl))
17690 check_function_concept (fndecl);
17692 if (flag_openmp)
17693 if (tree attr = lookup_attribute ("omp declare variant base",
17694 DECL_ATTRIBUTES (fndecl)))
17695 omp_declare_variant_finalize (fndecl, attr);
17697 /* Complain if there's just no return statement. */
17698 if ((warn_return_type
17699 || (cxx_dialect >= cxx14
17700 && DECL_DECLARED_CONSTEXPR_P (fndecl)))
17701 && !VOID_TYPE_P (TREE_TYPE (fntype))
17702 && !dependent_type_p (TREE_TYPE (fntype))
17703 && !current_function_returns_value && !current_function_returns_null
17704 /* Don't complain if we abort or throw. */
17705 && !current_function_returns_abnormally
17706 /* Don't complain if there's an infinite loop. */
17707 && !current_function_infinite_loop
17708 /* Don't complain if we are declared noreturn. */
17709 && !TREE_THIS_VOLATILE (fndecl)
17710 && !DECL_NAME (DECL_RESULT (fndecl))
17711 && !warning_suppressed_p (fndecl, OPT_Wreturn_type)
17712 /* Structor return values (if any) are set by the compiler. */
17713 && !DECL_CONSTRUCTOR_P (fndecl)
17714 && !DECL_DESTRUCTOR_P (fndecl)
17715 && targetm.warn_func_return (fndecl))
17717 gcc_rich_location richloc (input_location);
17718 /* Potentially add a "return *this;" fix-it hint for
17719 assignment operators. */
17720 if (IDENTIFIER_ASSIGN_OP_P (DECL_NAME (fndecl)))
17722 tree valtype = TREE_TYPE (DECL_RESULT (fndecl));
17723 if (TREE_CODE (valtype) == REFERENCE_TYPE
17724 && current_class_ref
17725 && same_type_ignoring_top_level_qualifiers_p
17726 (TREE_TYPE (valtype), TREE_TYPE (current_class_ref))
17727 && global_dc->option_enabled (OPT_Wreturn_type,
17728 global_dc->lang_mask,
17729 global_dc->option_state))
17730 add_return_star_this_fixit (&richloc, fndecl);
17732 if (cxx_dialect >= cxx14
17733 && DECL_DECLARED_CONSTEXPR_P (fndecl))
17734 error_at (&richloc, "no return statement in %<constexpr%> function "
17735 "returning non-void");
17736 else if (warning_at (&richloc, OPT_Wreturn_type,
17737 "no return statement in function returning "
17738 "non-void"))
17739 suppress_warning (fndecl, OPT_Wreturn_type);
17742 /* Lambda closure members are implicitly constexpr if possible. */
17743 if (cxx_dialect >= cxx17
17744 && LAMBDA_TYPE_P (CP_DECL_CONTEXT (fndecl)))
17745 DECL_DECLARED_CONSTEXPR_P (fndecl)
17746 = ((processing_template_decl
17747 || is_valid_constexpr_fn (fndecl, /*complain*/false))
17748 && potential_constant_expression (DECL_SAVED_TREE (fndecl)));
17750 /* Save constexpr function body before it gets munged by
17751 the NRV transformation. */
17752 maybe_save_constexpr_fundef (fndecl);
17754 /* Invoke the pre-genericize plugin before we start munging things. */
17755 if (!processing_template_decl)
17756 invoke_plugin_callbacks (PLUGIN_PRE_GENERICIZE, fndecl);
17758 /* Perform delayed folding before NRV transformation. */
17759 if (!processing_template_decl
17760 && !DECL_IMMEDIATE_FUNCTION_P (fndecl)
17761 && !DECL_OMP_DECLARE_REDUCTION_P (fndecl))
17762 cp_fold_function (fndecl);
17764 /* Set up the named return value optimization, if we can. Candidate
17765 variables are selected in check_return_expr. */
17766 if (current_function_return_value)
17768 tree r = current_function_return_value;
17769 tree outer;
17771 if (r != error_mark_node
17772 /* This is only worth doing for fns that return in memory--and
17773 simpler, since we don't have to worry about promoted modes. */
17774 && aggregate_value_p (TREE_TYPE (TREE_TYPE (fndecl)), fndecl)
17775 /* Only allow this for variables declared in the outer scope of
17776 the function so we know that their lifetime always ends with a
17777 return; see g++.dg/opt/nrv6.C. We could be more flexible if
17778 we were to do this optimization in tree-ssa. */
17779 && (outer = outer_curly_brace_block (fndecl))
17780 && chain_member (r, BLOCK_VARS (outer)))
17781 finalize_nrv (&DECL_SAVED_TREE (fndecl), r, DECL_RESULT (fndecl));
17783 current_function_return_value = NULL_TREE;
17786 /* Must mark the RESULT_DECL as being in this function. */
17787 DECL_CONTEXT (DECL_RESULT (fndecl)) = fndecl;
17789 /* Set the BLOCK_SUPERCONTEXT of the outermost function scope to point
17790 to the FUNCTION_DECL node itself. */
17791 BLOCK_SUPERCONTEXT (DECL_INITIAL (fndecl)) = fndecl;
17793 /* Store the end of the function, so that we get good line number
17794 info for the epilogue. */
17795 cfun->function_end_locus = input_location;
17797 /* Complain about parameters that are only set, but never otherwise used. */
17798 if (warn_unused_but_set_parameter
17799 && !processing_template_decl
17800 && errorcount == unused_but_set_errorcount
17801 && !DECL_CLONED_FUNCTION_P (fndecl))
17803 tree decl;
17805 for (decl = DECL_ARGUMENTS (fndecl);
17806 decl;
17807 decl = DECL_CHAIN (decl))
17808 if (TREE_USED (decl)
17809 && TREE_CODE (decl) == PARM_DECL
17810 && !DECL_READ_P (decl)
17811 && DECL_NAME (decl)
17812 && !DECL_ARTIFICIAL (decl)
17813 && !warning_suppressed_p (decl,OPT_Wunused_but_set_parameter)
17814 && !DECL_IN_SYSTEM_HEADER (decl)
17815 && TREE_TYPE (decl) != error_mark_node
17816 && !TYPE_REF_P (TREE_TYPE (decl))
17817 && (!CLASS_TYPE_P (TREE_TYPE (decl))
17818 || !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (decl))))
17819 warning_at (DECL_SOURCE_LOCATION (decl),
17820 OPT_Wunused_but_set_parameter,
17821 "parameter %qD set but not used", decl);
17822 unused_but_set_errorcount = errorcount;
17825 /* Complain about locally defined typedefs that are not used in this
17826 function. */
17827 maybe_warn_unused_local_typedefs ();
17829 /* Possibly warn about unused parameters. */
17830 if (warn_unused_parameter
17831 && !processing_template_decl
17832 && !DECL_CLONED_FUNCTION_P (fndecl))
17833 do_warn_unused_parameter (fndecl);
17835 /* Genericize before inlining. */
17836 if (!processing_template_decl
17837 && !DECL_IMMEDIATE_FUNCTION_P (fndecl)
17838 && !DECL_OMP_DECLARE_REDUCTION_P (fndecl))
17839 cp_genericize (fndecl);
17841 /* Emit the resumer and destroyer functions now, providing that we have
17842 not encountered some fatal error. */
17843 if (coro_emit_helpers)
17845 emit_coro_helper (resumer);
17846 emit_coro_helper (destroyer);
17849 cleanup:
17850 /* We're leaving the context of this function, so zap cfun. It's still in
17851 DECL_STRUCT_FUNCTION, and we'll restore it in tree_rest_of_compilation. */
17852 set_cfun (NULL);
17853 current_function_decl = NULL;
17855 /* If this is an in-class inline definition, we may have to pop the
17856 bindings for the template parameters that we added in
17857 maybe_begin_member_template_processing when start_function was
17858 called. */
17859 if (inline_p)
17860 maybe_end_member_template_processing ();
17862 /* Leave the scope of the class. */
17863 if (ctype)
17864 pop_nested_class ();
17866 --function_depth;
17868 /* Clean up. */
17869 current_function_decl = NULL_TREE;
17871 invoke_plugin_callbacks (PLUGIN_FINISH_PARSE_FUNCTION, fndecl);
17872 return fndecl;
17875 /* Create the FUNCTION_DECL for a function definition.
17876 DECLSPECS and DECLARATOR are the parts of the declaration;
17877 they describe the return type and the name of the function,
17878 but twisted together in a fashion that parallels the syntax of C.
17880 This function creates a binding context for the function body
17881 as well as setting up the FUNCTION_DECL in current_function_decl.
17883 Returns a FUNCTION_DECL on success.
17885 If the DECLARATOR is not suitable for a function (it defines a datum
17886 instead), we return 0, which tells yyparse to report a parse error.
17888 May return void_type_node indicating that this method is actually
17889 a friend. See grokfield for more details.
17891 Came here with a `.pushlevel' .
17893 DO NOT MAKE ANY CHANGES TO THIS CODE WITHOUT MAKING CORRESPONDING
17894 CHANGES TO CODE IN `grokfield'. */
17896 tree
17897 grokmethod (cp_decl_specifier_seq *declspecs,
17898 const cp_declarator *declarator, tree attrlist)
17900 tree fndecl = grokdeclarator (declarator, declspecs, MEMFUNCDEF, 0,
17901 &attrlist);
17903 if (fndecl == error_mark_node)
17904 return error_mark_node;
17906 if (attrlist)
17907 cplus_decl_attributes (&fndecl, attrlist, 0);
17909 /* Pass friends other than inline friend functions back. */
17910 if (fndecl == void_type_node)
17911 return fndecl;
17913 if (DECL_IN_AGGR_P (fndecl))
17915 if (DECL_CLASS_SCOPE_P (fndecl))
17916 error ("%qD is already defined in class %qT", fndecl,
17917 DECL_CONTEXT (fndecl));
17918 return error_mark_node;
17921 check_template_shadow (fndecl);
17923 /* p1779 ABI-Isolation makes inline not a default for in-class
17924 definitions in named module purview. If the user explicitly
17925 made it inline, grokdeclarator will already have done the right
17926 things. */
17927 if ((!named_module_purview_p ()
17928 || flag_module_implicit_inline
17929 /* Lambda's operator function remains inline. */
17930 || LAMBDA_TYPE_P (DECL_CONTEXT (fndecl)))
17931 /* If the user explicitly asked for this to be inline, we don't
17932 need to do more, but more importantly we want to warn if we
17933 can't inline it. */
17934 && !DECL_DECLARED_INLINE_P (fndecl))
17936 if (TREE_PUBLIC (fndecl))
17937 DECL_COMDAT (fndecl) = 1;
17938 DECL_DECLARED_INLINE_P (fndecl) = 1;
17939 /* It's ok if we can't inline this. */
17940 DECL_NO_INLINE_WARNING_P (fndecl) = 1;
17943 /* We process method specializations in finish_struct_1. */
17944 if (processing_template_decl && !DECL_TEMPLATE_SPECIALIZATION (fndecl))
17946 /* Avoid calling decl_spec_seq... until we have to. */
17947 bool friendp = decl_spec_seq_has_spec_p (declspecs, ds_friend);
17948 fndecl = push_template_decl (fndecl, friendp);
17949 if (fndecl == error_mark_node)
17950 return fndecl;
17953 if (DECL_CHAIN (fndecl) && !decl_spec_seq_has_spec_p (declspecs, ds_friend))
17955 fndecl = copy_node (fndecl);
17956 TREE_CHAIN (fndecl) = NULL_TREE;
17959 cp_finish_decl (fndecl, NULL_TREE, false, NULL_TREE, 0);
17961 DECL_IN_AGGR_P (fndecl) = 1;
17962 return fndecl;
17966 /* VAR is a VAR_DECL. If its type is incomplete, remember VAR so that
17967 we can lay it out later, when and if its type becomes complete.
17969 Also handle constexpr variables where the initializer involves
17970 an unlowered PTRMEM_CST because the class isn't complete yet. */
17972 void
17973 maybe_register_incomplete_var (tree var)
17975 gcc_assert (VAR_P (var));
17977 /* Keep track of variables with incomplete types. */
17978 if (!processing_template_decl && TREE_TYPE (var) != error_mark_node
17979 && DECL_EXTERNAL (var))
17981 tree inner_type = TREE_TYPE (var);
17983 while (TREE_CODE (inner_type) == ARRAY_TYPE)
17984 inner_type = TREE_TYPE (inner_type);
17985 inner_type = TYPE_MAIN_VARIANT (inner_type);
17987 if ((!COMPLETE_TYPE_P (inner_type) && CLASS_TYPE_P (inner_type))
17988 /* RTTI TD entries are created while defining the type_info. */
17989 || (TYPE_LANG_SPECIFIC (inner_type)
17990 && TYPE_BEING_DEFINED (inner_type)))
17992 incomplete_var iv = {var, inner_type};
17993 vec_safe_push (incomplete_vars, iv);
17995 else if (!(DECL_LANG_SPECIFIC (var) && DECL_TEMPLATE_INFO (var))
17996 && decl_constant_var_p (var)
17997 && (TYPE_PTRMEM_P (inner_type) || CLASS_TYPE_P (inner_type)))
17999 /* When the outermost open class is complete we can resolve any
18000 pointers-to-members. */
18001 tree context = outermost_open_class ();
18002 incomplete_var iv = {var, context};
18003 vec_safe_push (incomplete_vars, iv);
18008 /* Called when a class type (given by TYPE) is defined. If there are
18009 any existing VAR_DECLs whose type has been completed by this
18010 declaration, update them now. */
18012 void
18013 complete_vars (tree type)
18015 unsigned ix;
18016 incomplete_var *iv;
18018 for (ix = 0; vec_safe_iterate (incomplete_vars, ix, &iv); )
18020 if (same_type_p (type, iv->incomplete_type))
18022 tree var = iv->decl;
18023 tree type = TREE_TYPE (var);
18025 if (type != error_mark_node
18026 && (TYPE_MAIN_VARIANT (strip_array_types (type))
18027 == iv->incomplete_type))
18029 /* Complete the type of the variable. */
18030 complete_type (type);
18031 cp_apply_type_quals_to_decl (cp_type_quals (type), var);
18032 if (COMPLETE_TYPE_P (type))
18033 layout_var_decl (var);
18036 /* Remove this entry from the list. */
18037 incomplete_vars->unordered_remove (ix);
18039 else
18040 ix++;
18044 /* If DECL is of a type which needs a cleanup, build and return an
18045 expression to perform that cleanup here. Return NULL_TREE if no
18046 cleanup need be done. DECL can also be a _REF when called from
18047 split_nonconstant_init_1. */
18049 tree
18050 cxx_maybe_build_cleanup (tree decl, tsubst_flags_t complain)
18052 tree type;
18053 tree attr;
18054 tree cleanup;
18056 /* Assume no cleanup is required. */
18057 cleanup = NULL_TREE;
18059 if (error_operand_p (decl))
18060 return cleanup;
18062 /* Handle "__attribute__((cleanup))". We run the cleanup function
18063 before the destructor since the destructor is what actually
18064 terminates the lifetime of the object. */
18065 if (DECL_P (decl))
18066 attr = lookup_attribute ("cleanup", DECL_ATTRIBUTES (decl));
18067 else
18068 attr = NULL_TREE;
18069 if (attr)
18071 tree id;
18072 tree fn;
18073 tree arg;
18075 /* Get the name specified by the user for the cleanup function. */
18076 id = TREE_VALUE (TREE_VALUE (attr));
18077 /* Look up the name to find the cleanup function to call. It is
18078 important to use lookup_name here because that is what is
18079 used in c-common.c:handle_cleanup_attribute when performing
18080 initial checks on the attribute. Note that those checks
18081 include ensuring that the function found is not an overloaded
18082 function, or an object with an overloaded call operator,
18083 etc.; we can rely on the fact that the function found is an
18084 ordinary FUNCTION_DECL. */
18085 fn = lookup_name (id);
18086 arg = build_address (decl);
18087 if (!mark_used (decl, complain) && !(complain & tf_error))
18088 return error_mark_node;
18089 cleanup = cp_build_function_call_nary (fn, complain, arg, NULL_TREE);
18090 if (cleanup == error_mark_node)
18091 return error_mark_node;
18093 /* Handle ordinary C++ destructors. */
18094 type = TREE_TYPE (decl);
18095 if (type_build_dtor_call (type))
18097 int flags = LOOKUP_NORMAL|LOOKUP_NONVIRTUAL|LOOKUP_DESTRUCTOR;
18098 tree addr;
18099 tree call;
18101 if (TREE_CODE (type) == ARRAY_TYPE)
18102 addr = decl;
18103 else
18104 addr = build_address (decl);
18106 call = build_delete (input_location, TREE_TYPE (addr), addr,
18107 sfk_complete_destructor, flags, 0, complain);
18108 if (call == error_mark_node)
18109 cleanup = error_mark_node;
18110 else if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
18111 /* Discard the call. */;
18112 else if (decl_maybe_constant_destruction (decl, type)
18113 && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
18114 cxx_constant_dtor (call, decl);
18115 else if (cleanup)
18116 cleanup = cp_build_compound_expr (cleanup, call, complain);
18117 else
18118 cleanup = call;
18121 /* build_delete sets the location of the destructor call to the
18122 current location, even though the destructor is going to be
18123 called later, at the end of the current scope. This can lead to
18124 a "jumpy" behavior for users of debuggers when they step around
18125 the end of the block. So let's unset the location of the
18126 destructor call instead. */
18127 protected_set_expr_location (cleanup, UNKNOWN_LOCATION);
18128 if (cleanup && CONVERT_EXPR_P (cleanup))
18129 protected_set_expr_location (TREE_OPERAND (cleanup, 0), UNKNOWN_LOCATION);
18131 if (cleanup
18132 && DECL_P (decl)
18133 && !lookup_attribute ("warn_unused", TYPE_ATTRIBUTES (TREE_TYPE (decl)))
18134 /* Treat objects with destructors as used; the destructor may do
18135 something substantive. */
18136 && !mark_used (decl, complain) && !(complain & tf_error))
18137 return error_mark_node;
18139 if (cleanup && cfun && !processing_template_decl
18140 && !expr_noexcept_p (cleanup, tf_none))
18141 cp_function_chain->throwing_cleanup = true;
18143 return cleanup;
18147 /* Return the FUNCTION_TYPE that corresponds to MEMFNTYPE, which can be a
18148 FUNCTION_DECL, METHOD_TYPE, FUNCTION_TYPE, pointer or reference to
18149 METHOD_TYPE or FUNCTION_TYPE, or pointer to member function. */
18151 tree
18152 static_fn_type (tree memfntype)
18154 tree fntype;
18155 tree args;
18157 if (TYPE_PTRMEMFUNC_P (memfntype))
18158 memfntype = TYPE_PTRMEMFUNC_FN_TYPE (memfntype);
18159 if (INDIRECT_TYPE_P (memfntype)
18160 || TREE_CODE (memfntype) == FUNCTION_DECL)
18161 memfntype = TREE_TYPE (memfntype);
18162 if (TREE_CODE (memfntype) == FUNCTION_TYPE)
18163 return memfntype;
18164 gcc_assert (TREE_CODE (memfntype) == METHOD_TYPE);
18165 args = TYPE_ARG_TYPES (memfntype);
18166 fntype = build_function_type (TREE_TYPE (memfntype), TREE_CHAIN (args));
18167 fntype = apply_memfn_quals (fntype, type_memfn_quals (memfntype));
18168 fntype = (cp_build_type_attribute_variant
18169 (fntype, TYPE_ATTRIBUTES (memfntype)));
18170 fntype = cxx_copy_lang_qualifiers (fntype, memfntype);
18171 return fntype;
18174 /* DECL was originally constructed as a non-static member function,
18175 but turned out to be static. Update it accordingly. */
18177 void
18178 revert_static_member_fn (tree decl)
18180 tree stype = static_fn_type (decl);
18181 cp_cv_quals quals = type_memfn_quals (stype);
18182 cp_ref_qualifier rqual = type_memfn_rqual (stype);
18184 if (quals != TYPE_UNQUALIFIED || rqual != REF_QUAL_NONE)
18185 stype = apply_memfn_quals (stype, TYPE_UNQUALIFIED, REF_QUAL_NONE);
18187 TREE_TYPE (decl) = stype;
18189 if (DECL_ARGUMENTS (decl))
18190 DECL_ARGUMENTS (decl) = DECL_CHAIN (DECL_ARGUMENTS (decl));
18191 DECL_STATIC_FUNCTION_P (decl) = 1;
18194 /* Return which tree structure is used by T, or TS_CP_GENERIC if T is
18195 one of the language-independent trees. */
18197 enum cp_tree_node_structure_enum
18198 cp_tree_node_structure (union lang_tree_node * t)
18200 switch (TREE_CODE (&t->generic))
18202 case ARGUMENT_PACK_SELECT: return TS_CP_ARGUMENT_PACK_SELECT;
18203 case BASELINK: return TS_CP_BASELINK;
18204 case CONSTRAINT_INFO: return TS_CP_CONSTRAINT_INFO;
18205 case DEFERRED_NOEXCEPT: return TS_CP_DEFERRED_NOEXCEPT;
18206 case DEFERRED_PARSE: return TS_CP_DEFERRED_PARSE;
18207 case IDENTIFIER_NODE: return TS_CP_IDENTIFIER;
18208 case LAMBDA_EXPR: return TS_CP_LAMBDA_EXPR;
18209 case BINDING_VECTOR: return TS_CP_BINDING_VECTOR;
18210 case OVERLOAD: return TS_CP_OVERLOAD;
18211 case PTRMEM_CST: return TS_CP_PTRMEM;
18212 case STATIC_ASSERT: return TS_CP_STATIC_ASSERT;
18213 case TEMPLATE_DECL: return TS_CP_TEMPLATE_DECL;
18214 case TEMPLATE_INFO: return TS_CP_TEMPLATE_INFO;
18215 case TEMPLATE_PARM_INDEX: return TS_CP_TPI;
18216 case TRAIT_EXPR: return TS_CP_TRAIT_EXPR;
18217 case USERDEF_LITERAL: return TS_CP_USERDEF_LITERAL;
18218 default: return TS_CP_GENERIC;
18222 /* Build the void_list_node (void_type_node having been created). */
18223 tree
18224 build_void_list_node (void)
18226 tree t = build_tree_list (NULL_TREE, void_type_node);
18227 return t;
18230 bool
18231 cp_missing_noreturn_ok_p (tree decl)
18233 /* A missing noreturn is ok for the `main' function. */
18234 return DECL_MAIN_P (decl);
18237 /* Return the decl used to identify the COMDAT group into which DECL should
18238 be placed. */
18240 tree
18241 cxx_comdat_group (tree decl)
18243 /* Virtual tables, construction virtual tables, and virtual table
18244 tables all go in a single COMDAT group, named after the primary
18245 virtual table. */
18246 if (VAR_P (decl) && DECL_VTABLE_OR_VTT_P (decl))
18247 decl = CLASSTYPE_VTABLES (DECL_CONTEXT (decl));
18248 /* For all other DECLs, the COMDAT group is the mangled name of the
18249 declaration itself. */
18250 else
18252 while (DECL_THUNK_P (decl))
18254 /* If TARGET_USE_LOCAL_THUNK_ALIAS_P, use_thunk puts the thunk
18255 into the same section as the target function. In that case
18256 we must return target's name. */
18257 tree target = THUNK_TARGET (decl);
18258 if (TARGET_USE_LOCAL_THUNK_ALIAS_P (target)
18259 && DECL_SECTION_NAME (target) != NULL
18260 && DECL_ONE_ONLY (target))
18261 decl = target;
18262 else
18263 break;
18267 return decl;
18270 /* Returns the return type for FN as written by the user, which may include
18271 a placeholder for a deduced return type. */
18273 tree
18274 fndecl_declared_return_type (tree fn)
18276 fn = STRIP_TEMPLATE (fn);
18277 if (FNDECL_USED_AUTO (fn))
18278 return DECL_SAVED_AUTO_RETURN_TYPE (fn);
18280 return TREE_TYPE (TREE_TYPE (fn));
18283 /* Returns true iff DECL is a variable or function declared with an auto type
18284 that has not yet been deduced to a real type. */
18286 bool
18287 undeduced_auto_decl (tree decl)
18289 if (cxx_dialect < cxx11)
18290 return false;
18291 STRIP_ANY_LOCATION_WRAPPER (decl);
18292 return ((VAR_OR_FUNCTION_DECL_P (decl)
18293 || TREE_CODE (decl) == TEMPLATE_DECL)
18294 && type_uses_auto (TREE_TYPE (decl)));
18297 /* Complain if DECL has an undeduced return type. */
18299 bool
18300 require_deduced_type (tree decl, tsubst_flags_t complain)
18302 if (undeduced_auto_decl (decl))
18304 if (warning_suppressed_p (decl) && seen_error ())
18305 /* We probably already complained about deduction failure. */;
18306 else if (complain & tf_error)
18307 error ("use of %qD before deduction of %<auto%>", decl);
18308 note_failed_type_completion_for_satisfaction (decl);
18309 return false;
18311 return true;
18314 /* Create a representation of the explicit-specifier with
18315 constant-expression of EXPR. COMPLAIN is as for tsubst. */
18317 tree
18318 build_explicit_specifier (tree expr, tsubst_flags_t complain)
18320 if (check_for_bare_parameter_packs (expr))
18321 return error_mark_node;
18323 if (instantiation_dependent_expression_p (expr))
18324 /* Wait for instantiation, tsubst_function_decl will handle it. */
18325 return expr;
18327 expr = build_converted_constant_bool_expr (expr, complain);
18328 expr = instantiate_non_dependent_expr_sfinae (expr, complain);
18329 expr = cxx_constant_value (expr);
18330 return expr;
18333 #include "gt-cp-decl.h"