c++: designator and anon struct [PR101767]
[official-gcc.git] / gcc / cp / decl.cc
blob375385e0013348e473283eef7ee19d7b6d408266
1 /* Process declarations and variables for -*- C++ -*- compiler.
2 Copyright (C) 1988-2022 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 /* OLD_PARMS is the innermost set of template parameters for some template
1474 declaration, and NEW_PARMS is the corresponding set of template parameters
1475 for a redeclaration of that template. Merge the default arguments within
1476 these two sets of parameters. CLASS_P is true iff the template in
1477 question is a class template. */
1479 bool
1480 merge_default_template_args (tree new_parms, tree old_parms, bool class_p)
1482 gcc_checking_assert (TREE_VEC_LENGTH (new_parms)
1483 == TREE_VEC_LENGTH (old_parms));
1484 for (int i = 0; i < TREE_VEC_LENGTH (new_parms); i++)
1486 tree new_parm = TREE_VALUE (TREE_VEC_ELT (new_parms, i));
1487 tree old_parm = TREE_VALUE (TREE_VEC_ELT (old_parms, i));
1488 tree& new_default = TREE_PURPOSE (TREE_VEC_ELT (new_parms, i));
1489 tree& old_default = TREE_PURPOSE (TREE_VEC_ELT (old_parms, i));
1490 if (new_default != NULL_TREE && old_default != NULL_TREE)
1492 auto_diagnostic_group d;
1493 error ("redefinition of default argument for %q+#D", new_parm);
1494 inform (DECL_SOURCE_LOCATION (old_parm),
1495 "original definition appeared here");
1496 return false;
1498 else if (new_default != NULL_TREE)
1499 /* Update the previous template parameters (which are the ones
1500 that will really count) with the new default value. */
1501 old_default = new_default;
1502 else if (class_p && old_default != NULL_TREE)
1503 /* Update the new parameters, too; they'll be used as the
1504 parameters for any members. */
1505 new_default = old_default;
1507 return true;
1510 /* If NEWDECL is a redeclaration of OLDDECL, merge the declarations.
1511 If the redeclaration is invalid, a diagnostic is issued, and the
1512 error_mark_node is returned. Otherwise, OLDDECL is returned.
1514 If NEWDECL is not a redeclaration of OLDDECL, NULL_TREE is
1515 returned.
1517 HIDING is true if the new decl is being hidden. WAS_HIDDEN is true
1518 if the old decl was hidden.
1520 Hidden decls can be anticipated builtins, injected friends, or
1521 (coming soon) injected from a local-extern decl. */
1523 tree
1524 duplicate_decls (tree newdecl, tree olddecl, bool hiding, bool was_hidden)
1526 unsigned olddecl_uid = DECL_UID (olddecl);
1527 int types_match = 0;
1528 int new_defines_function = 0;
1529 tree new_template_info;
1530 location_t olddecl_loc = DECL_SOURCE_LOCATION (olddecl);
1531 location_t newdecl_loc = DECL_SOURCE_LOCATION (newdecl);
1533 if (newdecl == olddecl)
1534 return olddecl;
1536 types_match = decls_match (newdecl, olddecl);
1538 /* If either the type of the new decl or the type of the old decl is an
1539 error_mark_node, then that implies that we have already issued an
1540 error (earlier) for some bogus type specification, and in that case,
1541 it is rather pointless to harass the user with yet more error message
1542 about the same declaration, so just pretend the types match here. */
1543 if (TREE_TYPE (newdecl) == error_mark_node
1544 || TREE_TYPE (olddecl) == error_mark_node)
1545 return error_mark_node;
1547 /* Check for redeclaration and other discrepancies. */
1548 if (TREE_CODE (olddecl) == FUNCTION_DECL
1549 && DECL_IS_UNDECLARED_BUILTIN (olddecl))
1551 if (TREE_CODE (newdecl) != FUNCTION_DECL)
1553 /* Avoid warnings redeclaring built-ins which have not been
1554 explicitly declared. */
1555 if (was_hidden)
1557 if (TREE_PUBLIC (newdecl)
1558 && CP_DECL_CONTEXT (newdecl) == global_namespace)
1559 warning_at (newdecl_loc,
1560 OPT_Wbuiltin_declaration_mismatch,
1561 "built-in function %qD declared as non-function",
1562 newdecl);
1563 return NULL_TREE;
1566 /* If you declare a built-in or predefined function name as static,
1567 the old definition is overridden, but optionally warn this was a
1568 bad choice of name. */
1569 if (! TREE_PUBLIC (newdecl))
1571 warning_at (newdecl_loc,
1572 OPT_Wshadow,
1573 fndecl_built_in_p (olddecl)
1574 ? G_("shadowing built-in function %q#D")
1575 : G_("shadowing library function %q#D"), olddecl);
1576 /* Discard the old built-in function. */
1577 return NULL_TREE;
1579 /* If the built-in is not ansi, then programs can override
1580 it even globally without an error. */
1581 else if (! fndecl_built_in_p (olddecl))
1582 warning_at (newdecl_loc, 0,
1583 "library function %q#D redeclared as non-function %q#D",
1584 olddecl, newdecl);
1585 else
1586 error_at (newdecl_loc,
1587 "declaration of %q#D conflicts with built-in "
1588 "declaration %q#D", newdecl, olddecl);
1589 return NULL_TREE;
1591 else if (!types_match)
1593 /* Avoid warnings redeclaring built-ins which have not been
1594 explicitly declared. */
1595 if (was_hidden)
1597 tree t1, t2;
1599 /* A new declaration doesn't match a built-in one unless it
1600 is also extern "C". */
1601 gcc_assert (DECL_IS_UNDECLARED_BUILTIN (olddecl));
1602 gcc_assert (DECL_EXTERN_C_P (olddecl));
1603 if (!DECL_EXTERN_C_P (newdecl))
1604 return NULL_TREE;
1606 for (t1 = TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1607 t2 = TYPE_ARG_TYPES (TREE_TYPE (olddecl));
1608 t1 || t2;
1609 t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2))
1611 if (!t1 || !t2)
1612 break;
1613 /* FILE, tm types are not known at the time
1614 we create the builtins. */
1615 for (unsigned i = 0;
1616 i < sizeof (builtin_structptr_types)
1617 / sizeof (builtin_structptr_type);
1618 ++i)
1619 if (TREE_VALUE (t2) == builtin_structptr_types[i].node)
1621 tree t = TREE_VALUE (t1);
1623 if (TYPE_PTR_P (t)
1624 && TYPE_IDENTIFIER (TREE_TYPE (t))
1625 == get_identifier (builtin_structptr_types[i].str)
1626 && compparms (TREE_CHAIN (t1), TREE_CHAIN (t2)))
1628 tree oldargs = TYPE_ARG_TYPES (TREE_TYPE (olddecl));
1630 TYPE_ARG_TYPES (TREE_TYPE (olddecl))
1631 = TYPE_ARG_TYPES (TREE_TYPE (newdecl));
1632 types_match = decls_match (newdecl, olddecl);
1633 if (types_match)
1634 return duplicate_decls (newdecl, olddecl,
1635 hiding, was_hidden);
1636 TYPE_ARG_TYPES (TREE_TYPE (olddecl)) = oldargs;
1638 goto next_arg;
1641 if (! same_type_p (TREE_VALUE (t1), TREE_VALUE (t2)))
1642 break;
1643 next_arg:;
1646 warning_at (newdecl_loc,
1647 OPT_Wbuiltin_declaration_mismatch,
1648 "declaration of %q#D conflicts with built-in "
1649 "declaration %q#D", newdecl, olddecl);
1651 else if ((DECL_EXTERN_C_P (newdecl)
1652 && DECL_EXTERN_C_P (olddecl))
1653 || compparms (TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1654 TYPE_ARG_TYPES (TREE_TYPE (olddecl))))
1656 /* Don't really override olddecl for __* prefixed builtins
1657 except for __[^b]*_chk, the compiler might be using those
1658 explicitly. */
1659 if (fndecl_built_in_p (olddecl))
1661 tree id = DECL_NAME (olddecl);
1662 const char *name = IDENTIFIER_POINTER (id);
1663 size_t len;
1665 if (name[0] == '_'
1666 && name[1] == '_'
1667 && (startswith (name + 2, "builtin_")
1668 || (len = strlen (name)) <= strlen ("___chk")
1669 || memcmp (name + len - strlen ("_chk"),
1670 "_chk", strlen ("_chk") + 1) != 0))
1672 if (DECL_INITIAL (newdecl))
1674 error_at (newdecl_loc,
1675 "definition of %q#D ambiguates built-in "
1676 "declaration %q#D", newdecl, olddecl);
1677 return error_mark_node;
1679 auto_diagnostic_group d;
1680 if (permerror (newdecl_loc,
1681 "new declaration %q#D ambiguates built-in"
1682 " declaration %q#D", newdecl, olddecl)
1683 && flag_permissive)
1684 inform (newdecl_loc,
1685 "ignoring the %q#D declaration", newdecl);
1686 return flag_permissive ? olddecl : error_mark_node;
1690 /* A near match; override the builtin. */
1692 if (TREE_PUBLIC (newdecl))
1693 warning_at (newdecl_loc,
1694 OPT_Wbuiltin_declaration_mismatch,
1695 "new declaration %q#D ambiguates built-in "
1696 "declaration %q#D", newdecl, olddecl);
1697 else
1698 warning (OPT_Wshadow,
1699 fndecl_built_in_p (olddecl)
1700 ? G_("shadowing built-in function %q#D")
1701 : G_("shadowing library function %q#D"), olddecl);
1703 else
1704 /* Discard the old built-in function. */
1705 return NULL_TREE;
1707 /* Replace the old RTL to avoid problems with inlining. */
1708 COPY_DECL_RTL (newdecl, olddecl);
1710 else
1712 /* Even if the types match, prefer the new declarations type
1713 for built-ins which have not been explicitly declared,
1714 for exception lists, etc... */
1715 tree type = TREE_TYPE (newdecl);
1716 tree attribs = (*targetm.merge_type_attributes)
1717 (TREE_TYPE (olddecl), type);
1719 type = cp_build_type_attribute_variant (type, attribs);
1720 TREE_TYPE (newdecl) = TREE_TYPE (olddecl) = type;
1723 /* If a function is explicitly declared "throw ()", propagate that to
1724 the corresponding builtin. */
1725 if (DECL_BUILT_IN_CLASS (olddecl) == BUILT_IN_NORMAL
1726 && was_hidden
1727 && TREE_NOTHROW (newdecl)
1728 && !TREE_NOTHROW (olddecl))
1730 enum built_in_function fncode = DECL_FUNCTION_CODE (olddecl);
1731 tree tmpdecl = builtin_decl_explicit (fncode);
1732 if (tmpdecl && tmpdecl != olddecl && types_match)
1733 TREE_NOTHROW (tmpdecl) = 1;
1736 /* Whether or not the builtin can throw exceptions has no
1737 bearing on this declarator. */
1738 TREE_NOTHROW (olddecl) = 0;
1740 if (DECL_THIS_STATIC (newdecl) && !DECL_THIS_STATIC (olddecl))
1742 /* If a builtin function is redeclared as `static', merge
1743 the declarations, but make the original one static. */
1744 DECL_THIS_STATIC (olddecl) = 1;
1745 TREE_PUBLIC (olddecl) = 0;
1747 /* Make the old declaration consistent with the new one so
1748 that all remnants of the builtin-ness of this function
1749 will be banished. */
1750 SET_DECL_LANGUAGE (olddecl, DECL_LANGUAGE (newdecl));
1751 COPY_DECL_RTL (newdecl, olddecl);
1754 else if (TREE_CODE (olddecl) != TREE_CODE (newdecl))
1756 /* C++ Standard, 3.3, clause 4:
1757 "[Note: a namespace name or a class template name must be unique
1758 in its declarative region (7.3.2, clause 14). ]" */
1759 if (TREE_CODE (olddecl) == NAMESPACE_DECL
1760 || TREE_CODE (newdecl) == NAMESPACE_DECL)
1761 /* Namespace conflicts with not namespace. */;
1762 else if (DECL_TYPE_TEMPLATE_P (olddecl)
1763 || DECL_TYPE_TEMPLATE_P (newdecl))
1764 /* Class template conflicts. */;
1765 else if ((TREE_CODE (olddecl) == TEMPLATE_DECL
1766 && DECL_TEMPLATE_RESULT (olddecl)
1767 && TREE_CODE (DECL_TEMPLATE_RESULT (olddecl)) == VAR_DECL)
1768 || (TREE_CODE (newdecl) == TEMPLATE_DECL
1769 && DECL_TEMPLATE_RESULT (newdecl)
1770 && TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == VAR_DECL))
1771 /* Variable template conflicts. */;
1772 else if (concept_definition_p (olddecl)
1773 || concept_definition_p (newdecl))
1774 /* Concept conflicts. */;
1775 else if ((TREE_CODE (newdecl) == FUNCTION_DECL
1776 && DECL_FUNCTION_TEMPLATE_P (olddecl))
1777 || (TREE_CODE (olddecl) == FUNCTION_DECL
1778 && DECL_FUNCTION_TEMPLATE_P (newdecl)))
1780 /* One is a function and the other is a template
1781 function. */
1782 if (!UDLIT_OPER_P (DECL_NAME (newdecl)))
1783 return NULL_TREE;
1785 /* There can only be one! */
1786 if (TREE_CODE (newdecl) == TEMPLATE_DECL
1787 && check_raw_literal_operator (olddecl))
1788 error_at (newdecl_loc,
1789 "literal operator %q#D conflicts with"
1790 " raw literal operator", newdecl);
1791 else if (check_raw_literal_operator (newdecl))
1792 error_at (newdecl_loc,
1793 "raw literal operator %q#D conflicts with"
1794 " literal operator template", newdecl);
1795 else
1796 return NULL_TREE;
1798 inform (olddecl_loc, "previous declaration %q#D", olddecl);
1799 return error_mark_node;
1801 else if ((VAR_P (olddecl) && DECL_DECOMPOSITION_P (olddecl))
1802 || (VAR_P (newdecl) && DECL_DECOMPOSITION_P (newdecl)))
1803 /* A structured binding must be unique in its declarative region. */;
1804 else if (DECL_IMPLICIT_TYPEDEF_P (olddecl)
1805 || DECL_IMPLICIT_TYPEDEF_P (newdecl))
1806 /* One is an implicit typedef, that's ok. */
1807 return NULL_TREE;
1809 error ("%q#D redeclared as different kind of entity", newdecl);
1810 inform (olddecl_loc, "previous declaration %q#D", olddecl);
1812 return error_mark_node;
1814 else if (!types_match)
1816 if (CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl))
1817 /* These are certainly not duplicate declarations; they're
1818 from different scopes. */
1819 return NULL_TREE;
1821 if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1823 tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1824 tree newres = DECL_TEMPLATE_RESULT (newdecl);
1826 /* The name of a class template may not be declared to refer to
1827 any other template, class, function, object, namespace, value,
1828 or type in the same scope. */
1829 if (TREE_CODE (oldres) == TYPE_DECL
1830 || TREE_CODE (newres) == TYPE_DECL)
1832 error_at (newdecl_loc,
1833 "conflicting declaration of template %q#D", newdecl);
1834 inform (olddecl_loc,
1835 "previous declaration %q#D", olddecl);
1836 return error_mark_node;
1839 else if (TREE_CODE (oldres) == FUNCTION_DECL
1840 && TREE_CODE (newres) == FUNCTION_DECL)
1842 if (duplicate_function_template_decls (newdecl, olddecl))
1843 return error_mark_node;
1844 return NULL_TREE;
1846 else if (check_concept_refinement (olddecl, newdecl))
1847 return error_mark_node;
1848 return NULL_TREE;
1850 if (TREE_CODE (newdecl) == FUNCTION_DECL)
1852 if (DECL_EXTERN_C_P (newdecl) && DECL_EXTERN_C_P (olddecl))
1854 error_at (newdecl_loc,
1855 "conflicting declaration of C function %q#D",
1856 newdecl);
1857 inform (olddecl_loc,
1858 "previous declaration %q#D", olddecl);
1859 return error_mark_node;
1861 /* For function versions, params and types match, but they
1862 are not ambiguous. */
1863 else if ((!DECL_FUNCTION_VERSIONED (newdecl)
1864 && !DECL_FUNCTION_VERSIONED (olddecl))
1865 // The functions have the same parameter types.
1866 && compparms (TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1867 TYPE_ARG_TYPES (TREE_TYPE (olddecl)))
1868 // And the same constraints.
1869 && equivalently_constrained (newdecl, olddecl))
1871 error_at (newdecl_loc,
1872 "ambiguating new declaration of %q#D", newdecl);
1873 inform (olddecl_loc,
1874 "old declaration %q#D", olddecl);
1875 return error_mark_node;
1877 else
1878 return NULL_TREE;
1880 else
1882 error_at (newdecl_loc, "conflicting declaration %q#D", newdecl);
1883 inform (olddecl_loc,
1884 "previous declaration as %q#D", olddecl);
1885 return error_mark_node;
1888 else if (TREE_CODE (newdecl) == FUNCTION_DECL
1889 && DECL_OMP_DECLARE_REDUCTION_P (newdecl))
1891 /* OMP UDRs are never duplicates. */
1892 gcc_assert (DECL_OMP_DECLARE_REDUCTION_P (olddecl));
1893 error_at (newdecl_loc,
1894 "redeclaration of %<pragma omp declare reduction%>");
1895 inform (olddecl_loc,
1896 "previous %<pragma omp declare reduction%> declaration");
1897 return error_mark_node;
1899 else if (TREE_CODE (newdecl) == FUNCTION_DECL
1900 && ((DECL_TEMPLATE_SPECIALIZATION (olddecl)
1901 && (!DECL_TEMPLATE_INFO (newdecl)
1902 || (DECL_TI_TEMPLATE (newdecl)
1903 != DECL_TI_TEMPLATE (olddecl))))
1904 || (DECL_TEMPLATE_SPECIALIZATION (newdecl)
1905 && (!DECL_TEMPLATE_INFO (olddecl)
1906 || (DECL_TI_TEMPLATE (olddecl)
1907 != DECL_TI_TEMPLATE (newdecl))))))
1908 /* It's OK to have a template specialization and a non-template
1909 with the same type, or to have specializations of two
1910 different templates with the same type. Note that if one is a
1911 specialization, and the other is an instantiation of the same
1912 template, that we do not exit at this point. That situation
1913 can occur if we instantiate a template class, and then
1914 specialize one of its methods. This situation is valid, but
1915 the declarations must be merged in the usual way. */
1916 return NULL_TREE;
1917 else if (TREE_CODE (newdecl) == FUNCTION_DECL
1918 && ((DECL_TEMPLATE_INSTANTIATION (olddecl)
1919 && !DECL_USE_TEMPLATE (newdecl))
1920 || (DECL_TEMPLATE_INSTANTIATION (newdecl)
1921 && !DECL_USE_TEMPLATE (olddecl))))
1922 /* One of the declarations is a template instantiation, and the
1923 other is not a template at all. That's OK. */
1924 return NULL_TREE;
1925 else if (TREE_CODE (newdecl) == NAMESPACE_DECL)
1927 /* In [namespace.alias] we have:
1929 In a declarative region, a namespace-alias-definition can be
1930 used to redefine a namespace-alias declared in that declarative
1931 region to refer only to the namespace to which it already
1932 refers.
1934 Therefore, if we encounter a second alias directive for the same
1935 alias, we can just ignore the second directive. */
1936 if (DECL_NAMESPACE_ALIAS (newdecl)
1937 && (DECL_NAMESPACE_ALIAS (newdecl)
1938 == DECL_NAMESPACE_ALIAS (olddecl)))
1939 return olddecl;
1941 /* Leave it to update_binding to merge or report error. */
1942 return NULL_TREE;
1944 else
1946 const char *errmsg = redeclaration_error_message (newdecl, olddecl);
1947 if (errmsg)
1949 auto_diagnostic_group d;
1950 error_at (newdecl_loc, errmsg, newdecl);
1951 if (DECL_NAME (olddecl) != NULL_TREE)
1952 inform (olddecl_loc,
1953 (DECL_INITIAL (olddecl) && namespace_bindings_p ())
1954 ? G_("%q#D previously defined here")
1955 : G_("%q#D previously declared here"), olddecl);
1956 return error_mark_node;
1958 else if (TREE_CODE (olddecl) == FUNCTION_DECL
1959 && DECL_INITIAL (olddecl) != NULL_TREE
1960 && !prototype_p (TREE_TYPE (olddecl))
1961 && prototype_p (TREE_TYPE (newdecl)))
1963 /* Prototype decl follows defn w/o prototype. */
1964 auto_diagnostic_group d;
1965 if (warning_at (newdecl_loc, 0,
1966 "prototype specified for %q#D", newdecl))
1967 inform (olddecl_loc,
1968 "previous non-prototype definition here");
1970 else if (VAR_OR_FUNCTION_DECL_P (olddecl)
1971 && DECL_LANGUAGE (newdecl) != DECL_LANGUAGE (olddecl))
1973 /* [dcl.link]
1974 If two declarations of the same function or object
1975 specify different linkage-specifications ..., the program
1976 is ill-formed.... Except for functions with C++ linkage,
1977 a function declaration without a linkage specification
1978 shall not precede the first linkage specification for
1979 that function. A function can be declared without a
1980 linkage specification after an explicit linkage
1981 specification has been seen; the linkage explicitly
1982 specified in the earlier declaration is not affected by
1983 such a function declaration.
1985 DR 563 raises the question why the restrictions on
1986 functions should not also apply to objects. Older
1987 versions of G++ silently ignore the linkage-specification
1988 for this example:
1990 namespace N {
1991 extern int i;
1992 extern "C" int i;
1995 which is clearly wrong. Therefore, we now treat objects
1996 like functions. */
1997 if (current_lang_depth () == 0)
1999 /* There is no explicit linkage-specification, so we use
2000 the linkage from the previous declaration. */
2001 retrofit_lang_decl (newdecl);
2002 SET_DECL_LANGUAGE (newdecl, DECL_LANGUAGE (olddecl));
2004 else
2006 auto_diagnostic_group d;
2007 error_at (newdecl_loc,
2008 "conflicting declaration of %q#D with %qL linkage",
2009 newdecl, DECL_LANGUAGE (newdecl));
2010 inform (olddecl_loc,
2011 "previous declaration with %qL linkage",
2012 DECL_LANGUAGE (olddecl));
2016 if (DECL_LANG_SPECIFIC (olddecl) && DECL_USE_TEMPLATE (olddecl))
2018 else if (TREE_CODE (olddecl) == FUNCTION_DECL)
2020 /* Note: free functions, as TEMPLATE_DECLs, are handled below. */
2021 if (DECL_FUNCTION_MEMBER_P (olddecl)
2022 && (/* grokfndecl passes member function templates too
2023 as FUNCTION_DECLs. */
2024 DECL_TEMPLATE_INFO (olddecl)
2025 /* C++11 8.3.6/6.
2026 Default arguments for a member function of a class
2027 template shall be specified on the initial declaration
2028 of the member function within the class template. */
2029 || CLASSTYPE_TEMPLATE_INFO (CP_DECL_CONTEXT (olddecl))))
2031 check_redeclaration_no_default_args (newdecl);
2033 if (DECL_TEMPLATE_INFO (olddecl)
2034 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (olddecl)))
2036 tree new_parms = DECL_TEMPLATE_INFO (newdecl)
2037 ? DECL_INNERMOST_TEMPLATE_PARMS (DECL_TI_TEMPLATE (newdecl))
2038 : INNERMOST_TEMPLATE_PARMS (current_template_parms);
2039 tree old_parms
2040 = DECL_INNERMOST_TEMPLATE_PARMS (DECL_TI_TEMPLATE (olddecl));
2041 merge_default_template_args (new_parms, old_parms,
2042 /*class_p=*/false);
2045 else
2047 tree t1 = FUNCTION_FIRST_USER_PARMTYPE (olddecl);
2048 tree t2 = FUNCTION_FIRST_USER_PARMTYPE (newdecl);
2049 int i = 1;
2051 for (; t1 && t1 != void_list_node;
2052 t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2), i++)
2053 if (TREE_PURPOSE (t1) && TREE_PURPOSE (t2))
2055 if (simple_cst_equal (TREE_PURPOSE (t1),
2056 TREE_PURPOSE (t2)) == 1)
2058 auto_diagnostic_group d;
2059 if (permerror (newdecl_loc,
2060 "default argument given for parameter "
2061 "%d of %q#D", i, newdecl))
2062 inform (olddecl_loc,
2063 "previous specification in %q#D here",
2064 olddecl);
2066 else
2068 auto_diagnostic_group d;
2069 error_at (newdecl_loc,
2070 "default argument given for parameter %d "
2071 "of %q#D", i, newdecl);
2072 inform (olddecl_loc,
2073 "previous specification in %q#D here",
2074 olddecl);
2078 /* C++17 11.3.6/4: "If a friend declaration specifies a default
2079 argument expression, that declaration... shall be the only
2080 declaration of the function or function template in the
2081 translation unit." */
2082 check_no_redeclaration_friend_default_args (olddecl, newdecl);
2087 /* Do not merge an implicit typedef with an explicit one. In:
2089 class A;
2091 typedef class A A __attribute__ ((foo));
2093 the attribute should apply only to the typedef. */
2094 if (TREE_CODE (olddecl) == TYPE_DECL
2095 && (DECL_IMPLICIT_TYPEDEF_P (olddecl)
2096 || DECL_IMPLICIT_TYPEDEF_P (newdecl)))
2097 return NULL_TREE;
2099 if (DECL_TEMPLATE_PARM_P (olddecl) != DECL_TEMPLATE_PARM_P (newdecl))
2100 return NULL_TREE;
2102 if (!validate_constexpr_redeclaration (olddecl, newdecl))
2103 return error_mark_node;
2105 if (modules_p ()
2106 && TREE_CODE (CP_DECL_CONTEXT (olddecl)) == NAMESPACE_DECL
2107 && TREE_CODE (olddecl) != NAMESPACE_DECL
2108 && !hiding)
2110 if (DECL_ARTIFICIAL (olddecl))
2112 if (!(global_purview_p () || not_module_p ()))
2113 error ("declaration %qD conflicts with builtin", newdecl);
2114 else
2115 DECL_MODULE_EXPORT_P (olddecl) = DECL_MODULE_EXPORT_P (newdecl);
2117 else
2119 if (!module_may_redeclare (olddecl))
2121 error ("declaration %qD conflicts with import", newdecl);
2122 inform (olddecl_loc, "import declared %q#D here", olddecl);
2124 return error_mark_node;
2127 if (DECL_MODULE_EXPORT_P (newdecl)
2128 && !DECL_MODULE_EXPORT_P (olddecl))
2130 error ("conflicting exporting declaration %qD", newdecl);
2131 inform (olddecl_loc, "previous declaration %q#D here", olddecl);
2136 /* We have committed to returning OLDDECL at this point. */
2138 /* If new decl is `static' and an `extern' was seen previously,
2139 warn about it. */
2140 warn_extern_redeclared_static (newdecl, olddecl);
2142 /* True to merge attributes between the declarations, false to
2143 set OLDDECL's attributes to those of NEWDECL (for template
2144 explicit specializations that specify their own attributes
2145 independent of those specified for the primary template). */
2146 const bool merge_attr = (TREE_CODE (newdecl) != FUNCTION_DECL
2147 || !DECL_TEMPLATE_SPECIALIZATION (newdecl)
2148 || DECL_TEMPLATE_SPECIALIZATION (olddecl));
2150 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2152 if (merge_attr)
2154 if (diagnose_mismatched_attributes (olddecl, newdecl))
2155 inform (olddecl_loc, DECL_INITIAL (olddecl)
2156 ? G_("previous definition of %qD here")
2157 : G_("previous declaration of %qD here"), olddecl);
2159 /* [dcl.attr.noreturn]: The first declaration of a function shall
2160 specify the noreturn attribute if any declaration of that function
2161 specifies the noreturn attribute. */
2162 tree a;
2163 if (TREE_THIS_VOLATILE (newdecl)
2164 && !TREE_THIS_VOLATILE (olddecl)
2165 /* This applies to [[noreturn]] only, not its GNU variants. */
2166 && (a = lookup_attribute ("noreturn", DECL_ATTRIBUTES (newdecl)))
2167 && cxx11_attribute_p (a)
2168 && get_attribute_namespace (a) == NULL_TREE)
2170 error_at (newdecl_loc, "function %qD declared %<[[noreturn]]%> "
2171 "but its first declaration was not", newdecl);
2172 inform (olddecl_loc, "previous declaration of %qD", olddecl);
2176 /* Now that functions must hold information normally held
2177 by field decls, there is extra work to do so that
2178 declaration information does not get destroyed during
2179 definition. */
2180 if (DECL_VINDEX (olddecl))
2181 DECL_VINDEX (newdecl) = DECL_VINDEX (olddecl);
2182 if (DECL_CONTEXT (olddecl))
2183 DECL_CONTEXT (newdecl) = DECL_CONTEXT (olddecl);
2184 DECL_STATIC_CONSTRUCTOR (newdecl) |= DECL_STATIC_CONSTRUCTOR (olddecl);
2185 DECL_STATIC_DESTRUCTOR (newdecl) |= DECL_STATIC_DESTRUCTOR (olddecl);
2186 DECL_PURE_VIRTUAL_P (newdecl) |= DECL_PURE_VIRTUAL_P (olddecl);
2187 DECL_VIRTUAL_P (newdecl) |= DECL_VIRTUAL_P (olddecl);
2188 DECL_INVALID_OVERRIDER_P (newdecl) |= DECL_INVALID_OVERRIDER_P (olddecl);
2189 DECL_FINAL_P (newdecl) |= DECL_FINAL_P (olddecl);
2190 DECL_OVERRIDE_P (newdecl) |= DECL_OVERRIDE_P (olddecl);
2191 DECL_THIS_STATIC (newdecl) |= DECL_THIS_STATIC (olddecl);
2192 DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (newdecl)
2193 |= DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (olddecl);
2194 if (DECL_OVERLOADED_OPERATOR_P (olddecl))
2195 DECL_OVERLOADED_OPERATOR_CODE_RAW (newdecl)
2196 = DECL_OVERLOADED_OPERATOR_CODE_RAW (olddecl);
2197 new_defines_function = DECL_INITIAL (newdecl) != NULL_TREE;
2199 /* Optionally warn about more than one declaration for the same
2200 name, but don't warn about a function declaration followed by a
2201 definition. */
2202 if (warn_redundant_decls && ! DECL_ARTIFICIAL (olddecl)
2203 && !(new_defines_function && DECL_INITIAL (olddecl) == NULL_TREE)
2204 /* Don't warn about extern decl followed by definition. */
2205 && !(DECL_EXTERNAL (olddecl) && ! DECL_EXTERNAL (newdecl))
2206 /* Don't warn if at least one is/was hidden. */
2207 && !(hiding || was_hidden)
2208 /* Don't warn about declaration followed by specialization. */
2209 && (! DECL_TEMPLATE_SPECIALIZATION (newdecl)
2210 || DECL_TEMPLATE_SPECIALIZATION (olddecl)))
2212 auto_diagnostic_group d;
2213 if (warning_at (newdecl_loc,
2214 OPT_Wredundant_decls,
2215 "redundant redeclaration of %qD in same scope",
2216 newdecl))
2217 inform (olddecl_loc,
2218 "previous declaration of %qD", olddecl);
2221 /* [dcl.fct.def.delete] A deleted definition of a function shall be the
2222 first declaration of the function or, for an explicit specialization
2223 of a function template, the first declaration of that
2224 specialization. */
2225 if (!(DECL_TEMPLATE_INSTANTIATION (olddecl)
2226 && DECL_TEMPLATE_SPECIALIZATION (newdecl)))
2228 if (DECL_DELETED_FN (newdecl))
2230 auto_diagnostic_group d;
2231 if (pedwarn (newdecl_loc, 0, "deleted definition of %qD "
2232 "is not first declaration", newdecl))
2233 inform (olddecl_loc,
2234 "previous declaration of %qD", olddecl);
2236 DECL_DELETED_FN (newdecl) |= DECL_DELETED_FN (olddecl);
2240 /* Deal with C++: must preserve virtual function table size. */
2241 if (TREE_CODE (olddecl) == TYPE_DECL)
2243 tree newtype = TREE_TYPE (newdecl);
2244 tree oldtype = TREE_TYPE (olddecl);
2246 if (newtype != error_mark_node && oldtype != error_mark_node
2247 && TYPE_LANG_SPECIFIC (newtype) && TYPE_LANG_SPECIFIC (oldtype))
2248 CLASSTYPE_FRIEND_CLASSES (newtype)
2249 = CLASSTYPE_FRIEND_CLASSES (oldtype);
2251 DECL_ORIGINAL_TYPE (newdecl) = DECL_ORIGINAL_TYPE (olddecl);
2254 /* Copy all the DECL_... slots specified in the new decl except for
2255 any that we copy here from the old type. */
2256 if (merge_attr)
2257 DECL_ATTRIBUTES (newdecl)
2258 = (*targetm.merge_decl_attributes) (olddecl, newdecl);
2259 else
2260 DECL_ATTRIBUTES (olddecl) = DECL_ATTRIBUTES (newdecl);
2262 if (TREE_CODE (newdecl) == TEMPLATE_DECL)
2264 tree old_result = DECL_TEMPLATE_RESULT (olddecl);
2265 tree new_result = DECL_TEMPLATE_RESULT (newdecl);
2266 TREE_TYPE (olddecl) = TREE_TYPE (old_result);
2268 /* The new decl should not already have gathered any
2269 specializations. */
2270 gcc_assert (!DECL_TEMPLATE_SPECIALIZATIONS (newdecl));
2272 DECL_ATTRIBUTES (old_result)
2273 = (*targetm.merge_decl_attributes) (old_result, new_result);
2275 if (DECL_FUNCTION_TEMPLATE_P (newdecl))
2277 if (DECL_SOURCE_LOCATION (newdecl)
2278 != DECL_SOURCE_LOCATION (olddecl))
2280 /* Per C++11 8.3.6/4, default arguments cannot be added in
2281 later declarations of a function template. */
2282 check_redeclaration_no_default_args (newdecl);
2283 /* C++17 11.3.6/4: "If a friend declaration specifies a default
2284 argument expression, that declaration... shall be the only
2285 declaration of the function or function template in the
2286 translation unit." */
2287 check_no_redeclaration_friend_default_args
2288 (old_result, new_result);
2290 tree new_parms = DECL_INNERMOST_TEMPLATE_PARMS (newdecl);
2291 tree old_parms = DECL_INNERMOST_TEMPLATE_PARMS (olddecl);
2292 merge_default_template_args (new_parms, old_parms,
2293 /*class_p=*/false);
2295 if (!DECL_UNIQUE_FRIEND_P (old_result))
2296 DECL_UNIQUE_FRIEND_P (new_result) = false;
2298 check_default_args (newdecl);
2300 if (GNU_INLINE_P (old_result) != GNU_INLINE_P (new_result)
2301 && DECL_INITIAL (new_result))
2303 if (DECL_INITIAL (old_result))
2304 DECL_UNINLINABLE (old_result) = 1;
2305 else
2306 DECL_UNINLINABLE (old_result) = DECL_UNINLINABLE (new_result);
2307 DECL_EXTERNAL (old_result) = DECL_EXTERNAL (new_result);
2308 DECL_NOT_REALLY_EXTERN (old_result)
2309 = DECL_NOT_REALLY_EXTERN (new_result);
2310 DECL_INTERFACE_KNOWN (old_result)
2311 = DECL_INTERFACE_KNOWN (new_result);
2312 DECL_DECLARED_INLINE_P (old_result)
2313 = DECL_DECLARED_INLINE_P (new_result);
2314 DECL_DISREGARD_INLINE_LIMITS (old_result)
2315 |= DECL_DISREGARD_INLINE_LIMITS (new_result);
2318 else
2320 DECL_DECLARED_INLINE_P (old_result)
2321 |= DECL_DECLARED_INLINE_P (new_result);
2322 DECL_DISREGARD_INLINE_LIMITS (old_result)
2323 |= DECL_DISREGARD_INLINE_LIMITS (new_result);
2324 check_redeclaration_exception_specification (newdecl, olddecl);
2326 merge_attribute_bits (new_result, old_result);
2330 /* If the new declaration is a definition, update the file and
2331 line information on the declaration, and also make
2332 the old declaration the same definition. */
2333 if (DECL_INITIAL (new_result) != NULL_TREE)
2335 DECL_SOURCE_LOCATION (olddecl)
2336 = DECL_SOURCE_LOCATION (old_result)
2337 = DECL_SOURCE_LOCATION (newdecl);
2338 DECL_INITIAL (old_result) = DECL_INITIAL (new_result);
2339 if (DECL_FUNCTION_TEMPLATE_P (newdecl))
2341 tree parm;
2342 DECL_ARGUMENTS (old_result)
2343 = DECL_ARGUMENTS (new_result);
2344 for (parm = DECL_ARGUMENTS (old_result); parm;
2345 parm = DECL_CHAIN (parm))
2346 DECL_CONTEXT (parm) = old_result;
2350 return olddecl;
2353 if (types_match)
2355 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2356 check_redeclaration_exception_specification (newdecl, olddecl);
2358 /* Automatically handles default parameters. */
2359 tree oldtype = TREE_TYPE (olddecl);
2360 tree newtype;
2362 /* For typedefs use the old type, as the new type's DECL_NAME points
2363 at newdecl, which will be ggc_freed. */
2364 if (TREE_CODE (newdecl) == TYPE_DECL)
2366 /* But NEWTYPE might have an attribute, honor that. */
2367 tree tem = TREE_TYPE (newdecl);
2368 newtype = oldtype;
2370 if (TYPE_USER_ALIGN (tem))
2372 if (TYPE_ALIGN (tem) > TYPE_ALIGN (newtype))
2373 SET_TYPE_ALIGN (newtype, TYPE_ALIGN (tem));
2374 TYPE_USER_ALIGN (newtype) = true;
2377 /* And remove the new type from the variants list. */
2378 if (TYPE_NAME (TREE_TYPE (newdecl)) == newdecl)
2380 tree remove = TREE_TYPE (newdecl);
2381 if (TYPE_MAIN_VARIANT (remove) == remove)
2383 gcc_assert (TYPE_NEXT_VARIANT (remove) == NULL_TREE);
2384 /* If remove is the main variant, no need to remove that
2385 from the list. One of the DECL_ORIGINAL_TYPE
2386 variants, e.g. created for aligned attribute, might still
2387 refer to the newdecl TYPE_DECL though, so remove that one
2388 in that case. */
2389 if (tree orig = DECL_ORIGINAL_TYPE (newdecl))
2390 if (orig != remove)
2391 for (tree t = TYPE_MAIN_VARIANT (orig); t;
2392 t = TYPE_MAIN_VARIANT (t))
2393 if (TYPE_NAME (TYPE_NEXT_VARIANT (t)) == newdecl)
2395 TYPE_NEXT_VARIANT (t)
2396 = TYPE_NEXT_VARIANT (TYPE_NEXT_VARIANT (t));
2397 break;
2400 else
2401 for (tree t = TYPE_MAIN_VARIANT (remove); ;
2402 t = TYPE_NEXT_VARIANT (t))
2403 if (TYPE_NEXT_VARIANT (t) == remove)
2405 TYPE_NEXT_VARIANT (t) = TYPE_NEXT_VARIANT (remove);
2406 break;
2410 else if (merge_attr)
2411 newtype = merge_types (TREE_TYPE (newdecl), TREE_TYPE (olddecl));
2412 else
2413 newtype = TREE_TYPE (newdecl);
2415 if (VAR_P (newdecl))
2417 DECL_THIS_EXTERN (newdecl) |= DECL_THIS_EXTERN (olddecl);
2418 /* For already initialized vars, TREE_READONLY could have been
2419 cleared in cp_finish_decl, because the var needs runtime
2420 initialization or destruction. Make sure not to set
2421 TREE_READONLY on it again. */
2422 if (DECL_INITIALIZED_P (olddecl)
2423 && !DECL_EXTERNAL (olddecl)
2424 && !TREE_READONLY (olddecl))
2425 TREE_READONLY (newdecl) = 0;
2426 DECL_INITIALIZED_P (newdecl) |= DECL_INITIALIZED_P (olddecl);
2427 DECL_NONTRIVIALLY_INITIALIZED_P (newdecl)
2428 |= DECL_NONTRIVIALLY_INITIALIZED_P (olddecl);
2429 if (DECL_DEPENDENT_INIT_P (olddecl))
2430 SET_DECL_DEPENDENT_INIT_P (newdecl, true);
2431 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (newdecl)
2432 |= DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (olddecl);
2433 DECL_DECLARED_CONSTEXPR_P (newdecl)
2434 |= DECL_DECLARED_CONSTEXPR_P (olddecl);
2435 DECL_DECLARED_CONSTINIT_P (newdecl)
2436 |= DECL_DECLARED_CONSTINIT_P (olddecl);
2438 /* Merge the threadprivate attribute from OLDDECL into NEWDECL. */
2439 if (DECL_LANG_SPECIFIC (olddecl)
2440 && CP_DECL_THREADPRIVATE_P (olddecl))
2442 /* Allocate a LANG_SPECIFIC structure for NEWDECL, if needed. */
2443 retrofit_lang_decl (newdecl);
2444 CP_DECL_THREADPRIVATE_P (newdecl) = 1;
2448 /* An explicit specialization of a function template or of a member
2449 function of a class template can be declared transaction_safe
2450 independently of whether the corresponding template entity is declared
2451 transaction_safe. */
2452 if (flag_tm && TREE_CODE (newdecl) == FUNCTION_DECL
2453 && DECL_TEMPLATE_INSTANTIATION (olddecl)
2454 && DECL_TEMPLATE_SPECIALIZATION (newdecl)
2455 && tx_safe_fn_type_p (newtype)
2456 && !tx_safe_fn_type_p (TREE_TYPE (newdecl)))
2457 newtype = tx_unsafe_fn_variant (newtype);
2459 TREE_TYPE (newdecl) = TREE_TYPE (olddecl) = newtype;
2461 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2462 check_default_args (newdecl);
2464 /* Lay the type out, unless already done. */
2465 if (! same_type_p (newtype, oldtype)
2466 && TREE_TYPE (newdecl) != error_mark_node
2467 && !(processing_template_decl && uses_template_parms (newdecl)))
2468 layout_type (TREE_TYPE (newdecl));
2470 if ((VAR_P (newdecl)
2471 || TREE_CODE (newdecl) == PARM_DECL
2472 || TREE_CODE (newdecl) == RESULT_DECL
2473 || TREE_CODE (newdecl) == FIELD_DECL
2474 || TREE_CODE (newdecl) == TYPE_DECL)
2475 && !(processing_template_decl && uses_template_parms (newdecl)))
2476 layout_decl (newdecl, 0);
2478 /* Merge deprecatedness. */
2479 if (TREE_DEPRECATED (newdecl))
2480 TREE_DEPRECATED (olddecl) = 1;
2482 /* Merge unavailability. */
2483 if (TREE_UNAVAILABLE (newdecl))
2484 TREE_UNAVAILABLE (olddecl) = 1;
2486 /* Preserve function specific target and optimization options */
2487 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2489 if (DECL_FUNCTION_SPECIFIC_TARGET (olddecl)
2490 && !DECL_FUNCTION_SPECIFIC_TARGET (newdecl))
2491 DECL_FUNCTION_SPECIFIC_TARGET (newdecl)
2492 = DECL_FUNCTION_SPECIFIC_TARGET (olddecl);
2494 if (DECL_FUNCTION_SPECIFIC_OPTIMIZATION (olddecl)
2495 && !DECL_FUNCTION_SPECIFIC_OPTIMIZATION (newdecl))
2496 DECL_FUNCTION_SPECIFIC_OPTIMIZATION (newdecl)
2497 = DECL_FUNCTION_SPECIFIC_OPTIMIZATION (olddecl);
2499 if (!DECL_UNIQUE_FRIEND_P (olddecl))
2500 DECL_UNIQUE_FRIEND_P (newdecl) = false;
2502 else
2504 /* Merge the const type qualifier. */
2505 if (TREE_READONLY (newdecl))
2506 TREE_READONLY (olddecl) = 1;
2507 /* Merge the volatile type qualifier. */
2508 if (TREE_THIS_VOLATILE (newdecl))
2509 TREE_THIS_VOLATILE (olddecl) = 1;
2512 /* Merge the initialization information. */
2513 if (DECL_INITIAL (newdecl) == NULL_TREE
2514 && DECL_INITIAL (olddecl) != NULL_TREE)
2516 DECL_INITIAL (newdecl) = DECL_INITIAL (olddecl);
2517 DECL_SOURCE_LOCATION (newdecl) = DECL_SOURCE_LOCATION (olddecl);
2518 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2520 DECL_SAVED_TREE (newdecl) = DECL_SAVED_TREE (olddecl);
2521 DECL_STRUCT_FUNCTION (newdecl) = DECL_STRUCT_FUNCTION (olddecl);
2525 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2527 DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (newdecl)
2528 |= DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (olddecl);
2529 DECL_NO_LIMIT_STACK (newdecl) |= DECL_NO_LIMIT_STACK (olddecl);
2530 if (DECL_IS_OPERATOR_NEW_P (olddecl))
2531 DECL_SET_IS_OPERATOR_NEW (newdecl, true);
2532 DECL_LOOPING_CONST_OR_PURE_P (newdecl)
2533 |= DECL_LOOPING_CONST_OR_PURE_P (olddecl);
2534 DECL_IS_REPLACEABLE_OPERATOR (newdecl)
2535 |= DECL_IS_REPLACEABLE_OPERATOR (olddecl);
2537 if (merge_attr)
2538 merge_attribute_bits (newdecl, olddecl);
2539 else
2541 /* Merge the noreturn bit. */
2542 TREE_THIS_VOLATILE (olddecl) = TREE_THIS_VOLATILE (newdecl);
2543 TREE_READONLY (olddecl) = TREE_READONLY (newdecl);
2544 TREE_NOTHROW (olddecl) = TREE_NOTHROW (newdecl);
2545 DECL_IS_MALLOC (olddecl) = DECL_IS_MALLOC (newdecl);
2546 DECL_PURE_P (olddecl) = DECL_PURE_P (newdecl);
2548 /* Keep the old RTL. */
2549 COPY_DECL_RTL (olddecl, newdecl);
2551 else if (VAR_P (newdecl)
2552 && (DECL_SIZE (olddecl) || !DECL_SIZE (newdecl)))
2554 /* Keep the old RTL. We cannot keep the old RTL if the old
2555 declaration was for an incomplete object and the new
2556 declaration is not since many attributes of the RTL will
2557 change. */
2558 COPY_DECL_RTL (olddecl, newdecl);
2561 /* If cannot merge, then use the new type and qualifiers,
2562 and don't preserve the old rtl. */
2563 else
2565 /* Clean out any memory we had of the old declaration. */
2566 tree oldstatic = value_member (olddecl, static_aggregates);
2567 if (oldstatic)
2568 TREE_VALUE (oldstatic) = error_mark_node;
2570 TREE_TYPE (olddecl) = TREE_TYPE (newdecl);
2571 TREE_READONLY (olddecl) = TREE_READONLY (newdecl);
2572 TREE_THIS_VOLATILE (olddecl) = TREE_THIS_VOLATILE (newdecl);
2573 TREE_NOTHROW (olddecl) = TREE_NOTHROW (newdecl);
2574 TREE_SIDE_EFFECTS (olddecl) = TREE_SIDE_EFFECTS (newdecl);
2577 /* Merge the storage class information. */
2578 merge_weak (newdecl, olddecl);
2580 DECL_DEFER_OUTPUT (newdecl) |= DECL_DEFER_OUTPUT (olddecl);
2581 TREE_PUBLIC (newdecl) = TREE_PUBLIC (olddecl);
2582 TREE_STATIC (olddecl) = TREE_STATIC (newdecl) |= TREE_STATIC (olddecl);
2583 if (! DECL_EXTERNAL (olddecl))
2584 DECL_EXTERNAL (newdecl) = 0;
2585 if (! DECL_COMDAT (olddecl))
2586 DECL_COMDAT (newdecl) = 0;
2588 if (VAR_OR_FUNCTION_DECL_P (newdecl) && DECL_LOCAL_DECL_P (newdecl))
2590 if (!DECL_LOCAL_DECL_P (olddecl))
2591 /* This can happen if olddecl was brought in from the
2592 enclosing namespace via a using-decl. The new decl is
2593 then not a block-scope extern at all. */
2594 DECL_LOCAL_DECL_P (newdecl) = false;
2595 else
2597 retrofit_lang_decl (newdecl);
2598 DECL_LOCAL_DECL_ALIAS (newdecl) = DECL_LOCAL_DECL_ALIAS (olddecl);
2602 new_template_info = NULL_TREE;
2603 if (DECL_LANG_SPECIFIC (newdecl) && DECL_LANG_SPECIFIC (olddecl))
2605 bool new_redefines_gnu_inline = false;
2607 if (new_defines_function
2608 && ((DECL_INTERFACE_KNOWN (olddecl)
2609 && TREE_CODE (olddecl) == FUNCTION_DECL)
2610 || (TREE_CODE (olddecl) == TEMPLATE_DECL
2611 && (TREE_CODE (DECL_TEMPLATE_RESULT (olddecl))
2612 == FUNCTION_DECL))))
2613 new_redefines_gnu_inline = GNU_INLINE_P (STRIP_TEMPLATE (olddecl));
2615 if (!new_redefines_gnu_inline)
2617 DECL_INTERFACE_KNOWN (newdecl) |= DECL_INTERFACE_KNOWN (olddecl);
2618 DECL_NOT_REALLY_EXTERN (newdecl) |= DECL_NOT_REALLY_EXTERN (olddecl);
2619 DECL_COMDAT (newdecl) |= DECL_COMDAT (olddecl);
2622 if (TREE_CODE (newdecl) != TYPE_DECL)
2624 DECL_TEMPLATE_INSTANTIATED (newdecl)
2625 |= DECL_TEMPLATE_INSTANTIATED (olddecl);
2626 DECL_ODR_USED (newdecl) |= DECL_ODR_USED (olddecl);
2628 /* If the OLDDECL is an instantiation and/or specialization,
2629 then the NEWDECL must be too. But, it may not yet be marked
2630 as such if the caller has created NEWDECL, but has not yet
2631 figured out that it is a redeclaration. */
2632 if (!DECL_USE_TEMPLATE (newdecl))
2633 DECL_USE_TEMPLATE (newdecl) = DECL_USE_TEMPLATE (olddecl);
2635 if (!DECL_TEMPLATE_SPECIALIZATION (newdecl))
2636 DECL_INITIALIZED_IN_CLASS_P (newdecl)
2637 |= DECL_INITIALIZED_IN_CLASS_P (olddecl);
2640 /* Don't really know how much of the language-specific
2641 values we should copy from old to new. */
2642 DECL_IN_AGGR_P (newdecl) = DECL_IN_AGGR_P (olddecl);
2644 if (LANG_DECL_HAS_MIN (newdecl))
2646 DECL_ACCESS (newdecl) = DECL_ACCESS (olddecl);
2647 if (DECL_TEMPLATE_INFO (newdecl))
2649 new_template_info = DECL_TEMPLATE_INFO (newdecl);
2650 if (DECL_TEMPLATE_INSTANTIATION (olddecl)
2651 && DECL_TEMPLATE_SPECIALIZATION (newdecl))
2652 /* Remember the presence of explicit specialization args. */
2653 TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (olddecl))
2654 = TINFO_USED_TEMPLATE_ID (new_template_info);
2656 DECL_TEMPLATE_INFO (newdecl) = DECL_TEMPLATE_INFO (olddecl);
2659 if (DECL_DECLARES_FUNCTION_P (newdecl))
2661 /* Only functions have these fields. */
2662 DECL_NONCONVERTING_P (newdecl) = DECL_NONCONVERTING_P (olddecl);
2663 DECL_BEFRIENDING_CLASSES (newdecl)
2664 = chainon (DECL_BEFRIENDING_CLASSES (newdecl),
2665 DECL_BEFRIENDING_CLASSES (olddecl));
2666 /* DECL_THUNKS is only valid for virtual functions,
2667 otherwise it is a DECL_FRIEND_CONTEXT. */
2668 if (DECL_VIRTUAL_P (newdecl))
2669 SET_DECL_THUNKS (newdecl, DECL_THUNKS (olddecl));
2671 else if (VAR_P (newdecl))
2673 /* Only variables have this field. */
2674 if (VAR_HAD_UNKNOWN_BOUND (olddecl))
2675 SET_VAR_HAD_UNKNOWN_BOUND (newdecl);
2679 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2681 tree parm;
2683 /* Merge parameter attributes. */
2684 tree oldarg, newarg;
2685 for (oldarg = DECL_ARGUMENTS(olddecl), newarg = DECL_ARGUMENTS(newdecl);
2686 oldarg && newarg;
2687 oldarg = DECL_CHAIN(oldarg), newarg = DECL_CHAIN(newarg))
2689 DECL_ATTRIBUTES (newarg)
2690 = (*targetm.merge_decl_attributes) (oldarg, newarg);
2691 DECL_ATTRIBUTES (oldarg) = DECL_ATTRIBUTES (newarg);
2694 if (DECL_TEMPLATE_INSTANTIATION (olddecl)
2695 && !DECL_TEMPLATE_INSTANTIATION (newdecl))
2697 /* If newdecl is not a specialization, then it is not a
2698 template-related function at all. And that means that we
2699 should have exited above, returning 0. */
2700 gcc_assert (DECL_TEMPLATE_SPECIALIZATION (newdecl));
2702 if (DECL_ODR_USED (olddecl))
2703 /* From [temp.expl.spec]:
2705 If a template, a member template or the member of a class
2706 template is explicitly specialized then that
2707 specialization shall be declared before the first use of
2708 that specialization that would cause an implicit
2709 instantiation to take place, in every translation unit in
2710 which such a use occurs. */
2711 error ("explicit specialization of %qD after first use",
2712 olddecl);
2714 SET_DECL_TEMPLATE_SPECIALIZATION (olddecl);
2715 DECL_COMDAT (newdecl) = (TREE_PUBLIC (newdecl)
2716 && DECL_DECLARED_INLINE_P (newdecl));
2718 /* Don't propagate visibility from the template to the
2719 specialization here. We'll do that in determine_visibility if
2720 appropriate. */
2721 DECL_VISIBILITY_SPECIFIED (olddecl) = 0;
2723 /* [temp.expl.spec/14] We don't inline explicit specialization
2724 just because the primary template says so. */
2725 gcc_assert (!merge_attr);
2727 DECL_DECLARED_INLINE_P (olddecl)
2728 = DECL_DECLARED_INLINE_P (newdecl);
2730 DECL_DISREGARD_INLINE_LIMITS (olddecl)
2731 = DECL_DISREGARD_INLINE_LIMITS (newdecl);
2733 DECL_UNINLINABLE (olddecl) = DECL_UNINLINABLE (newdecl);
2735 else if (new_defines_function && DECL_INITIAL (olddecl))
2737 /* Never inline re-defined extern inline functions.
2738 FIXME: this could be better handled by keeping both
2739 function as separate declarations. */
2740 DECL_UNINLINABLE (newdecl) = 1;
2742 else
2744 if (DECL_PENDING_INLINE_P (olddecl))
2746 DECL_PENDING_INLINE_P (newdecl) = 1;
2747 DECL_PENDING_INLINE_INFO (newdecl)
2748 = DECL_PENDING_INLINE_INFO (olddecl);
2750 else if (DECL_PENDING_INLINE_P (newdecl))
2752 else if (DECL_SAVED_AUTO_RETURN_TYPE (newdecl) == NULL)
2753 DECL_SAVED_AUTO_RETURN_TYPE (newdecl)
2754 = DECL_SAVED_AUTO_RETURN_TYPE (olddecl);
2756 DECL_DECLARED_INLINE_P (newdecl) |= DECL_DECLARED_INLINE_P (olddecl);
2758 DECL_UNINLINABLE (newdecl) = DECL_UNINLINABLE (olddecl)
2759 = (DECL_UNINLINABLE (newdecl) || DECL_UNINLINABLE (olddecl));
2761 DECL_DISREGARD_INLINE_LIMITS (newdecl)
2762 = DECL_DISREGARD_INLINE_LIMITS (olddecl)
2763 = (DECL_DISREGARD_INLINE_LIMITS (newdecl)
2764 || DECL_DISREGARD_INLINE_LIMITS (olddecl));
2767 /* Preserve abstractness on cloned [cd]tors. */
2768 DECL_ABSTRACT_P (newdecl) = DECL_ABSTRACT_P (olddecl);
2770 /* Update newdecl's parms to point at olddecl. */
2771 for (parm = DECL_ARGUMENTS (newdecl); parm;
2772 parm = DECL_CHAIN (parm))
2773 DECL_CONTEXT (parm) = olddecl;
2775 if (! types_match)
2777 SET_DECL_LANGUAGE (olddecl, DECL_LANGUAGE (newdecl));
2778 COPY_DECL_ASSEMBLER_NAME (newdecl, olddecl);
2779 COPY_DECL_RTL (newdecl, olddecl);
2781 if (! types_match || new_defines_function)
2783 /* These need to be copied so that the names are available.
2784 Note that if the types do match, we'll preserve inline
2785 info and other bits, but if not, we won't. */
2786 DECL_ARGUMENTS (olddecl) = DECL_ARGUMENTS (newdecl);
2787 DECL_RESULT (olddecl) = DECL_RESULT (newdecl);
2789 /* If redeclaring a builtin function, it stays built in
2790 if newdecl is a gnu_inline definition, or if newdecl is just
2791 a declaration. */
2792 if (fndecl_built_in_p (olddecl)
2793 && (new_defines_function ? GNU_INLINE_P (newdecl) : types_match))
2795 copy_decl_built_in_function (newdecl, olddecl);
2796 /* If we're keeping the built-in definition, keep the rtl,
2797 regardless of declaration matches. */
2798 COPY_DECL_RTL (olddecl, newdecl);
2799 if (DECL_BUILT_IN_CLASS (newdecl) == BUILT_IN_NORMAL)
2801 enum built_in_function fncode = DECL_FUNCTION_CODE (newdecl);
2802 if (builtin_decl_explicit_p (fncode))
2804 /* A compatible prototype of these builtin functions
2805 is seen, assume the runtime implements it with
2806 the expected semantics. */
2807 switch (fncode)
2809 case BUILT_IN_STPCPY:
2810 set_builtin_decl_implicit_p (fncode, true);
2811 break;
2812 default:
2813 set_builtin_decl_declared_p (fncode, true);
2814 break;
2818 copy_attributes_to_builtin (newdecl);
2821 if (new_defines_function)
2822 /* If defining a function declared with other language
2823 linkage, use the previously declared language linkage. */
2824 SET_DECL_LANGUAGE (newdecl, DECL_LANGUAGE (olddecl));
2825 else if (types_match)
2827 DECL_RESULT (newdecl) = DECL_RESULT (olddecl);
2828 /* Don't clear out the arguments if we're just redeclaring a
2829 function. */
2830 if (DECL_ARGUMENTS (olddecl))
2831 DECL_ARGUMENTS (newdecl) = DECL_ARGUMENTS (olddecl);
2834 else if (TREE_CODE (newdecl) == NAMESPACE_DECL)
2835 NAMESPACE_LEVEL (newdecl) = NAMESPACE_LEVEL (olddecl);
2837 /* Now preserve various other info from the definition. */
2838 TREE_ADDRESSABLE (newdecl) = TREE_ADDRESSABLE (olddecl);
2839 TREE_ASM_WRITTEN (newdecl) = TREE_ASM_WRITTEN (olddecl);
2840 DECL_COMMON (newdecl) = DECL_COMMON (olddecl);
2841 COPY_DECL_ASSEMBLER_NAME (olddecl, newdecl);
2843 /* Warn about conflicting visibility specifications. */
2844 if (DECL_VISIBILITY_SPECIFIED (olddecl)
2845 && DECL_VISIBILITY_SPECIFIED (newdecl)
2846 && DECL_VISIBILITY (newdecl) != DECL_VISIBILITY (olddecl))
2848 auto_diagnostic_group d;
2849 if (warning_at (newdecl_loc, OPT_Wattributes,
2850 "%qD: visibility attribute ignored because it "
2851 "conflicts with previous declaration", newdecl))
2852 inform (olddecl_loc,
2853 "previous declaration of %qD", olddecl);
2855 /* Choose the declaration which specified visibility. */
2856 if (DECL_VISIBILITY_SPECIFIED (olddecl))
2858 DECL_VISIBILITY (newdecl) = DECL_VISIBILITY (olddecl);
2859 DECL_VISIBILITY_SPECIFIED (newdecl) = 1;
2861 /* Init priority used to be merged from newdecl to olddecl by the memcpy,
2862 so keep this behavior. */
2863 if (VAR_P (newdecl) && DECL_HAS_INIT_PRIORITY_P (newdecl))
2865 SET_DECL_INIT_PRIORITY (olddecl, DECL_INIT_PRIORITY (newdecl));
2866 DECL_HAS_INIT_PRIORITY_P (olddecl) = 1;
2868 /* Likewise for DECL_ALIGN, DECL_USER_ALIGN and DECL_PACKED. */
2869 if (DECL_ALIGN (olddecl) > DECL_ALIGN (newdecl))
2871 SET_DECL_ALIGN (newdecl, DECL_ALIGN (olddecl));
2872 DECL_USER_ALIGN (newdecl) |= DECL_USER_ALIGN (olddecl);
2874 else if (DECL_ALIGN (olddecl) == DECL_ALIGN (newdecl)
2875 && DECL_USER_ALIGN (olddecl) != DECL_USER_ALIGN (newdecl))
2876 DECL_USER_ALIGN (newdecl) = 1;
2878 DECL_USER_ALIGN (olddecl) = DECL_USER_ALIGN (newdecl);
2879 if (DECL_WARN_IF_NOT_ALIGN (olddecl)
2880 > DECL_WARN_IF_NOT_ALIGN (newdecl))
2881 SET_DECL_WARN_IF_NOT_ALIGN (newdecl,
2882 DECL_WARN_IF_NOT_ALIGN (olddecl));
2883 if (TREE_CODE (newdecl) == FIELD_DECL)
2884 DECL_PACKED (olddecl) = DECL_PACKED (newdecl);
2886 /* The DECL_LANG_SPECIFIC information in OLDDECL will be replaced
2887 with that from NEWDECL below. */
2888 if (DECL_LANG_SPECIFIC (olddecl))
2890 gcc_checking_assert (DECL_LANG_SPECIFIC (olddecl)
2891 != DECL_LANG_SPECIFIC (newdecl));
2892 ggc_free (DECL_LANG_SPECIFIC (olddecl));
2895 /* Merge the USED information. */
2896 if (TREE_USED (olddecl))
2897 TREE_USED (newdecl) = 1;
2898 else if (TREE_USED (newdecl))
2899 TREE_USED (olddecl) = 1;
2901 if (VAR_P (newdecl))
2903 if (DECL_READ_P (olddecl))
2904 DECL_READ_P (newdecl) = 1;
2905 else if (DECL_READ_P (newdecl))
2906 DECL_READ_P (olddecl) = 1;
2909 if (DECL_PRESERVE_P (olddecl))
2910 DECL_PRESERVE_P (newdecl) = 1;
2911 else if (DECL_PRESERVE_P (newdecl))
2912 DECL_PRESERVE_P (olddecl) = 1;
2914 /* Merge the DECL_FUNCTION_VERSIONED information. newdecl will be copied
2915 to olddecl and deleted. */
2916 if (TREE_CODE (newdecl) == FUNCTION_DECL
2917 && DECL_FUNCTION_VERSIONED (olddecl))
2919 /* Set the flag for newdecl so that it gets copied to olddecl. */
2920 DECL_FUNCTION_VERSIONED (newdecl) = 1;
2921 /* newdecl will be purged after copying to olddecl and is no longer
2922 a version. */
2923 cgraph_node::delete_function_version_by_decl (newdecl);
2926 if (TREE_CODE (newdecl) == FUNCTION_DECL)
2928 int function_size;
2929 struct symtab_node *snode = symtab_node::get (olddecl);
2931 function_size = sizeof (struct tree_decl_common);
2933 memcpy ((char *) olddecl + sizeof (struct tree_common),
2934 (char *) newdecl + sizeof (struct tree_common),
2935 function_size - sizeof (struct tree_common));
2937 memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
2938 (char *) newdecl + sizeof (struct tree_decl_common),
2939 sizeof (struct tree_function_decl) - sizeof (struct tree_decl_common));
2941 /* Preserve symtab node mapping. */
2942 olddecl->decl_with_vis.symtab_node = snode;
2944 if (new_template_info)
2945 /* If newdecl is a template instantiation, it is possible that
2946 the following sequence of events has occurred:
2948 o A friend function was declared in a class template. The
2949 class template was instantiated.
2951 o The instantiation of the friend declaration was
2952 recorded on the instantiation list, and is newdecl.
2954 o Later, however, instantiate_class_template called pushdecl
2955 on the newdecl to perform name injection. But, pushdecl in
2956 turn called duplicate_decls when it discovered that another
2957 declaration of a global function with the same name already
2958 existed.
2960 o Here, in duplicate_decls, we decided to clobber newdecl.
2962 If we're going to do that, we'd better make sure that
2963 olddecl, and not newdecl, is on the list of
2964 instantiations so that if we try to do the instantiation
2965 again we won't get the clobbered declaration. */
2966 reregister_specialization (newdecl,
2967 new_template_info,
2968 olddecl);
2970 else
2972 size_t size = tree_code_size (TREE_CODE (newdecl));
2974 memcpy ((char *) olddecl + sizeof (struct tree_common),
2975 (char *) newdecl + sizeof (struct tree_common),
2976 sizeof (struct tree_decl_common) - sizeof (struct tree_common));
2978 switch (TREE_CODE (newdecl))
2980 case LABEL_DECL:
2981 case VAR_DECL:
2982 case RESULT_DECL:
2983 case PARM_DECL:
2984 case FIELD_DECL:
2985 case TYPE_DECL:
2986 case CONST_DECL:
2988 struct symtab_node *snode = NULL;
2990 if (VAR_P (newdecl)
2991 && (TREE_STATIC (olddecl) || TREE_PUBLIC (olddecl)
2992 || DECL_EXTERNAL (olddecl)))
2993 snode = symtab_node::get (olddecl);
2994 memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
2995 (char *) newdecl + sizeof (struct tree_decl_common),
2996 size - sizeof (struct tree_decl_common)
2997 + TREE_CODE_LENGTH (TREE_CODE (newdecl)) * sizeof (char *));
2998 if (VAR_P (newdecl))
2999 olddecl->decl_with_vis.symtab_node = snode;
3001 break;
3002 default:
3003 memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
3004 (char *) newdecl + sizeof (struct tree_decl_common),
3005 sizeof (struct tree_decl_non_common) - sizeof (struct tree_decl_common)
3006 + TREE_CODE_LENGTH (TREE_CODE (newdecl)) * sizeof (char *));
3007 break;
3011 if (VAR_OR_FUNCTION_DECL_P (newdecl))
3013 if (DECL_EXTERNAL (olddecl)
3014 || TREE_PUBLIC (olddecl)
3015 || TREE_STATIC (olddecl))
3017 /* Merge the section attribute.
3018 We want to issue an error if the sections conflict but that must be
3019 done later in decl_attributes since we are called before attributes
3020 are assigned. */
3021 if (DECL_SECTION_NAME (newdecl) != NULL)
3022 set_decl_section_name (olddecl, newdecl);
3024 if (DECL_ONE_ONLY (newdecl))
3026 struct symtab_node *oldsym, *newsym;
3027 if (TREE_CODE (olddecl) == FUNCTION_DECL)
3028 oldsym = cgraph_node::get_create (olddecl);
3029 else
3030 oldsym = varpool_node::get_create (olddecl);
3031 newsym = symtab_node::get (newdecl);
3032 oldsym->set_comdat_group (newsym->get_comdat_group ());
3036 if (VAR_P (newdecl)
3037 && CP_DECL_THREAD_LOCAL_P (newdecl))
3039 CP_DECL_THREAD_LOCAL_P (olddecl) = true;
3040 if (!processing_template_decl)
3041 set_decl_tls_model (olddecl, DECL_TLS_MODEL (newdecl));
3045 DECL_UID (olddecl) = olddecl_uid;
3047 /* NEWDECL contains the merged attribute lists.
3048 Update OLDDECL to be the same. */
3049 DECL_ATTRIBUTES (olddecl) = DECL_ATTRIBUTES (newdecl);
3051 /* If OLDDECL had its DECL_RTL instantiated, re-invoke make_decl_rtl
3052 so that encode_section_info has a chance to look at the new decl
3053 flags and attributes. */
3054 if (DECL_RTL_SET_P (olddecl)
3055 && (TREE_CODE (olddecl) == FUNCTION_DECL
3056 || (VAR_P (olddecl)
3057 && TREE_STATIC (olddecl))))
3058 make_decl_rtl (olddecl);
3060 /* The NEWDECL will no longer be needed. Because every out-of-class
3061 declaration of a member results in a call to duplicate_decls,
3062 freeing these nodes represents in a significant savings.
3064 Before releasing the node, be sore to remove function from symbol
3065 table that might have been inserted there to record comdat group.
3066 Be sure to however do not free DECL_STRUCT_FUNCTION because this
3067 structure is shared in between newdecl and oldecl. */
3068 if (TREE_CODE (newdecl) == FUNCTION_DECL)
3069 DECL_STRUCT_FUNCTION (newdecl) = NULL;
3070 if (VAR_OR_FUNCTION_DECL_P (newdecl))
3072 struct symtab_node *snode = symtab_node::get (newdecl);
3073 if (snode)
3074 snode->remove ();
3077 if (TREE_CODE (olddecl) == FUNCTION_DECL)
3079 tree clone;
3080 FOR_EACH_CLONE (clone, olddecl)
3082 DECL_ATTRIBUTES (clone) = DECL_ATTRIBUTES (olddecl);
3083 DECL_PRESERVE_P (clone) |= DECL_PRESERVE_P (olddecl);
3087 /* Remove the associated constraints for newdecl, if any, before
3088 reclaiming memory. */
3089 if (flag_concepts)
3090 remove_constraints (newdecl);
3092 ggc_free (newdecl);
3094 return olddecl;
3097 /* Return zero if the declaration NEWDECL is valid
3098 when the declaration OLDDECL (assumed to be for the same name)
3099 has already been seen.
3100 Otherwise return an error message format string with a %s
3101 where the identifier should go. */
3103 static const char *
3104 redeclaration_error_message (tree newdecl, tree olddecl)
3106 if (TREE_CODE (newdecl) == TYPE_DECL)
3108 /* Because C++ can put things into name space for free,
3109 constructs like "typedef struct foo { ... } foo"
3110 would look like an erroneous redeclaration. */
3111 if (same_type_p (TREE_TYPE (newdecl), TREE_TYPE (olddecl)))
3112 return NULL;
3113 else
3114 return G_("redefinition of %q#D");
3116 else if (TREE_CODE (newdecl) == FUNCTION_DECL)
3118 /* If this is a pure function, its olddecl will actually be
3119 the original initialization to `0' (which we force to call
3120 abort()). Don't complain about redefinition in this case. */
3121 if (DECL_LANG_SPECIFIC (olddecl) && DECL_PURE_VIRTUAL_P (olddecl)
3122 && DECL_INITIAL (olddecl) == NULL_TREE)
3123 return NULL;
3125 /* If both functions come from different namespaces, this is not
3126 a redeclaration - this is a conflict with a used function. */
3127 if (DECL_NAMESPACE_SCOPE_P (olddecl)
3128 && DECL_CONTEXT (olddecl) != DECL_CONTEXT (newdecl)
3129 && ! decls_match (olddecl, newdecl))
3130 return G_("%qD conflicts with used function");
3132 /* We'll complain about linkage mismatches in
3133 warn_extern_redeclared_static. */
3135 /* Defining the same name twice is no good. */
3136 if (decl_defined_p (olddecl)
3137 && decl_defined_p (newdecl))
3139 if (DECL_NAME (olddecl) == NULL_TREE)
3140 return G_("%q#D not declared in class");
3141 else if (!GNU_INLINE_P (olddecl)
3142 || GNU_INLINE_P (newdecl))
3143 return G_("redefinition of %q#D");
3146 if (DECL_DECLARED_INLINE_P (olddecl) && DECL_DECLARED_INLINE_P (newdecl))
3148 bool olda = GNU_INLINE_P (olddecl);
3149 bool newa = GNU_INLINE_P (newdecl);
3151 if (olda != newa)
3153 if (newa)
3154 return G_("%q+D redeclared inline with "
3155 "%<gnu_inline%> attribute");
3156 else
3157 return G_("%q+D redeclared inline without "
3158 "%<gnu_inline%> attribute");
3162 if (deduction_guide_p (olddecl)
3163 && deduction_guide_p (newdecl))
3164 return G_("deduction guide %q+D redeclared");
3166 /* [class.compare.default]: A definition of a comparison operator as
3167 defaulted that appears in a class shall be the first declaration of
3168 that function. */
3169 special_function_kind sfk = special_function_p (olddecl);
3170 if (sfk == sfk_comparison && DECL_DEFAULTED_FN (newdecl))
3171 return G_("comparison operator %q+D defaulted after "
3172 "its first declaration");
3174 check_abi_tag_redeclaration
3175 (olddecl, lookup_attribute ("abi_tag", DECL_ATTRIBUTES (olddecl)),
3176 lookup_attribute ("abi_tag", DECL_ATTRIBUTES (newdecl)));
3178 return NULL;
3180 else if (TREE_CODE (newdecl) == TEMPLATE_DECL)
3182 tree nt, ot;
3184 if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == CONCEPT_DECL)
3185 return G_("redefinition of %q#D");
3187 if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) != FUNCTION_DECL)
3188 return redeclaration_error_message (DECL_TEMPLATE_RESULT (newdecl),
3189 DECL_TEMPLATE_RESULT (olddecl));
3191 if (DECL_TEMPLATE_RESULT (newdecl) == DECL_TEMPLATE_RESULT (olddecl))
3192 return NULL;
3194 nt = DECL_TEMPLATE_RESULT (newdecl);
3195 if (DECL_TEMPLATE_INFO (nt))
3196 nt = DECL_TEMPLATE_RESULT (template_for_substitution (nt));
3197 ot = DECL_TEMPLATE_RESULT (olddecl);
3198 if (DECL_TEMPLATE_INFO (ot))
3199 ot = DECL_TEMPLATE_RESULT (template_for_substitution (ot));
3200 if (DECL_INITIAL (nt) && DECL_INITIAL (ot)
3201 && (!GNU_INLINE_P (ot) || GNU_INLINE_P (nt)))
3202 return G_("redefinition of %q#D");
3204 if (DECL_DECLARED_INLINE_P (ot) && DECL_DECLARED_INLINE_P (nt))
3206 bool olda = GNU_INLINE_P (ot);
3207 bool newa = GNU_INLINE_P (nt);
3209 if (olda != newa)
3211 if (newa)
3212 return G_("%q+D redeclared inline with "
3213 "%<gnu_inline%> attribute");
3214 else
3215 return G_("%q+D redeclared inline without "
3216 "%<gnu_inline%> attribute");
3220 if (deduction_guide_p (olddecl)
3221 && deduction_guide_p (newdecl))
3222 return G_("deduction guide %q+D redeclared");
3224 /* Core issue #226 (C++11):
3226 If a friend function template declaration specifies a
3227 default template-argument, that declaration shall be a
3228 definition and shall be the only declaration of the
3229 function template in the translation unit. */
3230 if ((cxx_dialect != cxx98)
3231 && TREE_CODE (ot) == FUNCTION_DECL && DECL_UNIQUE_FRIEND_P (ot)
3232 && !check_default_tmpl_args (nt, DECL_TEMPLATE_PARMS (newdecl),
3233 /*is_primary=*/true,
3234 /*is_partial=*/false,
3235 /*is_friend_decl=*/2))
3236 return G_("redeclaration of friend %q#D "
3237 "may not have default template arguments");
3239 return NULL;
3241 else if (VAR_P (newdecl)
3242 && (CP_DECL_THREAD_LOCAL_P (newdecl)
3243 != CP_DECL_THREAD_LOCAL_P (olddecl))
3244 && (! DECL_LANG_SPECIFIC (olddecl)
3245 || ! CP_DECL_THREADPRIVATE_P (olddecl)
3246 || CP_DECL_THREAD_LOCAL_P (newdecl)))
3248 /* Only variables can be thread-local, and all declarations must
3249 agree on this property. */
3250 if (CP_DECL_THREAD_LOCAL_P (newdecl))
3251 return G_("thread-local declaration of %q#D follows "
3252 "non-thread-local declaration");
3253 else
3254 return G_("non-thread-local declaration of %q#D follows "
3255 "thread-local declaration");
3257 else if (toplevel_bindings_p () || DECL_NAMESPACE_SCOPE_P (newdecl))
3259 /* The objects have been declared at namespace scope. If either
3260 is a member of an anonymous union, then this is an invalid
3261 redeclaration. For example:
3263 int i;
3264 union { int i; };
3266 is invalid. */
3267 if ((VAR_P (newdecl) && DECL_ANON_UNION_VAR_P (newdecl))
3268 || (VAR_P (olddecl) && DECL_ANON_UNION_VAR_P (olddecl)))
3269 return G_("redeclaration of %q#D");
3270 /* If at least one declaration is a reference, there is no
3271 conflict. For example:
3273 int i = 3;
3274 extern int i;
3276 is valid. */
3277 if (DECL_EXTERNAL (newdecl) || DECL_EXTERNAL (olddecl))
3278 return NULL;
3280 /* Static data member declared outside a class definition
3281 if the variable is defined within the class with constexpr
3282 specifier is declaration rather than definition (and
3283 deprecated). */
3284 if (cxx_dialect >= cxx17
3285 && VAR_P (olddecl)
3286 && DECL_CLASS_SCOPE_P (olddecl)
3287 && DECL_DECLARED_CONSTEXPR_P (olddecl)
3288 && !DECL_INITIAL (newdecl))
3290 DECL_EXTERNAL (newdecl) = 1;
3291 /* For now, only warn with explicit -Wdeprecated. */
3292 if (OPTION_SET_P (warn_deprecated))
3294 auto_diagnostic_group d;
3295 if (warning_at (DECL_SOURCE_LOCATION (newdecl), OPT_Wdeprecated,
3296 "redundant redeclaration of %<constexpr%> "
3297 "static data member %qD", newdecl))
3298 inform (DECL_SOURCE_LOCATION (olddecl),
3299 "previous declaration of %qD", olddecl);
3301 return NULL;
3304 /* Reject two definitions. */
3305 return G_("redefinition of %q#D");
3307 else
3309 /* Objects declared with block scope: */
3310 /* Reject two definitions, and reject a definition
3311 together with an external reference. */
3312 if (!(DECL_EXTERNAL (newdecl) && DECL_EXTERNAL (olddecl)))
3313 return G_("redeclaration of %q#D");
3314 return NULL;
3319 /* Hash and equality functions for the named_label table. */
3321 hashval_t
3322 named_label_hash::hash (const value_type entry)
3324 return IDENTIFIER_HASH_VALUE (entry->name);
3327 bool
3328 named_label_hash::equal (const value_type entry, compare_type name)
3330 return name == entry->name;
3333 /* Look for a label named ID in the current function. If one cannot
3334 be found, create one. Return the named_label_entry, or NULL on
3335 failure. */
3337 static named_label_entry *
3338 lookup_label_1 (tree id, bool making_local_p)
3340 auto_cond_timevar tv (TV_NAME_LOOKUP);
3342 /* You can't use labels at global scope. */
3343 if (current_function_decl == NULL_TREE)
3345 error ("label %qE referenced outside of any function", id);
3346 return NULL;
3349 if (!named_labels)
3350 named_labels = hash_table<named_label_hash>::create_ggc (13);
3352 hashval_t hash = IDENTIFIER_HASH_VALUE (id);
3353 named_label_entry **slot
3354 = named_labels->find_slot_with_hash (id, hash, INSERT);
3355 named_label_entry *old = *slot;
3357 if (old && old->label_decl)
3359 if (!making_local_p)
3360 return old;
3362 if (old->binding_level == current_binding_level)
3364 error ("local label %qE conflicts with existing label", id);
3365 inform (DECL_SOURCE_LOCATION (old->label_decl), "previous label");
3366 return NULL;
3370 /* We are making a new decl, create or reuse the named_label_entry */
3371 named_label_entry *ent = NULL;
3372 if (old && !old->label_decl)
3373 ent = old;
3374 else
3376 ent = ggc_cleared_alloc<named_label_entry> ();
3377 ent->name = id;
3378 ent->outer = old;
3379 *slot = ent;
3382 /* Now create the LABEL_DECL. */
3383 tree decl = build_decl (input_location, LABEL_DECL, id, void_type_node);
3385 DECL_CONTEXT (decl) = current_function_decl;
3386 SET_DECL_MODE (decl, VOIDmode);
3387 if (making_local_p)
3389 C_DECLARED_LABEL_FLAG (decl) = true;
3390 DECL_CHAIN (decl) = current_binding_level->names;
3391 current_binding_level->names = decl;
3394 ent->label_decl = decl;
3396 return ent;
3399 /* Wrapper for lookup_label_1. */
3401 tree
3402 lookup_label (tree id)
3404 named_label_entry *ent = lookup_label_1 (id, false);
3405 return ent ? ent->label_decl : NULL_TREE;
3408 tree
3409 declare_local_label (tree id)
3411 named_label_entry *ent = lookup_label_1 (id, true);
3412 return ent ? ent->label_decl : NULL_TREE;
3415 /* Returns nonzero if it is ill-formed to jump past the declaration of
3416 DECL. Returns 2 if it's also a real problem. */
3418 static int
3419 decl_jump_unsafe (tree decl)
3421 /* [stmt.dcl]/3: A program that jumps from a point where a local variable
3422 with automatic storage duration is not in scope to a point where it is
3423 in scope is ill-formed unless the variable has scalar type, class type
3424 with a trivial default constructor and a trivial destructor, a
3425 cv-qualified version of one of these types, or an array of one of the
3426 preceding types and is declared without an initializer (8.5). */
3427 tree type = TREE_TYPE (decl);
3429 if (!VAR_P (decl) || TREE_STATIC (decl)
3430 || type == error_mark_node)
3431 return 0;
3433 if (DECL_NONTRIVIALLY_INITIALIZED_P (decl)
3434 || variably_modified_type_p (type, NULL_TREE))
3435 return 2;
3437 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
3438 return 1;
3440 return 0;
3443 /* A subroutine of check_previous_goto_1 and check_goto to identify a branch
3444 to the user. */
3446 static bool
3447 identify_goto (tree decl, location_t loc, const location_t *locus,
3448 diagnostic_t diag_kind)
3450 bool complained
3451 = emit_diagnostic (diag_kind, loc, 0,
3452 decl ? N_("jump to label %qD")
3453 : N_("jump to case label"), decl);
3454 if (complained && locus)
3455 inform (*locus, " from here");
3456 return complained;
3459 /* Check that a single previously seen jump to a newly defined label
3460 is OK. DECL is the LABEL_DECL or 0; LEVEL is the binding_level for
3461 the jump context; NAMES are the names in scope in LEVEL at the jump
3462 context; LOCUS is the source position of the jump or 0. Returns
3463 true if all is well. */
3465 static bool
3466 check_previous_goto_1 (tree decl, cp_binding_level* level, tree names,
3467 bool exited_omp, const location_t *locus)
3469 cp_binding_level *b;
3470 bool complained = false;
3471 int identified = 0;
3472 bool saw_eh = false, saw_omp = false, saw_tm = false, saw_cxif = false;
3473 bool saw_ceif = false;
3475 if (exited_omp)
3477 complained = identify_goto (decl, input_location, locus, DK_ERROR);
3478 if (complained)
3479 inform (input_location, " exits OpenMP structured block");
3480 saw_omp = true;
3481 identified = 2;
3484 for (b = current_binding_level; b ; b = b->level_chain)
3486 tree new_decls, old_decls = (b == level ? names : NULL_TREE);
3488 for (new_decls = b->names; new_decls != old_decls;
3489 new_decls = (DECL_P (new_decls) ? DECL_CHAIN (new_decls)
3490 : TREE_CHAIN (new_decls)))
3492 int problem = decl_jump_unsafe (new_decls);
3493 if (! problem)
3494 continue;
3496 if (!identified)
3498 complained = identify_goto (decl, input_location, locus,
3499 problem > 1
3500 ? DK_ERROR : DK_PERMERROR);
3501 identified = 1;
3503 if (complained)
3505 if (problem > 1)
3506 inform (DECL_SOURCE_LOCATION (new_decls),
3507 " crosses initialization of %q#D", new_decls);
3508 else
3509 inform (DECL_SOURCE_LOCATION (new_decls),
3510 " enters scope of %q#D, which has "
3511 "non-trivial destructor", new_decls);
3515 if (b == level)
3516 break;
3518 const char *inf = NULL;
3519 location_t loc = input_location;
3520 switch (b->kind)
3522 case sk_try:
3523 if (!saw_eh)
3524 inf = G_(" enters %<try%> block");
3525 saw_eh = true;
3526 break;
3528 case sk_catch:
3529 if (!saw_eh)
3530 inf = G_(" enters %<catch%> block");
3531 saw_eh = true;
3532 break;
3534 case sk_omp:
3535 if (!saw_omp)
3536 inf = G_(" enters OpenMP structured block");
3537 saw_omp = true;
3538 break;
3540 case sk_transaction:
3541 if (!saw_tm)
3542 inf = G_(" enters synchronized or atomic statement");
3543 saw_tm = true;
3544 break;
3546 case sk_block:
3547 if (!saw_cxif && level_for_constexpr_if (b->level_chain))
3549 inf = G_(" enters %<constexpr if%> statement");
3550 loc = EXPR_LOCATION (b->level_chain->this_entity);
3551 saw_cxif = true;
3553 else if (!saw_ceif && level_for_consteval_if (b->level_chain))
3555 inf = G_(" enters %<consteval if%> statement");
3556 loc = EXPR_LOCATION (b->level_chain->this_entity);
3557 saw_ceif = true;
3559 break;
3561 default:
3562 break;
3565 if (inf)
3567 if (identified < 2)
3568 complained = identify_goto (decl, input_location, locus, DK_ERROR);
3569 identified = 2;
3570 if (complained)
3571 inform (loc, inf);
3575 return !identified;
3578 static void
3579 check_previous_goto (tree decl, struct named_label_use_entry *use)
3581 check_previous_goto_1 (decl, use->binding_level,
3582 use->names_in_scope, use->in_omp_scope,
3583 &use->o_goto_locus);
3586 static bool
3587 check_switch_goto (cp_binding_level* level)
3589 return check_previous_goto_1 (NULL_TREE, level, level->names, false, NULL);
3592 /* Check that a new jump to a label DECL is OK. Called by
3593 finish_goto_stmt. */
3595 void
3596 check_goto (tree decl)
3598 /* We can't know where a computed goto is jumping.
3599 So we assume that it's OK. */
3600 if (TREE_CODE (decl) != LABEL_DECL)
3601 return;
3603 /* We didn't record any information about this label when we created it,
3604 and there's not much point since it's trivial to analyze as a return. */
3605 if (decl == cdtor_label)
3606 return;
3608 hashval_t hash = IDENTIFIER_HASH_VALUE (DECL_NAME (decl));
3609 named_label_entry **slot
3610 = named_labels->find_slot_with_hash (DECL_NAME (decl), hash, NO_INSERT);
3611 named_label_entry *ent = *slot;
3613 /* If the label hasn't been defined yet, defer checking. */
3614 if (! DECL_INITIAL (decl))
3616 /* Don't bother creating another use if the last goto had the
3617 same data, and will therefore create the same set of errors. */
3618 if (ent->uses
3619 && ent->uses->names_in_scope == current_binding_level->names)
3620 return;
3622 named_label_use_entry *new_use
3623 = ggc_alloc<named_label_use_entry> ();
3624 new_use->binding_level = current_binding_level;
3625 new_use->names_in_scope = current_binding_level->names;
3626 new_use->o_goto_locus = input_location;
3627 new_use->in_omp_scope = false;
3629 new_use->next = ent->uses;
3630 ent->uses = new_use;
3631 return;
3634 bool saw_catch = false, complained = false;
3635 int identified = 0;
3636 tree bad;
3637 unsigned ix;
3639 if (ent->in_try_scope || ent->in_catch_scope || ent->in_transaction_scope
3640 || ent->in_constexpr_if || ent->in_consteval_if
3641 || ent->in_omp_scope || !vec_safe_is_empty (ent->bad_decls))
3643 diagnostic_t diag_kind = DK_PERMERROR;
3644 if (ent->in_try_scope || ent->in_catch_scope || ent->in_constexpr_if
3645 || ent->in_consteval_if || ent->in_transaction_scope
3646 || ent->in_omp_scope)
3647 diag_kind = DK_ERROR;
3648 complained = identify_goto (decl, DECL_SOURCE_LOCATION (decl),
3649 &input_location, diag_kind);
3650 identified = 1 + (diag_kind == DK_ERROR);
3653 FOR_EACH_VEC_SAFE_ELT (ent->bad_decls, ix, bad)
3655 int u = decl_jump_unsafe (bad);
3657 if (u > 1 && DECL_ARTIFICIAL (bad))
3659 /* Can't skip init of __exception_info. */
3660 if (identified == 1)
3662 complained = identify_goto (decl, DECL_SOURCE_LOCATION (decl),
3663 &input_location, DK_ERROR);
3664 identified = 2;
3666 if (complained)
3667 inform (DECL_SOURCE_LOCATION (bad), " enters %<catch%> block");
3668 saw_catch = true;
3670 else if (complained)
3672 if (u > 1)
3673 inform (DECL_SOURCE_LOCATION (bad),
3674 " skips initialization of %q#D", bad);
3675 else
3676 inform (DECL_SOURCE_LOCATION (bad),
3677 " enters scope of %q#D which has "
3678 "non-trivial destructor", bad);
3682 if (complained)
3684 if (ent->in_try_scope)
3685 inform (input_location, " enters %<try%> block");
3686 else if (ent->in_catch_scope && !saw_catch)
3687 inform (input_location, " enters %<catch%> block");
3688 else if (ent->in_transaction_scope)
3689 inform (input_location, " enters synchronized or atomic statement");
3690 else if (ent->in_constexpr_if)
3691 inform (input_location, " enters %<constexpr if%> statement");
3692 else if (ent->in_consteval_if)
3693 inform (input_location, " enters %<consteval if%> statement");
3696 if (ent->in_omp_scope)
3698 if (complained)
3699 inform (input_location, " enters OpenMP structured block");
3701 else if (flag_openmp)
3702 for (cp_binding_level *b = current_binding_level; b ; b = b->level_chain)
3704 if (b == ent->binding_level)
3705 break;
3706 if (b->kind == sk_omp)
3708 if (identified < 2)
3710 complained = identify_goto (decl,
3711 DECL_SOURCE_LOCATION (decl),
3712 &input_location, DK_ERROR);
3713 identified = 2;
3715 if (complained)
3716 inform (input_location, " exits OpenMP structured block");
3717 break;
3722 /* Check that a return is ok wrt OpenMP structured blocks.
3723 Called by finish_return_stmt. Returns true if all is well. */
3725 bool
3726 check_omp_return (void)
3728 for (cp_binding_level *b = current_binding_level; b ; b = b->level_chain)
3729 if (b->kind == sk_omp)
3731 error ("invalid exit from OpenMP structured block");
3732 return false;
3734 else if (b->kind == sk_function_parms)
3735 break;
3736 return true;
3739 /* Define a label, specifying the location in the source file.
3740 Return the LABEL_DECL node for the label. */
3742 tree
3743 define_label (location_t location, tree name)
3745 auto_cond_timevar tv (TV_NAME_LOOKUP);
3747 /* After labels, make any new cleanups in the function go into their
3748 own new (temporary) binding contour. */
3749 for (cp_binding_level *p = current_binding_level;
3750 p->kind != sk_function_parms;
3751 p = p->level_chain)
3752 p->more_cleanups_ok = 0;
3754 named_label_entry *ent = lookup_label_1 (name, false);
3755 tree decl = ent->label_decl;
3757 if (DECL_INITIAL (decl) != NULL_TREE)
3759 error ("duplicate label %qD", decl);
3760 return error_mark_node;
3762 else
3764 /* Mark label as having been defined. */
3765 DECL_INITIAL (decl) = error_mark_node;
3766 /* Say where in the source. */
3767 DECL_SOURCE_LOCATION (decl) = location;
3769 ent->binding_level = current_binding_level;
3770 ent->names_in_scope = current_binding_level->names;
3772 for (named_label_use_entry *use = ent->uses; use; use = use->next)
3773 check_previous_goto (decl, use);
3774 ent->uses = NULL;
3777 return decl;
3780 struct cp_switch
3782 cp_binding_level *level;
3783 struct cp_switch *next;
3784 /* The SWITCH_STMT being built. */
3785 tree switch_stmt;
3786 /* A splay-tree mapping the low element of a case range to the high
3787 element, or NULL_TREE if there is no high element. Used to
3788 determine whether or not a new case label duplicates an old case
3789 label. We need a tree, rather than simply a hash table, because
3790 of the GNU case range extension. */
3791 splay_tree cases;
3792 /* Remember whether a default: case label has been seen. */
3793 bool has_default_p;
3794 /* Remember whether a BREAK_STMT has been seen in this SWITCH_STMT. */
3795 bool break_stmt_seen_p;
3796 /* Set if inside of {FOR,DO,WHILE}_BODY nested inside of a switch,
3797 where BREAK_STMT doesn't belong to the SWITCH_STMT. */
3798 bool in_loop_body_p;
3801 /* A stack of the currently active switch statements. The innermost
3802 switch statement is on the top of the stack. There is no need to
3803 mark the stack for garbage collection because it is only active
3804 during the processing of the body of a function, and we never
3805 collect at that point. */
3807 static struct cp_switch *switch_stack;
3809 /* Called right after a switch-statement condition is parsed.
3810 SWITCH_STMT is the switch statement being parsed. */
3812 void
3813 push_switch (tree switch_stmt)
3815 struct cp_switch *p = XNEW (struct cp_switch);
3816 p->level = current_binding_level;
3817 p->next = switch_stack;
3818 p->switch_stmt = switch_stmt;
3819 p->cases = splay_tree_new (case_compare, NULL, NULL);
3820 p->has_default_p = false;
3821 p->break_stmt_seen_p = false;
3822 p->in_loop_body_p = false;
3823 switch_stack = p;
3826 void
3827 pop_switch (void)
3829 struct cp_switch *cs = switch_stack;
3831 /* Emit warnings as needed. */
3832 location_t switch_location = cp_expr_loc_or_input_loc (cs->switch_stmt);
3833 tree cond = SWITCH_STMT_COND (cs->switch_stmt);
3834 const bool bool_cond_p
3835 = (SWITCH_STMT_TYPE (cs->switch_stmt)
3836 && TREE_CODE (SWITCH_STMT_TYPE (cs->switch_stmt)) == BOOLEAN_TYPE);
3837 if (!processing_template_decl)
3838 c_do_switch_warnings (cs->cases, switch_location,
3839 SWITCH_STMT_TYPE (cs->switch_stmt), cond,
3840 bool_cond_p);
3842 /* For the benefit of block_may_fallthru remember if the switch body
3843 case labels cover all possible values and if there are break; stmts. */
3844 if (cs->has_default_p
3845 || (!processing_template_decl
3846 && c_switch_covers_all_cases_p (cs->cases,
3847 SWITCH_STMT_TYPE (cs->switch_stmt))))
3848 SWITCH_STMT_ALL_CASES_P (cs->switch_stmt) = 1;
3849 if (!cs->break_stmt_seen_p)
3850 SWITCH_STMT_NO_BREAK_P (cs->switch_stmt) = 1;
3851 /* Now that we're done with the switch warnings, set the switch type
3852 to the type of the condition if the index type was of scoped enum type.
3853 (Such types don't participate in the integer promotions.) We do this
3854 because of bit-fields whose declared type is a scoped enum type:
3855 gimplification will use the lowered index type, but convert the
3856 case values to SWITCH_STMT_TYPE, which would have been the declared type
3857 and verify_gimple_switch doesn't accept that. */
3858 if (is_bitfield_expr_with_lowered_type (cond))
3859 SWITCH_STMT_TYPE (cs->switch_stmt) = TREE_TYPE (cond);
3860 gcc_assert (!cs->in_loop_body_p);
3861 splay_tree_delete (cs->cases);
3862 switch_stack = switch_stack->next;
3863 free (cs);
3866 /* Note that a BREAK_STMT is about to be added. If it is inside of
3867 a SWITCH_STMT and not inside of a loop body inside of it, note
3868 in switch_stack we've seen a BREAK_STMT. */
3870 void
3871 note_break_stmt (void)
3873 if (switch_stack && !switch_stack->in_loop_body_p)
3874 switch_stack->break_stmt_seen_p = true;
3877 /* Note the start of processing of an iteration statement's body.
3878 The note_break_stmt function will do nothing while processing it.
3879 Return a flag that should be passed to note_iteration_stmt_body_end. */
3881 bool
3882 note_iteration_stmt_body_start (void)
3884 if (!switch_stack)
3885 return false;
3886 bool ret = switch_stack->in_loop_body_p;
3887 switch_stack->in_loop_body_p = true;
3888 return ret;
3891 /* Note the end of processing of an iteration statement's body. */
3893 void
3894 note_iteration_stmt_body_end (bool prev)
3896 if (switch_stack)
3897 switch_stack->in_loop_body_p = prev;
3900 /* Convert a case constant VALUE in a switch to the type TYPE of the switch
3901 condition. Note that if TYPE and VALUE are already integral we don't
3902 really do the conversion because the language-independent
3903 warning/optimization code will work better that way. */
3905 static tree
3906 case_conversion (tree type, tree value)
3908 if (value == NULL_TREE)
3909 return value;
3911 value = mark_rvalue_use (value);
3913 if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3914 type = type_promotes_to (type);
3916 tree ovalue = value;
3917 /* The constant-expression VALUE shall be a converted constant expression
3918 of the adjusted type of the switch condition, which doesn't allow
3919 narrowing conversions. */
3920 value = build_converted_constant_expr (type, value, tf_warning_or_error);
3922 if (cxx_dialect >= cxx11
3923 && (SCOPED_ENUM_P (type)
3924 || !INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (ovalue))))
3925 /* Use the converted value. */;
3926 else
3927 /* The already integral case. */
3928 value = ovalue;
3930 return cxx_constant_value (value);
3933 /* Note that we've seen a definition of a case label, and complain if this
3934 is a bad place for one. */
3936 tree
3937 finish_case_label (location_t loc, tree low_value, tree high_value)
3939 tree cond, r;
3940 cp_binding_level *p;
3941 tree type;
3943 if (low_value == NULL_TREE && high_value == NULL_TREE)
3944 switch_stack->has_default_p = true;
3946 if (processing_template_decl)
3948 tree label;
3950 /* For templates, just add the case label; we'll do semantic
3951 analysis at instantiation-time. */
3952 label = build_decl (loc, LABEL_DECL, NULL_TREE, void_type_node);
3953 return add_stmt (build_case_label (low_value, high_value, label));
3956 /* Find the condition on which this switch statement depends. */
3957 cond = SWITCH_STMT_COND (switch_stack->switch_stmt);
3958 if (cond && TREE_CODE (cond) == TREE_LIST)
3959 cond = TREE_VALUE (cond);
3961 if (!check_switch_goto (switch_stack->level))
3962 return error_mark_node;
3964 type = SWITCH_STMT_TYPE (switch_stack->switch_stmt);
3965 if (type == error_mark_node)
3966 return error_mark_node;
3968 low_value = case_conversion (type, low_value);
3969 high_value = case_conversion (type, high_value);
3971 r = c_add_case_label (loc, switch_stack->cases, cond, low_value, high_value);
3973 /* After labels, make any new cleanups in the function go into their
3974 own new (temporary) binding contour. */
3975 for (p = current_binding_level;
3976 p->kind != sk_function_parms;
3977 p = p->level_chain)
3978 p->more_cleanups_ok = 0;
3980 return r;
3983 struct typename_info {
3984 tree scope;
3985 tree name;
3986 tree template_id;
3987 bool enum_p;
3988 bool class_p;
3991 struct typename_hasher : ggc_ptr_hash<tree_node>
3993 typedef typename_info *compare_type;
3995 /* Hash a TYPENAME_TYPE. */
3997 static hashval_t
3998 hash (tree t)
4000 hashval_t hash;
4002 hash = (htab_hash_pointer (TYPE_CONTEXT (t))
4003 ^ htab_hash_pointer (TYPE_IDENTIFIER (t)));
4005 return hash;
4008 /* Compare two TYPENAME_TYPEs. */
4010 static bool
4011 equal (tree t1, const typename_info *t2)
4013 return (TYPE_IDENTIFIER (t1) == t2->name
4014 && TYPE_CONTEXT (t1) == t2->scope
4015 && TYPENAME_TYPE_FULLNAME (t1) == t2->template_id
4016 && TYPENAME_IS_ENUM_P (t1) == t2->enum_p
4017 && TYPENAME_IS_CLASS_P (t1) == t2->class_p);
4021 /* Build a TYPENAME_TYPE. If the type is `typename T::t', CONTEXT is
4022 the type of `T', NAME is the IDENTIFIER_NODE for `t'.
4024 Returns the new TYPENAME_TYPE. */
4026 static GTY (()) hash_table<typename_hasher> *typename_htab;
4028 tree
4029 build_typename_type (tree context, tree name, tree fullname,
4030 enum tag_types tag_type)
4032 typename_info ti;
4034 if (typename_htab == NULL)
4035 typename_htab = hash_table<typename_hasher>::create_ggc (61);
4037 ti.scope = FROB_CONTEXT (context);
4038 ti.name = name;
4039 ti.template_id = fullname;
4040 ti.enum_p = tag_type == enum_type;
4041 ti.class_p = (tag_type == class_type
4042 || tag_type == record_type
4043 || tag_type == union_type);
4044 hashval_t hash = (htab_hash_pointer (ti.scope)
4045 ^ htab_hash_pointer (ti.name));
4047 /* See if we already have this type. */
4048 tree *e = typename_htab->find_slot_with_hash (&ti, hash, INSERT);
4049 tree t = *e;
4050 if (*e)
4051 t = *e;
4052 else
4054 /* Build the TYPENAME_TYPE. */
4055 t = cxx_make_type (TYPENAME_TYPE);
4056 TYPE_CONTEXT (t) = ti.scope;
4057 TYPENAME_TYPE_FULLNAME (t) = ti.template_id;
4058 TYPENAME_IS_ENUM_P (t) = ti.enum_p;
4059 TYPENAME_IS_CLASS_P (t) = ti.class_p;
4061 /* Build the corresponding TYPE_DECL. */
4062 tree d = build_decl (input_location, TYPE_DECL, name, t);
4063 TYPE_NAME (t) = d;
4064 TYPE_STUB_DECL (t) = d;
4065 DECL_CONTEXT (d) = ti.scope;
4066 DECL_ARTIFICIAL (d) = 1;
4068 /* Store it in the hash table. */
4069 *e = t;
4071 /* TYPENAME_TYPEs must always be compared structurally, because
4072 they may or may not resolve down to another type depending on
4073 the currently open classes. */
4074 SET_TYPE_STRUCTURAL_EQUALITY (t);
4077 return t;
4080 /* Resolve `typename CONTEXT::NAME'. TAG_TYPE indicates the tag
4081 provided to name the type. Returns an appropriate type, unless an
4082 error occurs, in which case error_mark_node is returned. If we
4083 locate a non-artificial TYPE_DECL and TF_KEEP_TYPE_DECL is set, we
4084 return that, rather than the _TYPE it corresponds to, in other
4085 cases we look through the type decl. If TF_ERROR is set, complain
4086 about errors, otherwise be quiet. */
4088 tree
4089 make_typename_type (tree context, tree name, enum tag_types tag_type,
4090 tsubst_flags_t complain)
4092 tree fullname;
4093 tree t;
4094 bool want_template;
4096 if (name == error_mark_node
4097 || context == NULL_TREE
4098 || context == error_mark_node)
4099 return error_mark_node;
4101 if (TYPE_P (name))
4103 if (!(TYPE_LANG_SPECIFIC (name)
4104 && (CLASSTYPE_IS_TEMPLATE (name)
4105 || CLASSTYPE_USE_TEMPLATE (name))))
4106 name = TYPE_IDENTIFIER (name);
4107 else
4108 /* Create a TEMPLATE_ID_EXPR for the type. */
4109 name = build_nt (TEMPLATE_ID_EXPR,
4110 CLASSTYPE_TI_TEMPLATE (name),
4111 CLASSTYPE_TI_ARGS (name));
4113 else if (TREE_CODE (name) == TYPE_DECL)
4114 name = DECL_NAME (name);
4116 fullname = name;
4118 if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
4120 name = TREE_OPERAND (name, 0);
4121 if (DECL_TYPE_TEMPLATE_P (name))
4122 name = TREE_OPERAND (fullname, 0) = DECL_NAME (name);
4123 if (TREE_CODE (name) != IDENTIFIER_NODE)
4125 if (complain & tf_error)
4126 error ("%qD is not a type", name);
4127 return error_mark_node;
4130 if (TREE_CODE (name) == TEMPLATE_DECL)
4132 if (complain & tf_error)
4133 error ("%qD used without template arguments", name);
4134 return error_mark_node;
4136 else if (is_overloaded_fn (name))
4138 if (complain & tf_error)
4139 error ("%qD is a function, not a type", name);
4140 return error_mark_node;
4142 gcc_assert (identifier_p (name));
4143 gcc_assert (TYPE_P (context));
4145 if (TREE_CODE (context) == TYPE_PACK_EXPANSION)
4146 /* This can happen for C++17 variadic using (c++/88986). */;
4147 else if (!MAYBE_CLASS_TYPE_P (context))
4149 if (complain & tf_error)
4150 error ("%q#T is not a class", context);
4151 return error_mark_node;
4154 /* When the CONTEXT is a dependent type, NAME could refer to a
4155 dependent base class of CONTEXT. But look inside it anyway
4156 if CONTEXT is a currently open scope, in case it refers to a
4157 member of the current instantiation or a non-dependent base;
4158 lookup will stop when we hit a dependent base. */
4159 if (!dependent_scope_p (context))
4160 /* We should only set WANT_TYPE when we're a nested typename type.
4161 Then we can give better diagnostics if we find a non-type. */
4162 t = lookup_field (context, name, 2, /*want_type=*/true);
4163 else
4164 t = NULL_TREE;
4166 if ((!t || TREE_CODE (t) == TREE_LIST) && dependent_type_p (context))
4167 return build_typename_type (context, name, fullname, tag_type);
4169 want_template = TREE_CODE (fullname) == TEMPLATE_ID_EXPR;
4171 if (!t)
4173 if (complain & tf_error)
4175 if (!COMPLETE_TYPE_P (context))
4176 cxx_incomplete_type_error (NULL_TREE, context);
4177 else
4178 error (want_template ? G_("no class template named %q#T in %q#T")
4179 : G_("no type named %q#T in %q#T"), name, context);
4181 return error_mark_node;
4184 /* Pull out the template from an injected-class-name (or multiple). */
4185 if (want_template)
4186 t = maybe_get_template_decl_from_type_decl (t);
4188 if (TREE_CODE (t) == TREE_LIST)
4190 if (complain & tf_error)
4192 error ("lookup of %qT in %qT is ambiguous", name, context);
4193 print_candidates (t);
4195 return error_mark_node;
4198 if (want_template && !DECL_TYPE_TEMPLATE_P (t))
4200 if (complain & tf_error)
4201 error ("%<typename %T::%D%> names %q#T, which is not a class template",
4202 context, name, t);
4203 return error_mark_node;
4205 if (!want_template && TREE_CODE (t) != TYPE_DECL)
4207 if ((complain & tf_tst_ok) && cxx_dialect >= cxx17
4208 && DECL_TYPE_TEMPLATE_P (t))
4209 /* The caller permits this typename-specifier to name a template
4210 (because it appears in a CTAD-enabled context). */;
4211 else
4213 if (complain & tf_error)
4214 error ("%<typename %T::%D%> names %q#T, which is not a type",
4215 context, name, t);
4216 return error_mark_node;
4220 if (!check_accessibility_of_qualified_id (t, /*object_type=*/NULL_TREE,
4221 context, complain))
4222 return error_mark_node;
4224 if (!want_template && DECL_TYPE_TEMPLATE_P (t))
4225 return make_template_placeholder (t);
4227 if (want_template)
4229 t = lookup_template_class (t, TREE_OPERAND (fullname, 1),
4230 NULL_TREE, context,
4231 /*entering_scope=*/0,
4232 complain | tf_user);
4233 if (t == error_mark_node)
4234 return error_mark_node;
4235 t = TYPE_NAME (t);
4238 if (DECL_ARTIFICIAL (t) || !(complain & tf_keep_type_decl))
4239 t = TREE_TYPE (t);
4241 maybe_record_typedef_use (t);
4243 return t;
4246 /* Resolve `CONTEXT::template NAME'. Returns a TEMPLATE_DECL if the name
4247 can be resolved or an UNBOUND_CLASS_TEMPLATE, unless an error occurs,
4248 in which case error_mark_node is returned.
4250 If PARM_LIST is non-NULL, also make sure that the template parameter
4251 list of TEMPLATE_DECL matches.
4253 If COMPLAIN zero, don't complain about any errors that occur. */
4255 tree
4256 make_unbound_class_template (tree context, tree name, tree parm_list,
4257 tsubst_flags_t complain)
4259 if (TYPE_P (name))
4260 name = TYPE_IDENTIFIER (name);
4261 else if (DECL_P (name))
4262 name = DECL_NAME (name);
4263 gcc_assert (identifier_p (name));
4265 if (!dependent_type_p (context)
4266 || currently_open_class (context))
4268 tree tmpl = NULL_TREE;
4270 if (MAYBE_CLASS_TYPE_P (context))
4271 tmpl = lookup_field (context, name, 0, false);
4273 if (tmpl && TREE_CODE (tmpl) == TYPE_DECL)
4274 tmpl = maybe_get_template_decl_from_type_decl (tmpl);
4276 if (!tmpl || !DECL_TYPE_TEMPLATE_P (tmpl))
4278 if (complain & tf_error)
4279 error ("no class template named %q#T in %q#T", name, context);
4280 return error_mark_node;
4283 if (parm_list
4284 && !comp_template_parms (DECL_TEMPLATE_PARMS (tmpl), parm_list))
4286 if (complain & tf_error)
4288 error ("template parameters do not match template %qD", tmpl);
4289 inform (DECL_SOURCE_LOCATION (tmpl),
4290 "%qD declared here", tmpl);
4292 return error_mark_node;
4295 if (!perform_or_defer_access_check (TYPE_BINFO (context), tmpl, tmpl,
4296 complain))
4297 return error_mark_node;
4299 return tmpl;
4302 return make_unbound_class_template_raw (context, name, parm_list);
4305 /* Build an UNBOUND_CLASS_TEMPLATE. */
4307 tree
4308 make_unbound_class_template_raw (tree context, tree name, tree parm_list)
4310 /* Build the UNBOUND_CLASS_TEMPLATE. */
4311 tree t = cxx_make_type (UNBOUND_CLASS_TEMPLATE);
4312 TYPE_CONTEXT (t) = FROB_CONTEXT (context);
4313 TREE_TYPE (t) = NULL_TREE;
4314 SET_TYPE_STRUCTURAL_EQUALITY (t);
4316 /* Build the corresponding TEMPLATE_DECL. */
4317 tree d = build_decl (input_location, TEMPLATE_DECL, name, t);
4318 TYPE_NAME (t) = d;
4319 TYPE_STUB_DECL (t) = d;
4320 DECL_CONTEXT (d) = TYPE_CONTEXT (t);
4321 DECL_ARTIFICIAL (d) = 1;
4322 DECL_TEMPLATE_PARMS (d) = parm_list;
4324 return t;
4329 /* Push the declarations of builtin types into the global namespace.
4330 RID_INDEX is the index of the builtin type in the array
4331 RID_POINTERS. NAME is the name used when looking up the builtin
4332 type. TYPE is the _TYPE node for the builtin type.
4334 The calls to set_global_binding below should be
4335 eliminated. Built-in types should not be looked up name; their
4336 names are keywords that the parser can recognize. However, there
4337 is code in c-common.cc that uses identifier_global_value to look up
4338 built-in types by name. */
4340 void
4341 record_builtin_type (enum rid rid_index,
4342 const char* name,
4343 tree type)
4345 tree decl = NULL_TREE;
4347 if (name)
4349 tree tname = get_identifier (name);
4350 tree tdecl = build_decl (BUILTINS_LOCATION, TYPE_DECL, tname, type);
4351 DECL_ARTIFICIAL (tdecl) = 1;
4352 set_global_binding (tdecl);
4353 decl = tdecl;
4356 if ((int) rid_index < (int) RID_MAX)
4357 if (tree rname = ridpointers[(int) rid_index])
4358 if (!decl || DECL_NAME (decl) != rname)
4360 tree rdecl = build_decl (BUILTINS_LOCATION, TYPE_DECL, rname, type);
4361 DECL_ARTIFICIAL (rdecl) = 1;
4362 set_global_binding (rdecl);
4363 if (!decl)
4364 decl = rdecl;
4367 if (decl)
4369 if (!TYPE_NAME (type))
4370 TYPE_NAME (type) = decl;
4371 debug_hooks->type_decl (decl, 0);
4375 /* Push a type into the namespace so that the back ends ignore it. */
4377 static void
4378 record_unknown_type (tree type, const char* name)
4380 tree decl = pushdecl (build_decl (UNKNOWN_LOCATION,
4381 TYPE_DECL, get_identifier (name), type));
4382 /* Make sure the "unknown type" typedecl gets ignored for debug info. */
4383 DECL_IGNORED_P (decl) = 1;
4384 TYPE_DECL_SUPPRESS_DEBUG (decl) = 1;
4385 TYPE_SIZE (type) = TYPE_SIZE (void_type_node);
4386 SET_TYPE_ALIGN (type, 1);
4387 TYPE_USER_ALIGN (type) = 0;
4388 SET_TYPE_MODE (type, TYPE_MODE (void_type_node));
4391 /* Create all the predefined identifiers. */
4393 static void
4394 initialize_predefined_identifiers (void)
4396 struct predefined_identifier
4398 const char *name; /* Name. */
4399 tree *node; /* Node to store it in. */
4400 cp_identifier_kind kind; /* Kind of identifier. */
4403 /* A table of identifiers to create at startup. */
4404 static const predefined_identifier predefined_identifiers[] = {
4405 {"C++", &lang_name_cplusplus, cik_normal},
4406 {"C", &lang_name_c, cik_normal},
4407 /* Some of these names have a trailing space so that it is
4408 impossible for them to conflict with names written by users. */
4409 {"__ct ", &ctor_identifier, cik_ctor},
4410 {"__ct_base ", &base_ctor_identifier, cik_ctor},
4411 {"__ct_comp ", &complete_ctor_identifier, cik_ctor},
4412 {"__dt ", &dtor_identifier, cik_dtor},
4413 {"__dt_base ", &base_dtor_identifier, cik_dtor},
4414 {"__dt_comp ", &complete_dtor_identifier, cik_dtor},
4415 {"__dt_del ", &deleting_dtor_identifier, cik_dtor},
4416 {"__conv_op ", &conv_op_identifier, cik_conv_op},
4417 {"__in_chrg", &in_charge_identifier, cik_normal},
4418 {"__as_base ", &as_base_identifier, cik_normal},
4419 {"this", &this_identifier, cik_normal},
4420 {"__delta", &delta_identifier, cik_normal},
4421 {"__pfn", &pfn_identifier, cik_normal},
4422 {"_vptr", &vptr_identifier, cik_normal},
4423 {"__vtt_parm", &vtt_parm_identifier, cik_normal},
4424 {"::", &global_identifier, cik_normal},
4425 /* The demangler expects anonymous namespaces to be called
4426 something starting with '_GLOBAL__N_'. It no longer needs
4427 to be unique to the TU. */
4428 {"_GLOBAL__N_1", &anon_identifier, cik_normal},
4429 {"auto", &auto_identifier, cik_normal},
4430 {"decltype(auto)", &decltype_auto_identifier, cik_normal},
4431 {"initializer_list", &init_list_identifier, cik_normal},
4432 {"__for_range ", &for_range__identifier, cik_normal},
4433 {"__for_begin ", &for_begin__identifier, cik_normal},
4434 {"__for_end ", &for_end__identifier, cik_normal},
4435 {"__for_range", &for_range_identifier, cik_normal},
4436 {"__for_begin", &for_begin_identifier, cik_normal},
4437 {"__for_end", &for_end_identifier, cik_normal},
4438 {"abi_tag", &abi_tag_identifier, cik_normal},
4439 {"aligned", &aligned_identifier, cik_normal},
4440 {"begin", &begin_identifier, cik_normal},
4441 {"end", &end_identifier, cik_normal},
4442 {"get", &get__identifier, cik_normal},
4443 {"gnu", &gnu_identifier, cik_normal},
4444 {"tuple_element", &tuple_element_identifier, cik_normal},
4445 {"tuple_size", &tuple_size_identifier, cik_normal},
4446 {"type", &type_identifier, cik_normal},
4447 {"value", &value_identifier, cik_normal},
4448 {"_FUN", &fun_identifier, cik_normal},
4449 {"__closure", &closure_identifier, cik_normal},
4450 {"heap uninit", &heap_uninit_identifier, cik_normal},
4451 {"heap ", &heap_identifier, cik_normal},
4452 {"heap deleted", &heap_deleted_identifier, cik_normal},
4453 {"heap [] uninit", &heap_vec_uninit_identifier, cik_normal},
4454 {"heap []", &heap_vec_identifier, cik_normal},
4455 {"omp", &omp_identifier, cik_normal},
4456 {NULL, NULL, cik_normal}
4459 for (const predefined_identifier *pid = predefined_identifiers;
4460 pid->name; ++pid)
4462 *pid->node = get_identifier (pid->name);
4463 /* Some of these identifiers already have a special kind. */
4464 if (pid->kind != cik_normal)
4465 set_identifier_kind (*pid->node, pid->kind);
4469 /* Create the predefined scalar types of C,
4470 and some nodes representing standard constants (0, 1, (void *)0).
4471 Initialize the global binding level.
4472 Make definitions for built-in primitive functions. */
4474 void
4475 cxx_init_decl_processing (void)
4477 tree void_ftype;
4478 tree void_ftype_ptr;
4480 /* Create all the identifiers we need. */
4481 initialize_predefined_identifiers ();
4483 /* Create the global variables. */
4484 push_to_top_level ();
4486 current_function_decl = NULL_TREE;
4487 current_binding_level = NULL;
4488 /* Enter the global namespace. */
4489 gcc_assert (global_namespace == NULL_TREE);
4490 global_namespace = build_lang_decl (NAMESPACE_DECL, global_identifier,
4491 void_type_node);
4492 TREE_PUBLIC (global_namespace) = true;
4493 DECL_MODULE_EXPORT_P (global_namespace) = true;
4494 DECL_CONTEXT (global_namespace)
4495 = build_translation_unit_decl (get_identifier (main_input_filename));
4496 /* Remember whether we want the empty class passing ABI change warning
4497 in this TU. */
4498 TRANSLATION_UNIT_WARN_EMPTY_P (DECL_CONTEXT (global_namespace))
4499 = warn_abi && abi_version_crosses (12);
4500 debug_hooks->register_main_translation_unit
4501 (DECL_CONTEXT (global_namespace));
4502 begin_scope (sk_namespace, global_namespace);
4503 current_namespace = global_namespace;
4505 if (flag_visibility_ms_compat)
4506 default_visibility = VISIBILITY_HIDDEN;
4508 /* Initially, C. */
4509 current_lang_name = lang_name_c;
4511 /* Create the `std' namespace. */
4512 push_namespace (get_identifier ("std"));
4513 std_node = current_namespace;
4514 pop_namespace ();
4516 flag_noexcept_type = (cxx_dialect >= cxx17);
4518 c_common_nodes_and_builtins ();
4520 tree bool_ftype = build_function_type_list (boolean_type_node, NULL_TREE);
4521 tree decl
4522 = add_builtin_function ("__builtin_is_constant_evaluated",
4523 bool_ftype, CP_BUILT_IN_IS_CONSTANT_EVALUATED,
4524 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4525 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4527 tree cptr_ftype = build_function_type_list (const_ptr_type_node, NULL_TREE);
4528 decl = add_builtin_function ("__builtin_source_location",
4529 cptr_ftype, CP_BUILT_IN_SOURCE_LOCATION,
4530 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4531 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4533 tree bool_vaftype = build_varargs_function_type_list (boolean_type_node,
4534 NULL_TREE);
4535 decl
4536 = add_builtin_function ("__builtin_is_corresponding_member",
4537 bool_vaftype,
4538 CP_BUILT_IN_IS_CORRESPONDING_MEMBER,
4539 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4540 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4542 decl
4543 = add_builtin_function ("__builtin_is_pointer_interconvertible_with_class",
4544 bool_vaftype,
4545 CP_BUILT_IN_IS_POINTER_INTERCONVERTIBLE_WITH_CLASS,
4546 BUILT_IN_FRONTEND, NULL, NULL_TREE);
4547 set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4549 integer_two_node = build_int_cst (NULL_TREE, 2);
4551 /* Guess at the initial static decls size. */
4552 vec_alloc (static_decls, 500);
4554 /* ... and keyed classes. */
4555 vec_alloc (keyed_classes, 100);
4557 record_builtin_type (RID_BOOL, "bool", boolean_type_node);
4558 truthvalue_type_node = boolean_type_node;
4559 truthvalue_false_node = boolean_false_node;
4560 truthvalue_true_node = boolean_true_node;
4562 empty_except_spec = build_tree_list (NULL_TREE, NULL_TREE);
4563 noexcept_true_spec = build_tree_list (boolean_true_node, NULL_TREE);
4564 noexcept_false_spec = build_tree_list (boolean_false_node, NULL_TREE);
4565 noexcept_deferred_spec = build_tree_list (make_node (DEFERRED_NOEXCEPT),
4566 NULL_TREE);
4568 #if 0
4569 record_builtin_type (RID_MAX, NULL, string_type_node);
4570 #endif
4572 delta_type_node = ptrdiff_type_node;
4573 vtable_index_type = ptrdiff_type_node;
4575 vtt_parm_type = build_pointer_type (const_ptr_type_node);
4576 void_ftype = build_function_type_list (void_type_node, NULL_TREE);
4577 void_ftype_ptr = build_function_type_list (void_type_node,
4578 ptr_type_node, NULL_TREE);
4579 void_ftype_ptr
4580 = build_exception_variant (void_ftype_ptr, empty_except_spec);
4582 /* Create the conversion operator marker. This operator's DECL_NAME
4583 is in the identifier table, so we can use identifier equality to
4584 find it. */
4585 conv_op_marker = build_lang_decl (FUNCTION_DECL, conv_op_identifier,
4586 void_ftype);
4588 /* C++ extensions */
4590 unknown_type_node = make_node (LANG_TYPE);
4591 record_unknown_type (unknown_type_node, "unknown type");
4593 /* Indirecting an UNKNOWN_TYPE node yields an UNKNOWN_TYPE node. */
4594 TREE_TYPE (unknown_type_node) = unknown_type_node;
4596 /* Looking up TYPE_POINTER_TO and TYPE_REFERENCE_TO yield the same
4597 result. */
4598 TYPE_POINTER_TO (unknown_type_node) = unknown_type_node;
4599 TYPE_REFERENCE_TO (unknown_type_node) = unknown_type_node;
4601 init_list_type_node = make_node (LANG_TYPE);
4602 record_unknown_type (init_list_type_node, "init list");
4604 /* Used when parsing to distinguish parameter-lists () and (void). */
4605 explicit_void_list_node = build_void_list_node ();
4608 /* Make sure we get a unique function type, so we can give
4609 its pointer type a name. (This wins for gdb.) */
4610 tree vfunc_type = make_node (FUNCTION_TYPE);
4611 TREE_TYPE (vfunc_type) = integer_type_node;
4612 TYPE_ARG_TYPES (vfunc_type) = NULL_TREE;
4613 layout_type (vfunc_type);
4615 vtable_entry_type = build_pointer_type (vfunc_type);
4617 record_builtin_type (RID_MAX, "__vtbl_ptr_type", vtable_entry_type);
4619 vtbl_type_node
4620 = build_cplus_array_type (vtable_entry_type, NULL_TREE);
4621 layout_type (vtbl_type_node);
4622 vtbl_type_node = cp_build_qualified_type (vtbl_type_node, TYPE_QUAL_CONST);
4623 record_builtin_type (RID_MAX, NULL, vtbl_type_node);
4624 vtbl_ptr_type_node = build_pointer_type (vtable_entry_type);
4625 layout_type (vtbl_ptr_type_node);
4626 record_builtin_type (RID_MAX, NULL, vtbl_ptr_type_node);
4628 push_namespace (get_identifier ("__cxxabiv1"));
4629 abi_node = current_namespace;
4630 pop_namespace ();
4632 any_targ_node = make_node (LANG_TYPE);
4633 record_unknown_type (any_targ_node, "any type");
4635 /* Now, C++. */
4636 current_lang_name = lang_name_cplusplus;
4638 if (aligned_new_threshold > 1
4639 && !pow2p_hwi (aligned_new_threshold))
4641 error ("%<-faligned-new=%d%> is not a power of two",
4642 aligned_new_threshold);
4643 aligned_new_threshold = 1;
4645 if (aligned_new_threshold == -1)
4646 aligned_new_threshold = (cxx_dialect >= cxx17) ? 1 : 0;
4647 if (aligned_new_threshold == 1)
4648 aligned_new_threshold = malloc_alignment () / BITS_PER_UNIT;
4651 tree newattrs, extvisattr;
4652 tree newtype, deltype;
4653 tree ptr_ftype_sizetype;
4654 tree new_eh_spec;
4656 ptr_ftype_sizetype
4657 = build_function_type_list (ptr_type_node, size_type_node, NULL_TREE);
4658 if (cxx_dialect == cxx98)
4660 tree bad_alloc_id;
4661 tree bad_alloc_type_node;
4662 tree bad_alloc_decl;
4664 push_nested_namespace (std_node);
4665 bad_alloc_id = get_identifier ("bad_alloc");
4666 bad_alloc_type_node = make_class_type (RECORD_TYPE);
4667 TYPE_CONTEXT (bad_alloc_type_node) = current_namespace;
4668 bad_alloc_decl
4669 = create_implicit_typedef (bad_alloc_id, bad_alloc_type_node);
4670 DECL_CONTEXT (bad_alloc_decl) = current_namespace;
4671 pop_nested_namespace (std_node);
4673 new_eh_spec
4674 = add_exception_specifier (NULL_TREE, bad_alloc_type_node, -1);
4676 else
4677 new_eh_spec = noexcept_false_spec;
4679 /* Ensure attribs.cc is initialized. */
4680 init_attributes ();
4682 extvisattr = build_tree_list (get_identifier ("externally_visible"),
4683 NULL_TREE);
4684 newattrs = tree_cons (get_identifier ("alloc_size"),
4685 build_tree_list (NULL_TREE, integer_one_node),
4686 extvisattr);
4687 newtype = cp_build_type_attribute_variant (ptr_ftype_sizetype, newattrs);
4688 newtype = build_exception_variant (newtype, new_eh_spec);
4689 deltype = cp_build_type_attribute_variant (void_ftype_ptr, extvisattr);
4690 deltype = build_exception_variant (deltype, empty_except_spec);
4691 tree opnew = push_cp_library_fn (NEW_EXPR, newtype, 0);
4692 DECL_IS_MALLOC (opnew) = 1;
4693 DECL_SET_IS_OPERATOR_NEW (opnew, true);
4694 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4695 opnew = push_cp_library_fn (VEC_NEW_EXPR, newtype, 0);
4696 DECL_IS_MALLOC (opnew) = 1;
4697 DECL_SET_IS_OPERATOR_NEW (opnew, true);
4698 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4699 tree opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4700 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4701 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4702 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4703 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4704 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4705 if (flag_sized_deallocation)
4707 /* Also push the sized deallocation variants:
4708 void operator delete(void*, std::size_t) throw();
4709 void operator delete[](void*, std::size_t) throw(); */
4710 tree void_ftype_ptr_size
4711 = build_function_type_list (void_type_node, ptr_type_node,
4712 size_type_node, NULL_TREE);
4713 deltype = cp_build_type_attribute_variant (void_ftype_ptr_size,
4714 extvisattr);
4715 deltype = build_exception_variant (deltype, empty_except_spec);
4716 opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4717 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4718 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4719 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4720 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4721 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4724 if (aligned_new_threshold)
4726 push_nested_namespace (std_node);
4727 tree align_id = get_identifier ("align_val_t");
4728 align_type_node = start_enum (align_id, NULL_TREE, size_type_node,
4729 NULL_TREE, /*scoped*/true, NULL);
4730 pop_nested_namespace (std_node);
4732 /* operator new (size_t, align_val_t); */
4733 newtype = build_function_type_list (ptr_type_node, size_type_node,
4734 align_type_node, NULL_TREE);
4735 newtype = cp_build_type_attribute_variant (newtype, newattrs);
4736 newtype = build_exception_variant (newtype, new_eh_spec);
4737 opnew = push_cp_library_fn (NEW_EXPR, newtype, 0);
4738 DECL_IS_MALLOC (opnew) = 1;
4739 DECL_SET_IS_OPERATOR_NEW (opnew, true);
4740 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4741 opnew = push_cp_library_fn (VEC_NEW_EXPR, newtype, 0);
4742 DECL_IS_MALLOC (opnew) = 1;
4743 DECL_SET_IS_OPERATOR_NEW (opnew, true);
4744 DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4746 /* operator delete (void *, align_val_t); */
4747 deltype = build_function_type_list (void_type_node, ptr_type_node,
4748 align_type_node, NULL_TREE);
4749 deltype = cp_build_type_attribute_variant (deltype, extvisattr);
4750 deltype = build_exception_variant (deltype, empty_except_spec);
4751 opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4752 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4753 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4754 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4755 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4756 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4758 if (flag_sized_deallocation)
4760 /* operator delete (void *, size_t, align_val_t); */
4761 deltype = build_function_type_list (void_type_node, ptr_type_node,
4762 size_type_node, align_type_node,
4763 NULL_TREE);
4764 deltype = cp_build_type_attribute_variant (deltype, extvisattr);
4765 deltype = build_exception_variant (deltype, empty_except_spec);
4766 opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4767 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4768 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4769 opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4770 DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4771 DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4775 nullptr_type_node = make_node (NULLPTR_TYPE);
4776 TYPE_SIZE (nullptr_type_node) = bitsize_int (GET_MODE_BITSIZE (ptr_mode));
4777 TYPE_SIZE_UNIT (nullptr_type_node) = size_int (GET_MODE_SIZE (ptr_mode));
4778 TYPE_UNSIGNED (nullptr_type_node) = 1;
4779 TYPE_PRECISION (nullptr_type_node) = GET_MODE_BITSIZE (ptr_mode);
4780 if (abi_version_at_least (9))
4781 SET_TYPE_ALIGN (nullptr_type_node, GET_MODE_ALIGNMENT (ptr_mode));
4782 SET_TYPE_MODE (nullptr_type_node, ptr_mode);
4783 record_builtin_type (RID_MAX, "decltype(nullptr)", nullptr_type_node);
4784 nullptr_node = build_int_cst (nullptr_type_node, 0);
4787 if (! supports_one_only ())
4788 flag_weak = 0;
4790 abort_fndecl
4791 = build_library_fn_ptr ("__cxa_pure_virtual", void_ftype,
4792 ECF_NORETURN | ECF_NOTHROW | ECF_COLD);
4793 if (flag_weak)
4794 /* If no definition is available, resolve references to NULL. */
4795 declare_weak (abort_fndecl);
4797 /* Perform other language dependent initializations. */
4798 init_class_processing ();
4799 init_rtti_processing ();
4800 init_template_processing ();
4802 if (flag_exceptions)
4803 init_exception_processing ();
4805 if (modules_p ())
4806 init_modules (parse_in);
4808 make_fname_decl = cp_make_fname_decl;
4809 start_fname_decls ();
4811 /* Show we use EH for cleanups. */
4812 if (flag_exceptions)
4813 using_eh_for_cleanups ();
4815 /* Check that the hardware interference sizes are at least
4816 alignof(max_align_t), as required by the standard. */
4817 const int max_align = max_align_t_align () / BITS_PER_UNIT;
4818 if (OPTION_SET_P (param_destruct_interfere_size))
4820 if (param_destruct_interfere_size < max_align)
4821 error ("%<--param destructive-interference-size=%d%> is less than "
4822 "%d", param_destruct_interfere_size, max_align);
4823 else if (param_destruct_interfere_size < param_l1_cache_line_size)
4824 warning (OPT_Winterference_size,
4825 "%<--param destructive-interference-size=%d%> "
4826 "is less than %<--param l1-cache-line-size=%d%>",
4827 param_destruct_interfere_size, param_l1_cache_line_size);
4829 else if (param_destruct_interfere_size)
4830 /* Assume the internal value is OK. */;
4831 else if (param_l1_cache_line_size >= max_align)
4832 param_destruct_interfere_size = param_l1_cache_line_size;
4833 /* else leave it unset. */
4835 if (OPTION_SET_P (param_construct_interfere_size))
4837 if (param_construct_interfere_size < max_align)
4838 error ("%<--param constructive-interference-size=%d%> is less than "
4839 "%d", param_construct_interfere_size, max_align);
4840 else if (param_construct_interfere_size > param_l1_cache_line_size
4841 && param_l1_cache_line_size >= max_align)
4842 warning (OPT_Winterference_size,
4843 "%<--param constructive-interference-size=%d%> "
4844 "is greater than %<--param l1-cache-line-size=%d%>",
4845 param_construct_interfere_size, param_l1_cache_line_size);
4847 else if (param_construct_interfere_size)
4848 /* Assume the internal value is OK. */;
4849 else if (param_l1_cache_line_size >= max_align)
4850 param_construct_interfere_size = param_l1_cache_line_size;
4853 /* Enter an abi node in global-module context. returns a cookie to
4854 give to pop_abi_namespace. */
4856 unsigned
4857 push_abi_namespace (tree node)
4859 push_nested_namespace (node);
4860 push_visibility ("default", 2);
4861 unsigned flags = module_kind;
4862 module_kind = 0;
4863 return flags;
4866 /* Pop an abi namespace, FLAGS is the cookie push_abi_namespace gave
4867 you. */
4869 void
4870 pop_abi_namespace (unsigned flags, tree node)
4872 module_kind = flags;
4873 pop_visibility (2);
4874 pop_nested_namespace (node);
4877 /* Create the VAR_DECL for __FUNCTION__ etc. ID is the name to give
4878 the decl, LOC is the location to give the decl, NAME is the
4879 initialization string and TYPE_DEP indicates whether NAME depended
4880 on the type of the function. We make use of that to detect
4881 __PRETTY_FUNCTION__ inside a template fn. This is being done lazily
4882 at the point of first use, so we mustn't push the decl now. */
4884 static tree
4885 cp_make_fname_decl (location_t loc, tree id, int type_dep)
4887 tree domain = NULL_TREE;
4888 tree init = NULL_TREE;
4890 if (!(type_dep && in_template_function ()))
4892 const char *name = NULL;
4893 bool release_name = false;
4895 if (current_function_decl == NULL_TREE)
4896 name = "top level";
4897 else if (type_dep == 0)
4899 /* __FUNCTION__ */
4900 name = fname_as_string (type_dep);
4901 release_name = true;
4903 else
4905 /* __PRETTY_FUNCTION__ */
4906 gcc_checking_assert (type_dep == 1);
4907 name = cxx_printable_name (current_function_decl, 2);
4910 size_t length = strlen (name);
4911 domain = build_index_type (size_int (length));
4912 init = build_string (length + 1, name);
4913 if (release_name)
4914 free (const_cast<char *> (name));
4917 tree type = cp_build_qualified_type (char_type_node, TYPE_QUAL_CONST);
4918 type = build_cplus_array_type (type, domain);
4920 if (init)
4921 TREE_TYPE (init) = type;
4922 else
4923 init = error_mark_node;
4925 tree decl = build_decl (loc, VAR_DECL, id, type);
4927 TREE_READONLY (decl) = 1;
4928 DECL_ARTIFICIAL (decl) = 1;
4929 DECL_DECLARED_CONSTEXPR_P (decl) = 1;
4930 TREE_STATIC (decl) = 1;
4932 TREE_USED (decl) = 1;
4934 SET_DECL_VALUE_EXPR (decl, init);
4935 DECL_HAS_VALUE_EXPR_P (decl) = 1;
4936 /* For decl_constant_var_p. */
4937 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = 1;
4939 if (current_function_decl)
4941 DECL_CONTEXT (decl) = current_function_decl;
4942 decl = pushdecl_outermost_localscope (decl);
4943 if (decl != error_mark_node)
4944 add_decl_expr (decl);
4946 else
4948 DECL_THIS_STATIC (decl) = true;
4949 decl = pushdecl_top_level_and_finish (decl, NULL_TREE);
4952 return decl;
4955 /* Install DECL as a builtin function at current global scope. Return
4956 the new decl (if we found an existing version). Also installs it
4957 into ::std, if it's not '_*'. */
4959 tree
4960 cxx_builtin_function (tree decl)
4962 retrofit_lang_decl (decl);
4964 DECL_ARTIFICIAL (decl) = 1;
4965 SET_DECL_LANGUAGE (decl, lang_c);
4966 /* Runtime library routines are, by definition, available in an
4967 external shared object. */
4968 DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
4969 DECL_VISIBILITY_SPECIFIED (decl) = 1;
4971 tree id = DECL_NAME (decl);
4972 const char *name = IDENTIFIER_POINTER (id);
4973 bool hiding = false;
4974 if (name[0] != '_' || name[1] != '_')
4975 /* In the user's namespace, it must be declared before use. */
4976 hiding = true;
4977 else if (IDENTIFIER_LENGTH (id) > strlen ("___chk")
4978 && !startswith (name + 2, "builtin_")
4979 && 0 == memcmp (name + IDENTIFIER_LENGTH (id) - strlen ("_chk"),
4980 "_chk", strlen ("_chk") + 1))
4981 /* Treat __*_chk fortification functions as anticipated as well,
4982 unless they are __builtin_*_chk. */
4983 hiding = true;
4985 /* All builtins that don't begin with an '_' should additionally
4986 go in the 'std' namespace. */
4987 if (name[0] != '_')
4989 tree std_decl = copy_decl (decl);
4991 push_nested_namespace (std_node);
4992 DECL_CONTEXT (std_decl) = FROB_CONTEXT (std_node);
4993 pushdecl (std_decl, hiding);
4994 pop_nested_namespace (std_node);
4997 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4998 decl = pushdecl (decl, hiding);
5000 return decl;
5003 /* Like cxx_builtin_function, but guarantee the function is added to the global
5004 scope. This is to allow function specific options to add new machine
5005 dependent builtins when the target ISA changes via attribute((target(...)))
5006 which saves space on program startup if the program does not use non-generic
5007 ISAs. */
5009 tree
5010 cxx_builtin_function_ext_scope (tree decl)
5012 push_nested_namespace (global_namespace);
5013 decl = cxx_builtin_function (decl);
5014 pop_nested_namespace (global_namespace);
5016 return decl;
5019 /* Implement LANG_HOOKS_SIMULATE_BUILTIN_FUNCTION_DECL. */
5021 tree
5022 cxx_simulate_builtin_function_decl (tree decl)
5024 retrofit_lang_decl (decl);
5026 DECL_ARTIFICIAL (decl) = 1;
5027 SET_DECL_LANGUAGE (decl, lang_cplusplus);
5028 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5029 return pushdecl (decl);
5032 /* Generate a FUNCTION_DECL with the typical flags for a runtime library
5033 function. Not called directly. */
5035 static tree
5036 build_library_fn (tree name, enum tree_code operator_code, tree type,
5037 int ecf_flags)
5039 tree fn = build_lang_decl (FUNCTION_DECL, name, type);
5040 DECL_EXTERNAL (fn) = 1;
5041 TREE_PUBLIC (fn) = 1;
5042 DECL_ARTIFICIAL (fn) = 1;
5043 DECL_OVERLOADED_OPERATOR_CODE_RAW (fn)
5044 = OVL_OP_INFO (false, operator_code)->ovl_op_code;
5045 SET_DECL_LANGUAGE (fn, lang_c);
5046 /* Runtime library routines are, by definition, available in an
5047 external shared object. */
5048 DECL_VISIBILITY (fn) = VISIBILITY_DEFAULT;
5049 DECL_VISIBILITY_SPECIFIED (fn) = 1;
5050 set_call_expr_flags (fn, ecf_flags);
5051 return fn;
5054 /* Returns the _DECL for a library function with C++ linkage. */
5056 static tree
5057 build_cp_library_fn (tree name, enum tree_code operator_code, tree type,
5058 int ecf_flags)
5060 tree fn = build_library_fn (name, operator_code, type, ecf_flags);
5061 DECL_CONTEXT (fn) = FROB_CONTEXT (current_namespace);
5062 SET_DECL_LANGUAGE (fn, lang_cplusplus);
5063 return fn;
5066 /* Like build_library_fn, but takes a C string instead of an
5067 IDENTIFIER_NODE. */
5069 tree
5070 build_library_fn_ptr (const char* name, tree type, int ecf_flags)
5072 return build_library_fn (get_identifier (name), ERROR_MARK, type, ecf_flags);
5075 /* Like build_cp_library_fn, but takes a C string instead of an
5076 IDENTIFIER_NODE. */
5078 tree
5079 build_cp_library_fn_ptr (const char* name, tree type, int ecf_flags)
5081 return build_cp_library_fn (get_identifier (name), ERROR_MARK, type,
5082 ecf_flags);
5085 /* Like build_library_fn, but also pushes the function so that we will
5086 be able to find it via get_global_binding. Also, the function
5087 may throw exceptions listed in RAISES. */
5089 tree
5090 push_library_fn (tree name, tree type, tree raises, int ecf_flags)
5092 if (raises)
5093 type = build_exception_variant (type, raises);
5095 tree fn = build_library_fn (name, ERROR_MARK, type, ecf_flags);
5096 return pushdecl_top_level (fn);
5099 /* Like build_cp_library_fn, but also pushes the function so that it
5100 will be found by normal lookup. */
5102 static tree
5103 push_cp_library_fn (enum tree_code operator_code, tree type,
5104 int ecf_flags)
5106 tree fn = build_cp_library_fn (ovl_op_identifier (false, operator_code),
5107 operator_code, type, ecf_flags);
5108 pushdecl (fn);
5109 if (flag_tm)
5110 apply_tm_attr (fn, get_identifier ("transaction_safe"));
5111 return fn;
5114 /* Like push_library_fn, but also note that this function throws
5115 and does not return. Used for __throw_foo and the like. */
5117 tree
5118 push_throw_library_fn (tree name, tree type)
5120 tree fn = push_library_fn (name, type, NULL_TREE, ECF_NORETURN | ECF_COLD);
5121 return fn;
5124 /* When we call finish_struct for an anonymous union, we create
5125 default copy constructors and such. But, an anonymous union
5126 shouldn't have such things; this function undoes the damage to the
5127 anonymous union type T.
5129 (The reason that we create the synthesized methods is that we don't
5130 distinguish `union { int i; }' from `typedef union { int i; } U'.
5131 The first is an anonymous union; the second is just an ordinary
5132 union type.) */
5134 void
5135 fixup_anonymous_aggr (tree t)
5137 /* Wipe out memory of synthesized methods. */
5138 TYPE_HAS_USER_CONSTRUCTOR (t) = 0;
5139 TYPE_HAS_DEFAULT_CONSTRUCTOR (t) = 0;
5140 TYPE_HAS_COPY_CTOR (t) = 0;
5141 TYPE_HAS_CONST_COPY_CTOR (t) = 0;
5142 TYPE_HAS_COPY_ASSIGN (t) = 0;
5143 TYPE_HAS_CONST_COPY_ASSIGN (t) = 0;
5145 /* Splice the implicitly generated functions out of TYPE_FIELDS and diagnose
5146 invalid members. */
5147 for (tree probe, *prev_p = &TYPE_FIELDS (t); (probe = *prev_p);)
5149 if (TREE_CODE (probe) == FUNCTION_DECL && DECL_ARTIFICIAL (probe))
5150 *prev_p = DECL_CHAIN (probe);
5151 else
5152 prev_p = &DECL_CHAIN (probe);
5154 if (DECL_ARTIFICIAL (probe)
5155 && (!DECL_IMPLICIT_TYPEDEF_P (probe)
5156 || TYPE_ANON_P (TREE_TYPE (probe))))
5157 continue;
5159 if (TREE_CODE (probe) != FIELD_DECL
5160 || (TREE_PRIVATE (probe) || TREE_PROTECTED (probe)))
5162 /* We already complained about static data members in
5163 finish_static_data_member_decl. */
5164 if (!VAR_P (probe))
5166 auto_diagnostic_group d;
5167 if (permerror (DECL_SOURCE_LOCATION (probe),
5168 TREE_CODE (t) == UNION_TYPE
5169 ? "%q#D invalid; an anonymous union may "
5170 "only have public non-static data members"
5171 : "%q#D invalid; an anonymous struct may "
5172 "only have public non-static data members", probe))
5174 static bool hint;
5175 if (flag_permissive && !hint)
5177 hint = true;
5178 inform (DECL_SOURCE_LOCATION (probe),
5179 "this flexibility is deprecated and will be "
5180 "removed");
5187 /* Splice all functions out of CLASSTYPE_MEMBER_VEC. */
5188 vec<tree,va_gc>* vec = CLASSTYPE_MEMBER_VEC (t);
5189 unsigned store = 0;
5190 for (tree elt : vec)
5191 if (!is_overloaded_fn (elt))
5192 (*vec)[store++] = elt;
5193 vec_safe_truncate (vec, store);
5195 /* Wipe RTTI info. */
5196 CLASSTYPE_TYPEINFO_VAR (t) = NULL_TREE;
5198 /* Anonymous aggregates cannot have fields with ctors, dtors or complex
5199 assignment operators (because they cannot have these methods themselves).
5200 For anonymous unions this is already checked because they are not allowed
5201 in any union, otherwise we have to check it. */
5202 if (TREE_CODE (t) != UNION_TYPE)
5204 tree field, type;
5206 if (BINFO_N_BASE_BINFOS (TYPE_BINFO (t)))
5208 error_at (location_of (t), "anonymous struct with base classes");
5209 /* Avoid ICE after error on anon-struct9.C. */
5210 TYPE_NEEDS_CONSTRUCTING (t) = false;
5213 for (field = TYPE_FIELDS (t); field; field = DECL_CHAIN (field))
5214 if (TREE_CODE (field) == FIELD_DECL)
5216 type = TREE_TYPE (field);
5217 if (CLASS_TYPE_P (type))
5219 if (TYPE_NEEDS_CONSTRUCTING (type))
5220 error ("member %q+#D with constructor not allowed "
5221 "in anonymous aggregate", field);
5222 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
5223 error ("member %q+#D with destructor not allowed "
5224 "in anonymous aggregate", field);
5225 if (TYPE_HAS_COMPLEX_COPY_ASSIGN (type))
5226 error ("member %q+#D with copy assignment operator "
5227 "not allowed in anonymous aggregate", field);
5233 /* Warn for an attribute located at LOCATION that appertains to the
5234 class type CLASS_TYPE that has not been properly placed after its
5235 class-key, in it class-specifier. */
5237 void
5238 warn_misplaced_attr_for_class_type (location_t location,
5239 tree class_type)
5241 gcc_assert (OVERLOAD_TYPE_P (class_type));
5243 auto_diagnostic_group d;
5244 if (warning_at (location, OPT_Wattributes,
5245 "attribute ignored in declaration "
5246 "of %q#T", class_type))
5247 inform (location,
5248 "attribute for %q#T must follow the %qs keyword",
5249 class_type, class_key_or_enum_as_string (class_type));
5252 /* Returns the cv-qualifiers that apply to the type specified
5253 by the DECLSPECS. */
5255 static int
5256 get_type_quals (const cp_decl_specifier_seq *declspecs)
5258 int type_quals = TYPE_UNQUALIFIED;
5260 if (decl_spec_seq_has_spec_p (declspecs, ds_const))
5261 type_quals |= TYPE_QUAL_CONST;
5262 if (decl_spec_seq_has_spec_p (declspecs, ds_volatile))
5263 type_quals |= TYPE_QUAL_VOLATILE;
5264 if (decl_spec_seq_has_spec_p (declspecs, ds_restrict))
5265 type_quals |= TYPE_QUAL_RESTRICT;
5267 return type_quals;
5270 /* Make sure that a declaration with no declarator is well-formed, i.e.
5271 just declares a tagged type or anonymous union.
5273 Returns the type declared; or NULL_TREE if none. */
5275 tree
5276 check_tag_decl (cp_decl_specifier_seq *declspecs,
5277 bool explicit_type_instantiation_p)
5279 int saw_friend = decl_spec_seq_has_spec_p (declspecs, ds_friend);
5280 int saw_typedef = decl_spec_seq_has_spec_p (declspecs, ds_typedef);
5281 /* If a class, struct, or enum type is declared by the DECLSPECS
5282 (i.e, if a class-specifier, enum-specifier, or non-typename
5283 elaborated-type-specifier appears in the DECLSPECS),
5284 DECLARED_TYPE is set to the corresponding type. */
5285 tree declared_type = NULL_TREE;
5286 bool error_p = false;
5288 if (declspecs->multiple_types_p)
5289 error_at (smallest_type_location (declspecs),
5290 "multiple types in one declaration");
5291 else if (declspecs->redefined_builtin_type)
5293 location_t loc = declspecs->locations[ds_redefined_builtin_type_spec];
5294 if (!in_system_header_at (loc))
5295 permerror (loc, "redeclaration of C++ built-in type %qT",
5296 declspecs->redefined_builtin_type);
5297 return NULL_TREE;
5300 if (declspecs->type
5301 && TYPE_P (declspecs->type)
5302 && ((TREE_CODE (declspecs->type) != TYPENAME_TYPE
5303 && MAYBE_CLASS_TYPE_P (declspecs->type))
5304 || TREE_CODE (declspecs->type) == ENUMERAL_TYPE))
5305 declared_type = declspecs->type;
5306 else if (declspecs->type == error_mark_node)
5307 error_p = true;
5309 if (type_uses_auto (declared_type))
5311 error_at (declspecs->locations[ds_type_spec],
5312 "%<auto%> can only be specified for variables "
5313 "or function declarations");
5314 return error_mark_node;
5317 if (declared_type && !OVERLOAD_TYPE_P (declared_type))
5318 declared_type = NULL_TREE;
5320 if (!declared_type && !saw_friend && !error_p)
5321 permerror (input_location, "declaration does not declare anything");
5322 /* Check for an anonymous union. */
5323 else if (declared_type && RECORD_OR_UNION_CODE_P (TREE_CODE (declared_type))
5324 && TYPE_UNNAMED_P (declared_type))
5326 /* 7/3 In a simple-declaration, the optional init-declarator-list
5327 can be omitted only when declaring a class (clause 9) or
5328 enumeration (7.2), that is, when the decl-specifier-seq contains
5329 either a class-specifier, an elaborated-type-specifier with
5330 a class-key (9.1), or an enum-specifier. In these cases and
5331 whenever a class-specifier or enum-specifier is present in the
5332 decl-specifier-seq, the identifiers in these specifiers are among
5333 the names being declared by the declaration (as class-name,
5334 enum-names, or enumerators, depending on the syntax). In such
5335 cases, and except for the declaration of an unnamed bit-field (9.6),
5336 the decl-specifier-seq shall introduce one or more names into the
5337 program, or shall redeclare a name introduced by a previous
5338 declaration. [Example:
5339 enum { }; // ill-formed
5340 typedef class { }; // ill-formed
5341 --end example] */
5342 if (saw_typedef)
5344 error_at (declspecs->locations[ds_typedef],
5345 "missing type-name in typedef-declaration");
5346 return NULL_TREE;
5348 /* Anonymous unions are objects, so they can have specifiers. */;
5349 SET_ANON_AGGR_TYPE_P (declared_type);
5351 if (TREE_CODE (declared_type) != UNION_TYPE)
5352 pedwarn (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (declared_type)),
5353 OPT_Wpedantic, "ISO C++ prohibits anonymous structs");
5356 else
5358 if (decl_spec_seq_has_spec_p (declspecs, ds_inline))
5359 error_at (declspecs->locations[ds_inline],
5360 "%<inline%> can only be specified for functions");
5361 else if (decl_spec_seq_has_spec_p (declspecs, ds_virtual))
5362 error_at (declspecs->locations[ds_virtual],
5363 "%<virtual%> can only be specified for functions");
5364 else if (saw_friend
5365 && (!current_class_type
5366 || current_scope () != current_class_type))
5367 error_at (declspecs->locations[ds_friend],
5368 "%<friend%> can only be specified inside a class");
5369 else if (decl_spec_seq_has_spec_p (declspecs, ds_explicit))
5370 error_at (declspecs->locations[ds_explicit],
5371 "%<explicit%> can only be specified for constructors");
5372 else if (declspecs->storage_class)
5373 error_at (declspecs->locations[ds_storage_class],
5374 "a storage class can only be specified for objects "
5375 "and functions");
5376 else if (decl_spec_seq_has_spec_p (declspecs, ds_const))
5377 error_at (declspecs->locations[ds_const],
5378 "%<const%> can only be specified for objects and "
5379 "functions");
5380 else if (decl_spec_seq_has_spec_p (declspecs, ds_volatile))
5381 error_at (declspecs->locations[ds_volatile],
5382 "%<volatile%> can only be specified for objects and "
5383 "functions");
5384 else if (decl_spec_seq_has_spec_p (declspecs, ds_restrict))
5385 error_at (declspecs->locations[ds_restrict],
5386 "%<__restrict%> can only be specified for objects and "
5387 "functions");
5388 else if (decl_spec_seq_has_spec_p (declspecs, ds_thread))
5389 error_at (declspecs->locations[ds_thread],
5390 "%<__thread%> can only be specified for objects "
5391 "and functions");
5392 else if (saw_typedef)
5393 warning_at (declspecs->locations[ds_typedef], 0,
5394 "%<typedef%> was ignored in this declaration");
5395 else if (decl_spec_seq_has_spec_p (declspecs, ds_constexpr))
5396 error_at (declspecs->locations[ds_constexpr],
5397 "%qs cannot be used for type declarations", "constexpr");
5398 else if (decl_spec_seq_has_spec_p (declspecs, ds_constinit))
5399 error_at (declspecs->locations[ds_constinit],
5400 "%qs cannot be used for type declarations", "constinit");
5401 else if (decl_spec_seq_has_spec_p (declspecs, ds_consteval))
5402 error_at (declspecs->locations[ds_consteval],
5403 "%qs cannot be used for type declarations", "consteval");
5406 if (declspecs->attributes && warn_attributes && declared_type)
5408 location_t loc;
5409 if (!CLASS_TYPE_P (declared_type)
5410 || !CLASSTYPE_TEMPLATE_INSTANTIATION (declared_type))
5411 /* For a non-template class, use the name location. */
5412 loc = location_of (declared_type);
5413 else
5414 /* For a template class (an explicit instantiation), use the
5415 current location. */
5416 loc = input_location;
5418 if (explicit_type_instantiation_p)
5419 /* [dcl.attr.grammar]/4:
5421 No attribute-specifier-seq shall appertain to an explicit
5422 instantiation. */
5424 if (warning_at (loc, OPT_Wattributes,
5425 "attribute ignored in explicit instantiation %q#T",
5426 declared_type))
5427 inform (loc,
5428 "no attribute can be applied to "
5429 "an explicit instantiation");
5431 else
5432 warn_misplaced_attr_for_class_type (loc, declared_type);
5435 return declared_type;
5438 /* Called when a declaration is seen that contains no names to declare.
5439 If its type is a reference to a structure, union or enum inherited
5440 from a containing scope, shadow that tag name for the current scope
5441 with a forward reference.
5442 If its type defines a new named structure or union
5443 or defines an enum, it is valid but we need not do anything here.
5444 Otherwise, it is an error.
5446 C++: may have to grok the declspecs to learn about static,
5447 complain for anonymous unions.
5449 Returns the TYPE declared -- or NULL_TREE if none. */
5451 tree
5452 shadow_tag (cp_decl_specifier_seq *declspecs)
5454 tree t = check_tag_decl (declspecs,
5455 /*explicit_type_instantiation_p=*/false);
5457 if (!t)
5458 return NULL_TREE;
5460 if (maybe_process_partial_specialization (t) == error_mark_node)
5461 return NULL_TREE;
5463 /* This is where the variables in an anonymous union are
5464 declared. An anonymous union declaration looks like:
5465 union { ... } ;
5466 because there is no declarator after the union, the parser
5467 sends that declaration here. */
5468 if (ANON_AGGR_TYPE_P (t))
5470 fixup_anonymous_aggr (t);
5472 if (TYPE_FIELDS (t))
5474 tree decl = grokdeclarator (/*declarator=*/NULL,
5475 declspecs, NORMAL, 0, NULL);
5476 finish_anon_union (decl);
5480 return t;
5483 /* Decode a "typename", such as "int **", returning a ..._TYPE node. */
5485 tree
5486 groktypename (cp_decl_specifier_seq *type_specifiers,
5487 const cp_declarator *declarator,
5488 bool is_template_arg)
5490 tree attrs;
5491 tree type;
5492 enum decl_context context
5493 = is_template_arg ? TEMPLATE_TYPE_ARG : TYPENAME;
5494 attrs = type_specifiers->attributes;
5495 type_specifiers->attributes = NULL_TREE;
5496 type = grokdeclarator (declarator, type_specifiers, context, 0, &attrs);
5497 if (attrs && type != error_mark_node)
5499 if (CLASS_TYPE_P (type))
5500 warning (OPT_Wattributes, "ignoring attributes applied to class type %qT "
5501 "outside of definition", type);
5502 else if (MAYBE_CLASS_TYPE_P (type))
5503 /* A template type parameter or other dependent type. */
5504 warning (OPT_Wattributes, "ignoring attributes applied to dependent "
5505 "type %qT without an associated declaration", type);
5506 else
5507 cplus_decl_attributes (&type, attrs, 0);
5509 return type;
5512 /* Process a DECLARATOR for a function-scope or namespace-scope
5513 variable or function declaration.
5514 (Function definitions go through start_function; class member
5515 declarations appearing in the body of the class go through
5516 grokfield.) The DECL corresponding to the DECLARATOR is returned.
5517 If an error occurs, the error_mark_node is returned instead.
5519 DECLSPECS are the decl-specifiers for the declaration. INITIALIZED is
5520 SD_INITIALIZED if an explicit initializer is present, or SD_DEFAULTED
5521 for an explicitly defaulted function, or SD_DELETED for an explicitly
5522 deleted function, but 0 (SD_UNINITIALIZED) if this is a variable
5523 implicitly initialized via a default constructor. It can also be
5524 SD_DECOMPOSITION which behaves much like SD_INITIALIZED, but we also
5525 mark the new decl as DECL_DECOMPOSITION_P.
5527 ATTRIBUTES and PREFIX_ATTRIBUTES are GNU attributes associated with this
5528 declaration.
5530 The scope represented by the context of the returned DECL is pushed
5531 (if it is not the global namespace) and is assigned to
5532 *PUSHED_SCOPE_P. The caller is then responsible for calling
5533 pop_scope on *PUSHED_SCOPE_P if it is set. */
5535 tree
5536 start_decl (const cp_declarator *declarator,
5537 cp_decl_specifier_seq *declspecs,
5538 int initialized,
5539 tree attributes,
5540 tree prefix_attributes,
5541 tree *pushed_scope_p)
5543 tree decl;
5544 tree context;
5545 bool was_public;
5546 int flags;
5547 bool alias;
5548 tree initial;
5550 *pushed_scope_p = NULL_TREE;
5552 if (prefix_attributes != error_mark_node)
5553 attributes = chainon (attributes, prefix_attributes);
5555 decl = grokdeclarator (declarator, declspecs, NORMAL, initialized,
5556 &attributes);
5558 if (decl == NULL_TREE || VOID_TYPE_P (decl)
5559 || decl == error_mark_node
5560 || prefix_attributes == error_mark_node)
5561 return error_mark_node;
5563 context = CP_DECL_CONTEXT (decl);
5564 if (context != global_namespace)
5565 *pushed_scope_p = push_scope (context);
5567 if (initialized && TREE_CODE (decl) == TYPE_DECL)
5569 error_at (DECL_SOURCE_LOCATION (decl),
5570 "typedef %qD is initialized (use %qs instead)",
5571 decl, "decltype");
5572 return error_mark_node;
5575 /* Save the DECL_INITIAL value in case it gets clobbered to assist
5576 with attribute validation. */
5577 initial = DECL_INITIAL (decl);
5579 if (initialized)
5581 if (! toplevel_bindings_p ()
5582 && DECL_EXTERNAL (decl))
5583 warning (0, "declaration of %q#D has %<extern%> and is initialized",
5584 decl);
5585 DECL_EXTERNAL (decl) = 0;
5586 if (toplevel_bindings_p ())
5587 TREE_STATIC (decl) = 1;
5588 /* Tell 'cplus_decl_attributes' this is an initialized decl,
5589 even though we might not yet have the initializer expression. */
5590 if (!DECL_INITIAL (decl))
5591 DECL_INITIAL (decl) = error_mark_node;
5593 alias = lookup_attribute ("alias", DECL_ATTRIBUTES (decl)) != 0;
5595 if (alias && TREE_CODE (decl) == FUNCTION_DECL)
5596 record_key_method_defined (decl);
5598 /* If this is a typedef that names the class for linkage purposes
5599 (7.1.3p8), apply any attributes directly to the type. */
5600 if (TREE_CODE (decl) == TYPE_DECL
5601 && OVERLOAD_TYPE_P (TREE_TYPE (decl))
5602 && decl == TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (decl))))
5603 flags = ATTR_FLAG_TYPE_IN_PLACE;
5604 else
5605 flags = 0;
5607 /* Set attributes here so if duplicate decl, will have proper attributes. */
5608 cplus_decl_attributes (&decl, attributes, flags);
5610 /* Restore the original DECL_INITIAL that we may have clobbered earlier to
5611 assist with attribute validation. */
5612 DECL_INITIAL (decl) = initial;
5614 /* Dllimported symbols cannot be defined. Static data members (which
5615 can be initialized in-class and dllimported) go through grokfield,
5616 not here, so we don't need to exclude those decls when checking for
5617 a definition. */
5618 if (initialized && DECL_DLLIMPORT_P (decl))
5620 error_at (DECL_SOURCE_LOCATION (decl),
5621 "definition of %q#D is marked %<dllimport%>", decl);
5622 DECL_DLLIMPORT_P (decl) = 0;
5625 /* If #pragma weak was used, mark the decl weak now. */
5626 if (!processing_template_decl && !DECL_DECOMPOSITION_P (decl))
5627 maybe_apply_pragma_weak (decl);
5629 if (TREE_CODE (decl) == FUNCTION_DECL
5630 && DECL_DECLARED_INLINE_P (decl)
5631 && DECL_UNINLINABLE (decl)
5632 && lookup_attribute ("noinline", DECL_ATTRIBUTES (decl)))
5633 warning_at (DECL_SOURCE_LOCATION (decl), 0,
5634 "inline function %qD given attribute %qs", decl, "noinline");
5636 if (TYPE_P (context) && COMPLETE_TYPE_P (complete_type (context)))
5638 bool this_tmpl = (current_template_depth
5639 > template_class_depth (context));
5640 if (VAR_P (decl))
5642 tree field = lookup_field (context, DECL_NAME (decl), 0, false);
5643 if (field == NULL_TREE
5644 || !(VAR_P (field) || variable_template_p (field)))
5645 error ("%q+#D is not a static data member of %q#T", decl, context);
5646 else if (variable_template_p (field)
5647 && (DECL_LANG_SPECIFIC (decl)
5648 && DECL_TEMPLATE_SPECIALIZATION (decl)))
5649 /* OK, specialization was already checked. */;
5650 else if (variable_template_p (field) && !this_tmpl)
5652 error_at (DECL_SOURCE_LOCATION (decl),
5653 "non-member-template declaration of %qD", decl);
5654 inform (DECL_SOURCE_LOCATION (field), "does not match "
5655 "member template declaration here");
5656 return error_mark_node;
5658 else
5660 if (variable_template_p (field))
5661 field = DECL_TEMPLATE_RESULT (field);
5663 if (DECL_CONTEXT (field) != context)
5665 if (!same_type_p (DECL_CONTEXT (field), context))
5666 permerror (input_location, "ISO C++ does not permit %<%T::%D%> "
5667 "to be defined as %<%T::%D%>",
5668 DECL_CONTEXT (field), DECL_NAME (decl),
5669 context, DECL_NAME (decl));
5670 DECL_CONTEXT (decl) = DECL_CONTEXT (field);
5672 /* Static data member are tricky; an in-class initialization
5673 still doesn't provide a definition, so the in-class
5674 declaration will have DECL_EXTERNAL set, but will have an
5675 initialization. Thus, duplicate_decls won't warn
5676 about this situation, and so we check here. */
5677 if (initialized && DECL_INITIALIZED_IN_CLASS_P (field))
5678 error ("duplicate initialization of %qD", decl);
5679 field = duplicate_decls (decl, field);
5680 if (field == error_mark_node)
5681 return error_mark_node;
5682 else if (field)
5683 decl = field;
5686 else
5688 tree field = check_classfn (context, decl,
5689 this_tmpl
5690 ? current_template_parms
5691 : NULL_TREE);
5692 if (field && field != error_mark_node
5693 && duplicate_decls (decl, field))
5694 decl = field;
5697 /* cp_finish_decl sets DECL_EXTERNAL if DECL_IN_AGGR_P is set. */
5698 DECL_IN_AGGR_P (decl) = 0;
5699 /* Do not mark DECL as an explicit specialization if it was not
5700 already marked as an instantiation; a declaration should
5701 never be marked as a specialization unless we know what
5702 template is being specialized. */
5703 if (DECL_LANG_SPECIFIC (decl) && DECL_USE_TEMPLATE (decl))
5705 SET_DECL_TEMPLATE_SPECIALIZATION (decl);
5706 if (TREE_CODE (decl) == FUNCTION_DECL)
5707 DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
5708 && DECL_DECLARED_INLINE_P (decl));
5709 else
5710 DECL_COMDAT (decl) = false;
5712 /* [temp.expl.spec] An explicit specialization of a static data
5713 member of a template is a definition if the declaration
5714 includes an initializer; otherwise, it is a declaration.
5716 We check for processing_specialization so this only applies
5717 to the new specialization syntax. */
5718 if (!initialized && processing_specialization)
5719 DECL_EXTERNAL (decl) = 1;
5722 if (DECL_EXTERNAL (decl) && ! DECL_TEMPLATE_SPECIALIZATION (decl)
5723 /* Aliases are definitions. */
5724 && !alias)
5725 permerror (declarator->id_loc,
5726 "declaration of %q#D outside of class is not definition",
5727 decl);
5730 /* Create a DECL_LANG_SPECIFIC so that DECL_DECOMPOSITION_P works. */
5731 if (initialized == SD_DECOMPOSITION)
5732 fit_decomposition_lang_decl (decl, NULL_TREE);
5734 was_public = TREE_PUBLIC (decl);
5736 if ((DECL_EXTERNAL (decl) || TREE_CODE (decl) == FUNCTION_DECL)
5737 && current_function_decl)
5739 /* A function-scope decl of some namespace-scope decl. */
5740 DECL_LOCAL_DECL_P (decl) = true;
5741 if (named_module_purview_p ())
5742 error_at (declarator->id_loc,
5743 "block-scope extern declaration %q#D not permitted"
5744 " in module purview", decl);
5747 /* Enter this declaration into the symbol table. Don't push the plain
5748 VAR_DECL for a variable template. */
5749 if (!template_parm_scope_p ()
5750 || !VAR_P (decl))
5751 decl = maybe_push_decl (decl);
5753 if (processing_template_decl)
5754 decl = push_template_decl (decl);
5756 if (decl == error_mark_node)
5757 return error_mark_node;
5759 if (VAR_P (decl)
5760 && DECL_NAMESPACE_SCOPE_P (decl) && !TREE_PUBLIC (decl) && !was_public
5761 && !DECL_THIS_STATIC (decl) && !DECL_ARTIFICIAL (decl)
5762 /* But not templated variables. */
5763 && !(DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)))
5765 /* This is a const variable with implicit 'static'. Set
5766 DECL_THIS_STATIC so we can tell it from variables that are
5767 !TREE_PUBLIC because of the anonymous namespace. */
5768 gcc_assert (CP_TYPE_CONST_P (TREE_TYPE (decl)) || errorcount);
5769 DECL_THIS_STATIC (decl) = 1;
5772 if (current_function_decl && VAR_P (decl)
5773 && DECL_DECLARED_CONSTEXPR_P (current_function_decl)
5774 && cxx_dialect < cxx23)
5776 bool ok = false;
5777 if (CP_DECL_THREAD_LOCAL_P (decl))
5778 error_at (DECL_SOURCE_LOCATION (decl),
5779 "%qD declared %<thread_local%> in %qs function only "
5780 "available with %<-std=c++2b%> or %<-std=gnu++2b%>", decl,
5781 DECL_IMMEDIATE_FUNCTION_P (current_function_decl)
5782 ? "consteval" : "constexpr");
5783 else if (TREE_STATIC (decl))
5784 error_at (DECL_SOURCE_LOCATION (decl),
5785 "%qD declared %<static%> in %qs function only available "
5786 "with %<-std=c++2b%> or %<-std=gnu++2b%>", decl,
5787 DECL_IMMEDIATE_FUNCTION_P (current_function_decl)
5788 ? "consteval" : "constexpr");
5789 else
5790 ok = true;
5791 if (!ok)
5792 cp_function_chain->invalid_constexpr = true;
5795 if (!processing_template_decl && VAR_P (decl))
5796 start_decl_1 (decl, initialized);
5798 return decl;
5801 /* Process the declaration of a variable DECL. INITIALIZED is true
5802 iff DECL is explicitly initialized. (INITIALIZED is false if the
5803 variable is initialized via an implicitly-called constructor.)
5804 This function must be called for ordinary variables (including, for
5805 example, implicit instantiations of templates), but must not be
5806 called for template declarations. */
5808 void
5809 start_decl_1 (tree decl, bool initialized)
5811 gcc_checking_assert (!processing_template_decl);
5813 if (error_operand_p (decl))
5814 return;
5816 gcc_checking_assert (VAR_P (decl));
5818 tree type = TREE_TYPE (decl);
5819 bool complete_p = COMPLETE_TYPE_P (type);
5820 bool aggregate_definition_p
5821 = MAYBE_CLASS_TYPE_P (type) && !DECL_EXTERNAL (decl);
5823 /* If an explicit initializer is present, or if this is a definition
5824 of an aggregate, then we need a complete type at this point.
5825 (Scalars are always complete types, so there is nothing to
5826 check.) This code just sets COMPLETE_P; errors (if necessary)
5827 are issued below. */
5828 if ((initialized || aggregate_definition_p)
5829 && !complete_p
5830 && COMPLETE_TYPE_P (complete_type (type)))
5832 complete_p = true;
5833 /* We will not yet have set TREE_READONLY on DECL if the type
5834 was "const", but incomplete, before this point. But, now, we
5835 have a complete type, so we can try again. */
5836 cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
5839 if (initialized)
5840 /* Is it valid for this decl to have an initializer at all? */
5842 /* Don't allow initializations for incomplete types except for
5843 arrays which might be completed by the initialization. */
5844 if (complete_p)
5845 ; /* A complete type is ok. */
5846 else if (type_uses_auto (type))
5847 ; /* An auto type is ok. */
5848 else if (TREE_CODE (type) != ARRAY_TYPE)
5850 error ("variable %q#D has initializer but incomplete type", decl);
5851 type = TREE_TYPE (decl) = error_mark_node;
5853 else if (!COMPLETE_TYPE_P (complete_type (TREE_TYPE (type))))
5855 if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
5856 error ("elements of array %q#D have incomplete type", decl);
5857 /* else we already gave an error in start_decl. */
5860 else if (aggregate_definition_p && !complete_p)
5862 if (type_uses_auto (type))
5863 gcc_assert (CLASS_PLACEHOLDER_TEMPLATE (type));
5864 else
5866 error ("aggregate %q#D has incomplete type and cannot be defined",
5867 decl);
5868 /* Change the type so that assemble_variable will give
5869 DECL an rtl we can live with: (mem (const_int 0)). */
5870 type = TREE_TYPE (decl) = error_mark_node;
5874 /* Create a new scope to hold this declaration if necessary.
5875 Whether or not a new scope is necessary cannot be determined
5876 until after the type has been completed; if the type is a
5877 specialization of a class template it is not until after
5878 instantiation has occurred that TYPE_HAS_NONTRIVIAL_DESTRUCTOR
5879 will be set correctly. */
5880 maybe_push_cleanup_level (type);
5883 /* Given a parenthesized list of values INIT, create a CONSTRUCTOR to handle
5884 C++20 P0960. TYPE is the type of the object we're initializing. */
5886 tree
5887 do_aggregate_paren_init (tree init, tree type)
5889 tree val = TREE_VALUE (init);
5891 if (TREE_CHAIN (init) == NULL_TREE)
5893 /* If the list has a single element and it's a string literal,
5894 then it's the initializer for the array as a whole. */
5895 if (TREE_CODE (type) == ARRAY_TYPE
5896 && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type)))
5897 && TREE_CODE (tree_strip_any_location_wrapper (val))
5898 == STRING_CST)
5899 return val;
5900 /* Handle non-standard extensions like compound literals. This also
5901 prevents triggering aggregate parenthesized-initialization in
5902 compiler-generated code for =default. */
5903 else if (same_type_ignoring_top_level_qualifiers_p (type,
5904 TREE_TYPE (val)))
5905 return val;
5908 init = build_constructor_from_list (init_list_type_node, init);
5909 CONSTRUCTOR_IS_DIRECT_INIT (init) = true;
5910 CONSTRUCTOR_IS_PAREN_INIT (init) = true;
5911 return init;
5914 /* Handle initialization of references. DECL, TYPE, and INIT have the
5915 same meaning as in cp_finish_decl. *CLEANUP must be NULL on entry,
5916 but will be set to a new CLEANUP_STMT if a temporary is created
5917 that must be destroyed subsequently.
5919 Returns an initializer expression to use to initialize DECL, or
5920 NULL if the initialization can be performed statically.
5922 Quotes on semantics can be found in ARM 8.4.3. */
5924 static tree
5925 grok_reference_init (tree decl, tree type, tree init, int flags)
5927 if (init == NULL_TREE)
5929 if ((DECL_LANG_SPECIFIC (decl) == 0
5930 || DECL_IN_AGGR_P (decl) == 0)
5931 && ! DECL_THIS_EXTERN (decl))
5932 error_at (DECL_SOURCE_LOCATION (decl),
5933 "%qD declared as reference but not initialized", decl);
5934 return NULL_TREE;
5937 tree ttype = TREE_TYPE (type);
5938 if (TREE_CODE (init) == TREE_LIST)
5940 /* This handles (C++20 only) code like
5942 const A& r(1, 2, 3);
5944 where we treat the parenthesized list as a CONSTRUCTOR. */
5945 if (TREE_TYPE (init) == NULL_TREE
5946 && CP_AGGREGATE_TYPE_P (ttype)
5947 && !DECL_DECOMPOSITION_P (decl)
5948 && (cxx_dialect >= cxx20))
5950 /* We don't know yet if we should treat const A& r(1) as
5951 const A& r{1}. */
5952 if (list_length (init) == 1)
5954 flags |= LOOKUP_AGGREGATE_PAREN_INIT;
5955 init = build_x_compound_expr_from_list (init, ELK_INIT,
5956 tf_warning_or_error);
5958 /* If the list had more than one element, the code is ill-formed
5959 pre-C++20, so we can build a constructor right away. */
5960 else
5961 init = do_aggregate_paren_init (init, ttype);
5963 else
5964 init = build_x_compound_expr_from_list (init, ELK_INIT,
5965 tf_warning_or_error);
5968 if (TREE_CODE (ttype) != ARRAY_TYPE
5969 && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
5970 /* Note: default conversion is only called in very special cases. */
5971 init = decay_conversion (init, tf_warning_or_error);
5973 /* check_initializer handles this for non-reference variables, but for
5974 references we need to do it here or the initializer will get the
5975 incomplete array type and confuse later calls to
5976 cp_complete_array_type. */
5977 if (TREE_CODE (ttype) == ARRAY_TYPE
5978 && TYPE_DOMAIN (ttype) == NULL_TREE
5979 && (BRACE_ENCLOSED_INITIALIZER_P (init)
5980 || TREE_CODE (init) == STRING_CST))
5982 cp_complete_array_type (&ttype, init, false);
5983 if (ttype != TREE_TYPE (type))
5984 type = cp_build_reference_type (ttype, TYPE_REF_IS_RVALUE (type));
5987 /* Convert INIT to the reference type TYPE. This may involve the
5988 creation of a temporary, whose lifetime must be the same as that
5989 of the reference. If so, a DECL_EXPR for the temporary will be
5990 added just after the DECL_EXPR for DECL. That's why we don't set
5991 DECL_INITIAL for local references (instead assigning to them
5992 explicitly); we need to allow the temporary to be initialized
5993 first. */
5994 return initialize_reference (type, init, flags,
5995 tf_warning_or_error);
5998 /* Designated initializers in arrays are not supported in GNU C++.
5999 The parser cannot detect this error since it does not know whether
6000 a given brace-enclosed initializer is for a class type or for an
6001 array. This function checks that CE does not use a designated
6002 initializer. If it does, an error is issued. Returns true if CE
6003 is valid, i.e., does not have a designated initializer. */
6005 bool
6006 check_array_designated_initializer (constructor_elt *ce,
6007 unsigned HOST_WIDE_INT index)
6009 /* Designated initializers for array elements are not supported. */
6010 if (ce->index)
6012 /* The parser only allows identifiers as designated
6013 initializers. */
6014 if (ce->index == error_mark_node)
6016 error ("name used in a GNU-style designated "
6017 "initializer for an array");
6018 return false;
6020 else if (identifier_p (ce->index))
6022 error ("name %qD used in a GNU-style designated "
6023 "initializer for an array", ce->index);
6024 return false;
6027 tree ce_index = build_expr_type_conversion (WANT_INT | WANT_ENUM,
6028 ce->index, true);
6029 if (ce_index
6030 && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (ce_index))
6031 && (TREE_CODE (ce_index = fold_non_dependent_expr (ce_index))
6032 == INTEGER_CST))
6034 /* A C99 designator is OK if it matches the current index. */
6035 if (wi::to_wide (ce_index) == index)
6037 ce->index = ce_index;
6038 return true;
6040 else
6041 sorry ("non-trivial designated initializers not supported");
6043 else
6044 error_at (cp_expr_loc_or_input_loc (ce->index),
6045 "C99 designator %qE is not an integral constant-expression",
6046 ce->index);
6048 return false;
6051 return true;
6054 /* When parsing `int a[] = {1, 2};' we don't know the size of the
6055 array until we finish parsing the initializer. If that's the
6056 situation we're in, update DECL accordingly. */
6058 static void
6059 maybe_deduce_size_from_array_init (tree decl, tree init)
6061 tree type = TREE_TYPE (decl);
6063 if (TREE_CODE (type) == ARRAY_TYPE
6064 && TYPE_DOMAIN (type) == NULL_TREE
6065 && TREE_CODE (decl) != TYPE_DECL)
6067 /* do_default is really a C-ism to deal with tentative definitions.
6068 But let's leave it here to ease the eventual merge. */
6069 int do_default = !DECL_EXTERNAL (decl);
6070 tree initializer = init ? init : DECL_INITIAL (decl);
6071 int failure = 0;
6073 /* Check that there are no designated initializers in INIT, as
6074 those are not supported in GNU C++, and as the middle-end
6075 will crash if presented with a non-numeric designated
6076 initializer. */
6077 if (initializer && BRACE_ENCLOSED_INITIALIZER_P (initializer))
6079 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (initializer);
6080 constructor_elt *ce;
6081 HOST_WIDE_INT i;
6082 FOR_EACH_VEC_SAFE_ELT (v, i, ce)
6084 if (instantiation_dependent_expression_p (ce->index))
6085 return;
6086 if (!check_array_designated_initializer (ce, i))
6087 failure = 1;
6088 /* If an un-designated initializer is type-dependent, we can't
6089 check brace elision yet. */
6090 if (ce->index == NULL_TREE
6091 && type_dependent_expression_p (ce->value))
6092 return;
6096 if (failure)
6097 TREE_TYPE (decl) = error_mark_node;
6098 else
6100 failure = cp_complete_array_type (&TREE_TYPE (decl), initializer,
6101 do_default);
6102 if (failure == 1)
6104 error_at (cp_expr_loc_or_loc (initializer,
6105 DECL_SOURCE_LOCATION (decl)),
6106 "initializer fails to determine size of %qD", decl);
6108 else if (failure == 2)
6110 if (do_default)
6112 error_at (DECL_SOURCE_LOCATION (decl),
6113 "array size missing in %qD", decl);
6115 /* If a `static' var's size isn't known, make it extern as
6116 well as static, so it does not get allocated. If it's not
6117 `static', then don't mark it extern; finish_incomplete_decl
6118 will give it a default size and it will get allocated. */
6119 else if (!pedantic && TREE_STATIC (decl) && !TREE_PUBLIC (decl))
6120 DECL_EXTERNAL (decl) = 1;
6122 else if (failure == 3)
6124 error_at (DECL_SOURCE_LOCATION (decl),
6125 "zero-size array %qD", decl);
6129 cp_apply_type_quals_to_decl (cp_type_quals (TREE_TYPE (decl)), decl);
6131 relayout_decl (decl);
6135 /* Set DECL_SIZE, DECL_ALIGN, etc. for DECL (a VAR_DECL), and issue
6136 any appropriate error messages regarding the layout. */
6138 static void
6139 layout_var_decl (tree decl)
6141 tree type;
6143 type = TREE_TYPE (decl);
6144 if (type == error_mark_node)
6145 return;
6147 /* If we haven't already laid out this declaration, do so now.
6148 Note that we must not call complete type for an external object
6149 because it's type might involve templates that we are not
6150 supposed to instantiate yet. (And it's perfectly valid to say
6151 `extern X x' for some incomplete type `X'.) */
6152 if (!DECL_EXTERNAL (decl))
6153 complete_type (type);
6154 if (!DECL_SIZE (decl)
6155 && TREE_TYPE (decl) != error_mark_node
6156 && complete_or_array_type_p (type))
6157 layout_decl (decl, 0);
6159 if (!DECL_EXTERNAL (decl) && DECL_SIZE (decl) == NULL_TREE)
6161 /* An automatic variable with an incomplete type: that is an error.
6162 Don't talk about array types here, since we took care of that
6163 message in grokdeclarator. */
6164 error_at (DECL_SOURCE_LOCATION (decl),
6165 "storage size of %qD isn%'t known", decl);
6166 TREE_TYPE (decl) = error_mark_node;
6168 #if 0
6169 /* Keep this code around in case we later want to control debug info
6170 based on whether a type is "used". (jason 1999-11-11) */
6172 else if (!DECL_EXTERNAL (decl) && MAYBE_CLASS_TYPE_P (ttype))
6173 /* Let debugger know it should output info for this type. */
6174 note_debug_info_needed (ttype);
6176 if (TREE_STATIC (decl) && DECL_CLASS_SCOPE_P (decl))
6177 note_debug_info_needed (DECL_CONTEXT (decl));
6178 #endif
6180 if ((DECL_EXTERNAL (decl) || TREE_STATIC (decl))
6181 && DECL_SIZE (decl) != NULL_TREE
6182 && ! TREE_CONSTANT (DECL_SIZE (decl)))
6184 if (TREE_CODE (DECL_SIZE (decl)) == INTEGER_CST
6185 && !DECL_LOCAL_DECL_P (decl))
6186 constant_expression_warning (DECL_SIZE (decl));
6187 else
6189 error_at (DECL_SOURCE_LOCATION (decl),
6190 "storage size of %qD isn%'t constant", decl);
6191 TREE_TYPE (decl) = error_mark_node;
6192 type = error_mark_node;
6196 /* If the final element initializes a flexible array field, add the size of
6197 that initializer to DECL's size. */
6198 if (type != error_mark_node
6199 && DECL_INITIAL (decl)
6200 && TREE_CODE (DECL_INITIAL (decl)) == CONSTRUCTOR
6201 && !vec_safe_is_empty (CONSTRUCTOR_ELTS (DECL_INITIAL (decl)))
6202 && DECL_SIZE (decl) != NULL_TREE
6203 && TREE_CODE (DECL_SIZE (decl)) == INTEGER_CST
6204 && TYPE_SIZE (type) != NULL_TREE
6205 && TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST
6206 && tree_int_cst_equal (DECL_SIZE (decl), TYPE_SIZE (type)))
6208 constructor_elt &elt = CONSTRUCTOR_ELTS (DECL_INITIAL (decl))->last ();
6209 if (elt.index)
6211 tree itype = TREE_TYPE (elt.index);
6212 tree vtype = TREE_TYPE (elt.value);
6213 if (TREE_CODE (itype) == ARRAY_TYPE
6214 && TYPE_DOMAIN (itype) == NULL
6215 && TREE_CODE (vtype) == ARRAY_TYPE
6216 && COMPLETE_TYPE_P (vtype))
6218 DECL_SIZE (decl)
6219 = size_binop (PLUS_EXPR, DECL_SIZE (decl), TYPE_SIZE (vtype));
6220 DECL_SIZE_UNIT (decl)
6221 = size_binop (PLUS_EXPR, DECL_SIZE_UNIT (decl),
6222 TYPE_SIZE_UNIT (vtype));
6228 /* If a local static variable is declared in an inline function, or if
6229 we have a weak definition, we must endeavor to create only one
6230 instance of the variable at link-time. */
6232 void
6233 maybe_commonize_var (tree decl)
6235 /* Don't mess with __FUNCTION__ and similar. */
6236 if (DECL_ARTIFICIAL (decl))
6237 return;
6239 /* Static data in a function with comdat linkage also has comdat
6240 linkage. */
6241 if ((TREE_STATIC (decl)
6242 && DECL_FUNCTION_SCOPE_P (decl)
6243 && vague_linkage_p (DECL_CONTEXT (decl)))
6244 || (TREE_PUBLIC (decl) && DECL_INLINE_VAR_P (decl)))
6246 if (flag_weak)
6248 /* With weak symbols, we simply make the variable COMDAT;
6249 that will cause copies in multiple translations units to
6250 be merged. */
6251 comdat_linkage (decl);
6253 else
6255 if (DECL_INITIAL (decl) == NULL_TREE
6256 || DECL_INITIAL (decl) == error_mark_node)
6258 /* Without weak symbols, we can use COMMON to merge
6259 uninitialized variables. */
6260 TREE_PUBLIC (decl) = 1;
6261 DECL_COMMON (decl) = 1;
6263 else
6265 /* While for initialized variables, we must use internal
6266 linkage -- which means that multiple copies will not
6267 be merged. */
6268 TREE_PUBLIC (decl) = 0;
6269 DECL_COMMON (decl) = 0;
6270 DECL_INTERFACE_KNOWN (decl) = 1;
6271 const char *msg;
6272 if (DECL_INLINE_VAR_P (decl))
6273 msg = G_("sorry: semantics of inline variable "
6274 "%q#D are wrong (you%'ll wind up with "
6275 "multiple copies)");
6276 else
6277 msg = G_("sorry: semantics of inline function "
6278 "static data %q#D are wrong (you%'ll wind "
6279 "up with multiple copies)");
6280 if (warning_at (DECL_SOURCE_LOCATION (decl), 0,
6281 msg, decl))
6282 inform (DECL_SOURCE_LOCATION (decl),
6283 "you can work around this by removing the initializer");
6289 /* Issue an error message if DECL is an uninitialized const variable.
6290 CONSTEXPR_CONTEXT_P is true when the function is called in a constexpr
6291 context from potential_constant_expression. Returns true if all is well,
6292 false otherwise. */
6294 bool
6295 check_for_uninitialized_const_var (tree decl, bool constexpr_context_p,
6296 tsubst_flags_t complain)
6298 tree type = strip_array_types (TREE_TYPE (decl));
6300 /* ``Unless explicitly declared extern, a const object does not have
6301 external linkage and must be initialized. ($8.4; $12.1)'' ARM
6302 7.1.6 */
6303 if (VAR_P (decl)
6304 && !TYPE_REF_P (type)
6305 && (CP_TYPE_CONST_P (type)
6306 /* C++20 permits trivial default initialization in constexpr
6307 context (P1331R2). */
6308 || (cxx_dialect < cxx20
6309 && (constexpr_context_p
6310 || var_in_constexpr_fn (decl))))
6311 && !DECL_NONTRIVIALLY_INITIALIZED_P (decl))
6313 tree field = default_init_uninitialized_part (type);
6314 if (!field)
6315 return true;
6317 bool show_notes = true;
6319 if (!constexpr_context_p || cxx_dialect >= cxx20)
6321 if (CP_TYPE_CONST_P (type))
6323 if (complain & tf_error)
6324 show_notes = permerror (DECL_SOURCE_LOCATION (decl),
6325 "uninitialized %<const %D%>", decl);
6327 else
6329 if (!is_instantiation_of_constexpr (current_function_decl)
6330 && (complain & tf_error))
6331 error_at (DECL_SOURCE_LOCATION (decl),
6332 "uninitialized variable %qD in %<constexpr%> "
6333 "function", decl);
6334 else
6335 show_notes = false;
6336 cp_function_chain->invalid_constexpr = true;
6339 else if (complain & tf_error)
6340 error_at (DECL_SOURCE_LOCATION (decl),
6341 "uninitialized variable %qD in %<constexpr%> context",
6342 decl);
6344 if (show_notes && CLASS_TYPE_P (type) && (complain & tf_error))
6346 tree defaulted_ctor;
6348 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)),
6349 "%q#T has no user-provided default constructor", type);
6350 defaulted_ctor = in_class_defaulted_default_constructor (type);
6351 if (defaulted_ctor)
6352 inform (DECL_SOURCE_LOCATION (defaulted_ctor),
6353 "constructor is not user-provided because it is "
6354 "explicitly defaulted in the class body");
6355 inform (DECL_SOURCE_LOCATION (field),
6356 "and the implicitly-defined constructor does not "
6357 "initialize %q#D", field);
6360 return false;
6363 return true;
6366 /* Structure holding the current initializer being processed by reshape_init.
6367 CUR is a pointer to the current element being processed, END is a pointer
6368 after the last element present in the initializer. */
6369 struct reshape_iter
6371 constructor_elt *cur;
6372 constructor_elt *end;
6375 static tree reshape_init_r (tree, reshape_iter *, tree, tsubst_flags_t);
6377 /* FIELD is an element of TYPE_FIELDS or NULL. In the former case, the value
6378 returned is the next FIELD_DECL (possibly FIELD itself) that can be
6379 initialized. If there are no more such fields, the return value
6380 will be NULL. */
6382 tree
6383 next_initializable_field (tree field)
6385 while (field
6386 && (TREE_CODE (field) != FIELD_DECL
6387 || DECL_UNNAMED_BIT_FIELD (field)
6388 || (DECL_ARTIFICIAL (field)
6389 /* In C++17, don't skip base class fields. */
6390 && !(cxx_dialect >= cxx17 && DECL_FIELD_IS_BASE (field))
6391 /* Don't skip vptr fields. We might see them when we're
6392 called from reduced_constant_expression_p. */
6393 && !DECL_VIRTUAL_P (field))))
6394 field = DECL_CHAIN (field);
6396 return field;
6399 /* Return true for [dcl.init.list] direct-list-initialization from
6400 single element of enumeration with a fixed underlying type. */
6402 bool
6403 is_direct_enum_init (tree type, tree init)
6405 if (cxx_dialect >= cxx17
6406 && TREE_CODE (type) == ENUMERAL_TYPE
6407 && ENUM_FIXED_UNDERLYING_TYPE_P (type)
6408 && TREE_CODE (init) == CONSTRUCTOR
6409 && CONSTRUCTOR_IS_DIRECT_INIT (init)
6410 && CONSTRUCTOR_NELTS (init) == 1
6411 /* DR 2374: The single element needs to be implicitly
6412 convertible to the underlying type of the enum. */
6413 && can_convert_arg (ENUM_UNDERLYING_TYPE (type),
6414 TREE_TYPE (CONSTRUCTOR_ELT (init, 0)->value),
6415 CONSTRUCTOR_ELT (init, 0)->value,
6416 LOOKUP_IMPLICIT, tf_none))
6417 return true;
6418 return false;
6421 /* Subroutine of reshape_init_array and reshape_init_vector, which does
6422 the actual work. ELT_TYPE is the element type of the array. MAX_INDEX is an
6423 INTEGER_CST representing the size of the array minus one (the maximum index),
6424 or NULL_TREE if the array was declared without specifying the size. D is
6425 the iterator within the constructor. */
6427 static tree
6428 reshape_init_array_1 (tree elt_type, tree max_index, reshape_iter *d,
6429 tree first_initializer_p, tsubst_flags_t complain)
6431 tree new_init;
6432 bool sized_array_p = (max_index && TREE_CONSTANT (max_index));
6433 unsigned HOST_WIDE_INT max_index_cst = 0;
6434 unsigned HOST_WIDE_INT index;
6436 /* The initializer for an array is always a CONSTRUCTOR. If this is the
6437 outermost CONSTRUCTOR and the element type is non-aggregate, we don't need
6438 to build a new one. But don't reuse if not complaining; if this is
6439 tentative, we might also reshape to another type (95319). */
6440 bool reuse = (first_initializer_p
6441 && (complain & tf_error)
6442 && !CP_AGGREGATE_TYPE_P (elt_type)
6443 && !TREE_SIDE_EFFECTS (first_initializer_p));
6444 if (reuse)
6445 new_init = first_initializer_p;
6446 else
6447 new_init = build_constructor (init_list_type_node, NULL);
6449 if (sized_array_p)
6451 /* Minus 1 is used for zero sized arrays. */
6452 if (integer_all_onesp (max_index))
6453 return new_init;
6455 if (tree_fits_uhwi_p (max_index))
6456 max_index_cst = tree_to_uhwi (max_index);
6457 /* sizetype is sign extended, not zero extended. */
6458 else
6459 max_index_cst = tree_to_uhwi (fold_convert (size_type_node, max_index));
6462 /* Loop until there are no more initializers. */
6463 for (index = 0;
6464 d->cur != d->end && (!sized_array_p || index <= max_index_cst);
6465 ++index)
6467 tree elt_init;
6468 constructor_elt *old_cur = d->cur;
6470 check_array_designated_initializer (d->cur, index);
6471 elt_init = reshape_init_r (elt_type, d,
6472 /*first_initializer_p=*/NULL_TREE,
6473 complain);
6474 if (elt_init == error_mark_node)
6475 return error_mark_node;
6476 tree idx = size_int (index);
6477 if (reuse)
6479 old_cur->index = idx;
6480 old_cur->value = elt_init;
6482 else
6483 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init),
6484 idx, elt_init);
6485 if (!TREE_CONSTANT (elt_init))
6486 TREE_CONSTANT (new_init) = false;
6488 /* This can happen with an invalid initializer (c++/54501). */
6489 if (d->cur == old_cur && !sized_array_p)
6490 break;
6493 return new_init;
6496 /* Subroutine of reshape_init_r, processes the initializers for arrays.
6497 Parameters are the same of reshape_init_r. */
6499 static tree
6500 reshape_init_array (tree type, reshape_iter *d, tree first_initializer_p,
6501 tsubst_flags_t complain)
6503 tree max_index = NULL_TREE;
6505 gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
6507 if (TYPE_DOMAIN (type))
6508 max_index = array_type_nelts (type);
6510 return reshape_init_array_1 (TREE_TYPE (type), max_index, d,
6511 first_initializer_p, complain);
6514 /* Subroutine of reshape_init_r, processes the initializers for vectors.
6515 Parameters are the same of reshape_init_r. */
6517 static tree
6518 reshape_init_vector (tree type, reshape_iter *d, tsubst_flags_t complain)
6520 tree max_index = NULL_TREE;
6522 gcc_assert (VECTOR_TYPE_P (type));
6524 if (COMPOUND_LITERAL_P (d->cur->value))
6526 tree value = d->cur->value;
6527 if (!same_type_p (TREE_TYPE (value), type))
6529 if (complain & tf_error)
6530 error ("invalid type %qT as initializer for a vector of type %qT",
6531 TREE_TYPE (d->cur->value), type);
6532 value = error_mark_node;
6534 ++d->cur;
6535 return value;
6538 /* For a vector, we initialize it as an array of the appropriate size. */
6539 if (VECTOR_TYPE_P (type))
6540 max_index = size_int (TYPE_VECTOR_SUBPARTS (type) - 1);
6542 return reshape_init_array_1 (TREE_TYPE (type), max_index, d,
6543 NULL_TREE, complain);
6546 /* Subroutine of reshape_init_r, processes the initializers for classes
6547 or union. Parameters are the same of reshape_init_r. */
6549 static tree
6550 reshape_init_class (tree type, reshape_iter *d, bool first_initializer_p,
6551 tsubst_flags_t complain)
6553 tree field;
6554 tree new_init;
6556 gcc_assert (CLASS_TYPE_P (type));
6558 /* The initializer for a class is always a CONSTRUCTOR. */
6559 new_init = build_constructor (init_list_type_node, NULL);
6561 int binfo_idx = -1;
6562 tree binfo = TYPE_BINFO (type);
6563 tree base_binfo = NULL_TREE;
6564 if (cxx_dialect >= cxx17 && uses_template_parms (type))
6566 /* We get here from maybe_aggr_guide for C++20 class template argument
6567 deduction. In this case we need to look through the binfo because a
6568 template doesn't have base fields. */
6569 binfo_idx = 0;
6570 BINFO_BASE_ITERATE (binfo, binfo_idx, base_binfo);
6572 if (base_binfo)
6573 field = base_binfo;
6574 else
6575 field = next_initializable_field (TYPE_FIELDS (type));
6577 if (!field)
6579 /* [dcl.init.aggr]
6581 An initializer for an aggregate member that is an
6582 empty class shall have the form of an empty
6583 initializer-list {}. */
6584 if (!first_initializer_p)
6586 if (complain & tf_error)
6587 error ("initializer for %qT must be brace-enclosed", type);
6588 return error_mark_node;
6590 return new_init;
6593 /* For C++20 CTAD, handle pack expansions in the base list. */
6594 tree last_was_pack_expansion = NULL_TREE;
6596 /* Loop through the initializable fields, gathering initializers. */
6597 while (d->cur != d->end)
6599 tree field_init;
6600 constructor_elt *old_cur = d->cur;
6602 /* Handle designated initializers, as an extension. */
6603 if (d->cur->index)
6605 if (d->cur->index == error_mark_node)
6606 return error_mark_node;
6608 if (TREE_CODE (d->cur->index) == FIELD_DECL)
6610 /* We already reshaped this. */
6611 if (field != d->cur->index)
6613 if (tree id = DECL_NAME (d->cur->index))
6614 gcc_checking_assert (d->cur->index
6615 == get_class_binding (type, id));
6616 field = d->cur->index;
6619 else if (TREE_CODE (d->cur->index) == IDENTIFIER_NODE)
6620 field = get_class_binding (type, d->cur->index);
6621 else
6623 if (complain & tf_error)
6624 error ("%<[%E] =%> used in a GNU-style designated initializer"
6625 " for class %qT", d->cur->index, type);
6626 return error_mark_node;
6629 if (!field && ANON_AGGR_TYPE_P (type))
6630 /* Apparently the designator isn't for a member of this anonymous
6631 struct, so head back to the enclosing class. */
6632 break;
6634 if (!field || TREE_CODE (field) != FIELD_DECL)
6636 if (complain & tf_error)
6637 error ("%qT has no non-static data member named %qD", type,
6638 d->cur->index);
6639 return error_mark_node;
6642 /* If the element is an anonymous union object and the initializer
6643 list is a designated-initializer-list, the anonymous union object
6644 is initialized by the designated-initializer-list { D }, where D
6645 is the designated-initializer-clause naming a member of the
6646 anonymous union object. */
6647 tree ictx = DECL_CONTEXT (field);
6648 if (!same_type_ignoring_top_level_qualifiers_p (ictx, type))
6650 /* Find the anon aggr that is a direct member of TYPE. */
6651 while (ANON_AGGR_TYPE_P (ictx))
6653 tree cctx = TYPE_CONTEXT (ictx);
6654 if (same_type_ignoring_top_level_qualifiers_p (cctx, type))
6655 goto found;
6656 ictx = cctx;
6659 /* Not found, e.g. FIELD is a member of a base class. */
6660 if (complain & tf_error)
6661 error ("%qD is not a direct member of %qT", field, type);
6662 return error_mark_node;
6664 found:
6665 /* Now find the TYPE member with that anon aggr type. */
6666 tree aafield = TYPE_FIELDS (type);
6667 for (; aafield; aafield = TREE_CHAIN (aafield))
6668 if (TREE_TYPE (aafield) == ictx)
6669 break;
6670 gcc_assert (aafield);
6671 field = aafield;
6675 /* If we processed all the member of the class, we are done. */
6676 if (!field)
6677 break;
6679 last_was_pack_expansion = (PACK_EXPANSION_P (TREE_TYPE (field))
6680 ? field : NULL_TREE);
6681 if (last_was_pack_expansion)
6682 /* Each non-trailing aggregate element that is a pack expansion is
6683 assumed to correspond to no elements of the initializer list. */
6684 goto continue_;
6686 field_init = reshape_init_r (TREE_TYPE (field), d,
6687 /*first_initializer_p=*/NULL_TREE,
6688 complain);
6689 if (field_init == error_mark_node)
6690 return error_mark_node;
6692 if (d->cur == old_cur && d->cur->index)
6694 /* This can happen with an invalid initializer for a flexible
6695 array member (c++/54441). */
6696 if (complain & tf_error)
6697 error ("invalid initializer for %q#D", field);
6698 return error_mark_node;
6701 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init), field, field_init);
6703 /* [dcl.init.aggr]
6705 When a union is initialized with a brace-enclosed
6706 initializer, the braces shall only contain an
6707 initializer for the first member of the union. */
6708 if (TREE_CODE (type) == UNION_TYPE)
6709 break;
6711 continue_:
6712 if (base_binfo)
6714 if (BINFO_BASE_ITERATE (binfo, ++binfo_idx, base_binfo))
6715 field = base_binfo;
6716 else
6717 field = next_initializable_field (TYPE_FIELDS (type));
6719 else
6720 field = next_initializable_field (DECL_CHAIN (field));
6723 /* A trailing aggregate element that is a pack expansion is assumed to
6724 correspond to all remaining elements of the initializer list (if any). */
6725 if (last_was_pack_expansion)
6727 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init),
6728 last_was_pack_expansion, d->cur->value);
6729 while (d->cur != d->end)
6730 d->cur++;
6733 return new_init;
6736 /* Subroutine of reshape_init_r. We're in a context where C99 initializer
6737 designators are not valid; either complain or return true to indicate
6738 that reshape_init_r should return error_mark_node. */
6740 static bool
6741 has_designator_problem (reshape_iter *d, tsubst_flags_t complain)
6743 if (d->cur->index)
6745 if (complain & tf_error)
6746 error_at (cp_expr_loc_or_input_loc (d->cur->index),
6747 "C99 designator %qE outside aggregate initializer",
6748 d->cur->index);
6749 else
6750 return true;
6752 return false;
6755 /* Subroutine of reshape_init, which processes a single initializer (part of
6756 a CONSTRUCTOR). TYPE is the type of the variable being initialized, D is the
6757 iterator within the CONSTRUCTOR which points to the initializer to process.
6758 If this is the first initializer of the outermost CONSTRUCTOR node,
6759 FIRST_INITIALIZER_P is that CONSTRUCTOR; otherwise, it is NULL_TREE. */
6761 static tree
6762 reshape_init_r (tree type, reshape_iter *d, tree first_initializer_p,
6763 tsubst_flags_t complain)
6765 tree init = d->cur->value;
6767 if (error_operand_p (init))
6768 return error_mark_node;
6770 if (first_initializer_p && !CP_AGGREGATE_TYPE_P (type)
6771 && has_designator_problem (d, complain))
6772 return error_mark_node;
6774 tree stripped_init = tree_strip_any_location_wrapper (init);
6776 if (TREE_CODE (type) == COMPLEX_TYPE)
6778 /* A complex type can be initialized from one or two initializers,
6779 but braces are not elided. */
6780 d->cur++;
6781 if (BRACE_ENCLOSED_INITIALIZER_P (stripped_init))
6783 if (CONSTRUCTOR_NELTS (stripped_init) > 2)
6785 if (complain & tf_error)
6786 error ("too many initializers for %qT", type);
6787 else
6788 return error_mark_node;
6791 else if (first_initializer_p && d->cur != d->end)
6793 vec<constructor_elt, va_gc> *v = 0;
6794 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, init);
6795 CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, d->cur->value);
6796 if (has_designator_problem (d, complain))
6797 return error_mark_node;
6798 d->cur++;
6799 init = build_constructor (init_list_type_node, v);
6801 return init;
6804 /* A non-aggregate type is always initialized with a single
6805 initializer. */
6806 if (!CP_AGGREGATE_TYPE_P (type)
6807 /* As is an array with dependent bound, which we can see
6808 during C++20 aggregate CTAD. */
6809 || (cxx_dialect >= cxx20
6810 && TREE_CODE (type) == ARRAY_TYPE
6811 && uses_template_parms (TYPE_DOMAIN (type))))
6813 /* It is invalid to initialize a non-aggregate type with a
6814 brace-enclosed initializer before C++0x.
6815 We need to check for BRACE_ENCLOSED_INITIALIZER_P here because
6816 of g++.old-deja/g++.mike/p7626.C: a pointer-to-member constant is
6817 a CONSTRUCTOR (with a record type). */
6818 if (TREE_CODE (stripped_init) == CONSTRUCTOR
6819 /* Don't complain about a capture-init. */
6820 && !CONSTRUCTOR_IS_DIRECT_INIT (stripped_init)
6821 && BRACE_ENCLOSED_INITIALIZER_P (stripped_init)) /* p7626.C */
6823 if (SCALAR_TYPE_P (type))
6825 if (cxx_dialect < cxx11)
6827 if (complain & tf_error)
6828 error ("braces around scalar initializer for type %qT",
6829 type);
6830 init = error_mark_node;
6832 else if (first_initializer_p
6833 || (CONSTRUCTOR_NELTS (stripped_init) > 0
6834 && (BRACE_ENCLOSED_INITIALIZER_P
6835 (CONSTRUCTOR_ELT (stripped_init,0)->value))))
6837 if (complain & tf_error)
6838 error ("too many braces around scalar initializer "
6839 "for type %qT", type);
6840 init = error_mark_node;
6843 else
6844 maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
6847 d->cur++;
6848 return init;
6851 /* "If T is a class type and the initializer list has a single element of
6852 type cv U, where U is T or a class derived from T, the object is
6853 initialized from that element." Even if T is an aggregate. */
6854 if (cxx_dialect >= cxx11 && (CLASS_TYPE_P (type) || VECTOR_TYPE_P (type))
6855 && first_initializer_p
6856 /* But not if it's a designated init. */
6857 && !d->cur->index
6858 && d->end - d->cur == 1
6859 && reference_related_p (type, TREE_TYPE (init)))
6861 d->cur++;
6862 return init;
6865 /* [dcl.init.aggr]
6867 All implicit type conversions (clause _conv_) are considered when
6868 initializing the aggregate member with an initializer from an
6869 initializer-list. If the initializer can initialize a member,
6870 the member is initialized. Otherwise, if the member is itself a
6871 non-empty subaggregate, brace elision is assumed and the
6872 initializer is considered for the initialization of the first
6873 member of the subaggregate. */
6874 if ((TREE_CODE (init) != CONSTRUCTOR || COMPOUND_LITERAL_P (init))
6875 /* But don't try this for the first initializer, since that would be
6876 looking through the outermost braces; A a2 = { a1 }; is not a
6877 valid aggregate initialization. */
6878 && !first_initializer_p
6879 && (same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (init))
6880 || can_convert_arg (type, TREE_TYPE (init), init, LOOKUP_NORMAL,
6881 complain)))
6883 d->cur++;
6884 return init;
6887 /* [dcl.init.string]
6889 A char array (whether plain char, signed char, or unsigned char)
6890 can be initialized by a string-literal (optionally enclosed in
6891 braces); a wchar_t array can be initialized by a wide
6892 string-literal (optionally enclosed in braces). */
6893 if (TREE_CODE (type) == ARRAY_TYPE
6894 && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type))))
6896 tree str_init = init;
6897 tree stripped_str_init = stripped_init;
6898 reshape_iter stripd = {};
6900 /* Strip one level of braces if and only if they enclose a single
6901 element (as allowed by [dcl.init.string]). */
6902 if (!first_initializer_p
6903 && TREE_CODE (stripped_str_init) == CONSTRUCTOR
6904 && CONSTRUCTOR_NELTS (stripped_str_init) == 1)
6906 stripd.cur = CONSTRUCTOR_ELT (stripped_str_init, 0);
6907 str_init = stripd.cur->value;
6908 stripped_str_init = tree_strip_any_location_wrapper (str_init);
6911 /* If it's a string literal, then it's the initializer for the array
6912 as a whole. Otherwise, continue with normal initialization for
6913 array types (one value per array element). */
6914 if (TREE_CODE (stripped_str_init) == STRING_CST)
6916 if ((first_initializer_p && has_designator_problem (d, complain))
6917 || (stripd.cur && has_designator_problem (&stripd, complain)))
6918 return error_mark_node;
6919 d->cur++;
6920 return str_init;
6924 /* The following cases are about aggregates. If we are not within a full
6925 initializer already, and there is not a CONSTRUCTOR, it means that there
6926 is a missing set of braces (that is, we are processing the case for
6927 which reshape_init exists). */
6928 bool braces_elided_p = false;
6929 if (!first_initializer_p)
6931 if (TREE_CODE (stripped_init) == CONSTRUCTOR)
6933 tree init_type = TREE_TYPE (init);
6934 if (init_type && TYPE_PTRMEMFUNC_P (init_type))
6935 /* There is no need to call reshape_init for pointer-to-member
6936 function initializers, as they are always constructed correctly
6937 by the front end. Here we have e.g. {.__pfn=0B, .__delta=0},
6938 which is missing outermost braces. We should warn below, and
6939 one of the routines below will wrap it in additional { }. */;
6940 /* For a nested compound literal, proceed to specialized routines,
6941 to handle initialization of arrays and similar. */
6942 else if (COMPOUND_LITERAL_P (stripped_init))
6943 gcc_assert (!BRACE_ENCLOSED_INITIALIZER_P (stripped_init));
6944 /* A CONSTRUCTOR of the target's type is a previously
6945 digested initializer. */
6946 else if (same_type_ignoring_top_level_qualifiers_p (type, init_type))
6948 ++d->cur;
6949 return init;
6951 else
6953 /* Something that hasn't been reshaped yet. */
6954 ++d->cur;
6955 gcc_assert (BRACE_ENCLOSED_INITIALIZER_P (stripped_init));
6956 return reshape_init (type, init, complain);
6960 if (complain & tf_warning)
6961 warning (OPT_Wmissing_braces,
6962 "missing braces around initializer for %qT",
6963 type);
6964 braces_elided_p = true;
6967 /* Dispatch to specialized routines. */
6968 tree new_init;
6969 if (CLASS_TYPE_P (type))
6970 new_init = reshape_init_class (type, d, first_initializer_p, complain);
6971 else if (TREE_CODE (type) == ARRAY_TYPE)
6972 new_init = reshape_init_array (type, d, first_initializer_p, complain);
6973 else if (VECTOR_TYPE_P (type))
6974 new_init = reshape_init_vector (type, d, complain);
6975 else
6976 gcc_unreachable();
6978 if (braces_elided_p
6979 && TREE_CODE (new_init) == CONSTRUCTOR)
6980 CONSTRUCTOR_BRACES_ELIDED_P (new_init) = true;
6982 return new_init;
6985 /* Undo the brace-elision allowed by [dcl.init.aggr] in a
6986 brace-enclosed aggregate initializer.
6988 INIT is the CONSTRUCTOR containing the list of initializers describing
6989 a brace-enclosed initializer for an entity of the indicated aggregate TYPE.
6990 It may not presently match the shape of the TYPE; for example:
6992 struct S { int a; int b; };
6993 struct S a[] = { 1, 2, 3, 4 };
6995 Here INIT will hold a vector of four elements, rather than a
6996 vector of two elements, each itself a vector of two elements. This
6997 routine transforms INIT from the former form into the latter. The
6998 revised CONSTRUCTOR node is returned. */
7000 tree
7001 reshape_init (tree type, tree init, tsubst_flags_t complain)
7003 vec<constructor_elt, va_gc> *v;
7004 reshape_iter d;
7005 tree new_init;
7007 gcc_assert (BRACE_ENCLOSED_INITIALIZER_P (init));
7009 v = CONSTRUCTOR_ELTS (init);
7011 /* An empty constructor does not need reshaping, and it is always a valid
7012 initializer. */
7013 if (vec_safe_is_empty (v))
7014 return init;
7016 /* Brace elision is not performed for a CONSTRUCTOR representing
7017 parenthesized aggregate initialization. */
7018 if (CONSTRUCTOR_IS_PAREN_INIT (init))
7020 tree elt = (*v)[0].value;
7021 /* If we're initializing a char array from a string-literal that is
7022 enclosed in braces, unwrap it here. */
7023 if (TREE_CODE (type) == ARRAY_TYPE
7024 && vec_safe_length (v) == 1
7025 && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type)))
7026 && TREE_CODE (tree_strip_any_location_wrapper (elt)) == STRING_CST)
7027 return elt;
7028 return init;
7031 /* Handle [dcl.init.list] direct-list-initialization from
7032 single element of enumeration with a fixed underlying type. */
7033 if (is_direct_enum_init (type, init))
7035 tree elt = CONSTRUCTOR_ELT (init, 0)->value;
7036 type = cv_unqualified (type);
7037 if (check_narrowing (ENUM_UNDERLYING_TYPE (type), elt, complain))
7039 warning_sentinel w (warn_useless_cast);
7040 warning_sentinel w2 (warn_ignored_qualifiers);
7041 return cp_build_c_cast (input_location, type, elt,
7042 tf_warning_or_error);
7044 else
7045 return error_mark_node;
7048 /* Recurse on this CONSTRUCTOR. */
7049 d.cur = &(*v)[0];
7050 d.end = d.cur + v->length ();
7052 new_init = reshape_init_r (type, &d, init, complain);
7053 if (new_init == error_mark_node)
7054 return error_mark_node;
7056 /* Make sure all the element of the constructor were used. Otherwise,
7057 issue an error about exceeding initializers. */
7058 if (d.cur != d.end)
7060 if (complain & tf_error)
7061 error ("too many initializers for %qT", type);
7062 return error_mark_node;
7065 if (CONSTRUCTOR_IS_DIRECT_INIT (init)
7066 && BRACE_ENCLOSED_INITIALIZER_P (new_init))
7067 CONSTRUCTOR_IS_DIRECT_INIT (new_init) = true;
7068 if (CONSTRUCTOR_IS_DESIGNATED_INIT (init)
7069 && BRACE_ENCLOSED_INITIALIZER_P (new_init))
7070 CONSTRUCTOR_IS_DESIGNATED_INIT (new_init) = true;
7072 return new_init;
7075 /* Verify array initializer. Returns true if errors have been reported. */
7077 bool
7078 check_array_initializer (tree decl, tree type, tree init)
7080 tree element_type = TREE_TYPE (type);
7082 /* Structured binding when initialized with an array type needs
7083 to have complete type. */
7084 if (decl
7085 && DECL_DECOMPOSITION_P (decl)
7086 && !DECL_DECOMP_BASE (decl)
7087 && !COMPLETE_TYPE_P (type))
7089 error_at (DECL_SOURCE_LOCATION (decl),
7090 "structured binding has incomplete type %qT", type);
7091 TREE_TYPE (decl) = error_mark_node;
7092 return true;
7095 /* The array type itself need not be complete, because the
7096 initializer may tell us how many elements are in the array.
7097 But, the elements of the array must be complete. */
7098 if (!COMPLETE_TYPE_P (complete_type (element_type)))
7100 if (decl)
7101 error_at (DECL_SOURCE_LOCATION (decl),
7102 "elements of array %q#D have incomplete type", decl);
7103 else
7104 error ("elements of array %q#T have incomplete type", type);
7105 return true;
7108 location_t loc = (decl ? location_of (decl) : input_location);
7109 if (!verify_type_context (loc, TCTX_ARRAY_ELEMENT, element_type))
7110 return true;
7112 /* A compound literal can't have variable size. */
7113 if (init && !decl
7114 && ((COMPLETE_TYPE_P (type) && !TREE_CONSTANT (TYPE_SIZE (type)))
7115 || !TREE_CONSTANT (TYPE_SIZE (element_type))))
7117 error ("variable-sized compound literal");
7118 return true;
7120 return false;
7123 /* Subroutine of check_initializer; args are passed down from that function.
7124 Set stmts_are_full_exprs_p to 1 across a call to build_aggr_init. */
7126 static tree
7127 build_aggr_init_full_exprs (tree decl, tree init, int flags)
7130 gcc_assert (stmts_are_full_exprs_p ());
7131 return build_aggr_init (decl, init, flags, tf_warning_or_error);
7134 /* Verify INIT (the initializer for DECL), and record the
7135 initialization in DECL_INITIAL, if appropriate. CLEANUP is as for
7136 grok_reference_init.
7138 If the return value is non-NULL, it is an expression that must be
7139 evaluated dynamically to initialize DECL. */
7141 static tree
7142 check_initializer (tree decl, tree init, int flags, vec<tree, va_gc> **cleanups)
7144 tree type;
7145 tree init_code = NULL;
7146 tree core_type;
7148 /* Things that are going to be initialized need to have complete
7149 type. */
7150 TREE_TYPE (decl) = type = complete_type (TREE_TYPE (decl));
7152 if (DECL_HAS_VALUE_EXPR_P (decl))
7154 /* A variable with DECL_HAS_VALUE_EXPR_P set is just a placeholder,
7155 it doesn't have storage to be initialized. */
7156 gcc_assert (init == NULL_TREE);
7157 return NULL_TREE;
7160 if (type == error_mark_node)
7161 /* We will have already complained. */
7162 return NULL_TREE;
7164 if (TREE_CODE (type) == ARRAY_TYPE)
7166 if (check_array_initializer (decl, type, init))
7167 return NULL_TREE;
7169 else if (!COMPLETE_TYPE_P (type))
7171 error_at (DECL_SOURCE_LOCATION (decl),
7172 "%q#D has incomplete type", decl);
7173 TREE_TYPE (decl) = error_mark_node;
7174 return NULL_TREE;
7176 else
7177 /* There is no way to make a variable-sized class type in GNU C++. */
7178 gcc_assert (TREE_CONSTANT (TYPE_SIZE (type)));
7180 if (init && BRACE_ENCLOSED_INITIALIZER_P (init))
7182 int init_len = CONSTRUCTOR_NELTS (init);
7183 if (SCALAR_TYPE_P (type))
7185 if (init_len == 0)
7187 maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
7188 init = build_zero_init (type, NULL_TREE, false);
7190 else if (init_len != 1 && TREE_CODE (type) != COMPLEX_TYPE)
7192 error_at (cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (decl)),
7193 "scalar object %qD requires one element in "
7194 "initializer", decl);
7195 TREE_TYPE (decl) = error_mark_node;
7196 return NULL_TREE;
7201 if (TREE_CODE (decl) == CONST_DECL)
7203 gcc_assert (!TYPE_REF_P (type));
7205 DECL_INITIAL (decl) = init;
7207 gcc_assert (init != NULL_TREE);
7208 init = NULL_TREE;
7210 else if (!init && DECL_REALLY_EXTERN (decl))
7212 else if (init || type_build_ctor_call (type)
7213 || TYPE_REF_P (type))
7215 if (TYPE_REF_P (type))
7217 init = grok_reference_init (decl, type, init, flags);
7218 flags |= LOOKUP_ALREADY_DIGESTED;
7220 else if (!init)
7221 check_for_uninitialized_const_var (decl, /*constexpr_context_p=*/false,
7222 tf_warning_or_error);
7223 /* Do not reshape constructors of vectors (they don't need to be
7224 reshaped. */
7225 else if (BRACE_ENCLOSED_INITIALIZER_P (init))
7227 if (is_std_init_list (type))
7229 init = perform_implicit_conversion (type, init,
7230 tf_warning_or_error);
7231 flags |= LOOKUP_ALREADY_DIGESTED;
7233 else if (TYPE_NON_AGGREGATE_CLASS (type))
7235 /* Don't reshape if the class has constructors. */
7236 if (cxx_dialect == cxx98)
7237 error_at (cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (decl)),
7238 "in C++98 %qD must be initialized by "
7239 "constructor, not by %<{...}%>",
7240 decl);
7242 else if (VECTOR_TYPE_P (type) && TYPE_VECTOR_OPAQUE (type))
7244 error ("opaque vector types cannot be initialized");
7245 init = error_mark_node;
7247 else
7249 init = reshape_init (type, init, tf_warning_or_error);
7250 flags |= LOOKUP_NO_NARROWING;
7253 /* [dcl.init] "Otherwise, if the destination type is an array, the object
7254 is initialized as follows..." So handle things like
7256 int a[](1, 2, 3);
7258 which is permitted in C++20 by P0960. */
7259 else if (TREE_CODE (init) == TREE_LIST
7260 && TREE_TYPE (init) == NULL_TREE
7261 && TREE_CODE (type) == ARRAY_TYPE
7262 && !DECL_DECOMPOSITION_P (decl)
7263 && (cxx_dialect >= cxx20))
7264 init = do_aggregate_paren_init (init, type);
7265 else if (TREE_CODE (init) == TREE_LIST
7266 && TREE_TYPE (init) != unknown_type_node
7267 && !MAYBE_CLASS_TYPE_P (type))
7269 gcc_assert (TREE_CODE (decl) != RESULT_DECL);
7271 /* We get here with code like `int a (2);' */
7272 init = build_x_compound_expr_from_list (init, ELK_INIT,
7273 tf_warning_or_error);
7276 /* If DECL has an array type without a specific bound, deduce the
7277 array size from the initializer. */
7278 maybe_deduce_size_from_array_init (decl, init);
7279 type = TREE_TYPE (decl);
7280 if (type == error_mark_node)
7281 return NULL_TREE;
7283 if (((type_build_ctor_call (type) || CLASS_TYPE_P (type))
7284 && !(flags & LOOKUP_ALREADY_DIGESTED)
7285 && !(init && BRACE_ENCLOSED_INITIALIZER_P (init)
7286 && CP_AGGREGATE_TYPE_P (type)
7287 && (CLASS_TYPE_P (type)
7288 || !TYPE_NEEDS_CONSTRUCTING (type)
7289 || type_has_extended_temps (type))))
7290 || (DECL_DECOMPOSITION_P (decl) && TREE_CODE (type) == ARRAY_TYPE))
7292 init_code = build_aggr_init_full_exprs (decl, init, flags);
7294 /* A constructor call is a non-trivial initializer even if
7295 it isn't explicitly written. */
7296 if (TREE_SIDE_EFFECTS (init_code))
7297 DECL_NONTRIVIALLY_INITIALIZED_P (decl) = true;
7299 /* If this is a constexpr initializer, expand_default_init will
7300 have returned an INIT_EXPR rather than a CALL_EXPR. In that
7301 case, pull the initializer back out and pass it down into
7302 store_init_value. */
7303 while (true)
7305 if (TREE_CODE (init_code) == EXPR_STMT
7306 || TREE_CODE (init_code) == STMT_EXPR
7307 || TREE_CODE (init_code) == CONVERT_EXPR)
7308 init_code = TREE_OPERAND (init_code, 0);
7309 else if (TREE_CODE (init_code) == BIND_EXPR)
7310 init_code = BIND_EXPR_BODY (init_code);
7311 else
7312 break;
7314 if (TREE_CODE (init_code) == INIT_EXPR)
7316 /* In C++20, the call to build_aggr_init could have created
7317 an INIT_EXPR with a CONSTRUCTOR as the RHS to handle
7318 A(1, 2). */
7319 tree rhs = TREE_OPERAND (init_code, 1);
7320 if (processing_template_decl && TREE_CODE (rhs) == TARGET_EXPR)
7321 /* Avoid leaking TARGET_EXPR into template trees. */
7322 rhs = build_implicit_conv_flags (type, init, flags);
7323 init = rhs;
7325 init_code = NULL_TREE;
7326 /* Don't call digest_init; it's unnecessary and will complain
7327 about aggregate initialization of non-aggregate classes. */
7328 flags |= LOOKUP_ALREADY_DIGESTED;
7330 else if (DECL_DECLARED_CONSTEXPR_P (decl)
7331 || DECL_DECLARED_CONSTINIT_P (decl))
7333 /* Declared constexpr or constinit, but no suitable initializer;
7334 massage init appropriately so we can pass it into
7335 store_init_value for the error. */
7336 if (CLASS_TYPE_P (type)
7337 && (!init || TREE_CODE (init) == TREE_LIST))
7339 init = build_functional_cast (input_location, type,
7340 init, tf_none);
7341 if (TREE_CODE (init) == TARGET_EXPR)
7342 TARGET_EXPR_DIRECT_INIT_P (init) = true;
7344 init_code = NULL_TREE;
7346 else
7347 init = NULL_TREE;
7350 if (init && TREE_CODE (init) != TREE_VEC)
7352 init_code = store_init_value (decl, init, cleanups, flags);
7354 if (DECL_INITIAL (decl)
7355 && TREE_CODE (DECL_INITIAL (decl)) == CONSTRUCTOR
7356 && !vec_safe_is_empty (CONSTRUCTOR_ELTS (DECL_INITIAL (decl))))
7358 tree elt = CONSTRUCTOR_ELTS (DECL_INITIAL (decl))->last ().value;
7359 if (TREE_CODE (TREE_TYPE (elt)) == ARRAY_TYPE
7360 && TYPE_SIZE (TREE_TYPE (elt)) == NULL_TREE)
7361 cp_complete_array_type (&TREE_TYPE (elt), elt, false);
7364 if (pedantic && TREE_CODE (type) == ARRAY_TYPE
7365 && DECL_INITIAL (decl)
7366 && TREE_CODE (DECL_INITIAL (decl)) == STRING_CST
7367 && PAREN_STRING_LITERAL_P (DECL_INITIAL (decl)))
7368 warning_at (cp_expr_loc_or_loc (DECL_INITIAL (decl),
7369 DECL_SOURCE_LOCATION (decl)),
7370 0, "array %qD initialized by parenthesized "
7371 "string literal %qE",
7372 decl, DECL_INITIAL (decl));
7373 init = NULL_TREE;
7376 else
7378 if (CLASS_TYPE_P (core_type = strip_array_types (type))
7379 && (CLASSTYPE_READONLY_FIELDS_NEED_INIT (core_type)
7380 || CLASSTYPE_REF_FIELDS_NEED_INIT (core_type)))
7381 diagnose_uninitialized_cst_or_ref_member (core_type, /*using_new=*/false,
7382 /*complain=*/true);
7384 check_for_uninitialized_const_var (decl, /*constexpr_context_p=*/false,
7385 tf_warning_or_error);
7388 if (init && init != error_mark_node)
7389 init_code = build2 (INIT_EXPR, type, decl, init);
7391 if (init_code)
7393 /* We might have set these in cp_finish_decl. */
7394 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = false;
7395 TREE_CONSTANT (decl) = false;
7398 if (init_code
7399 && DECL_IN_AGGR_P (decl)
7400 && DECL_INITIALIZED_IN_CLASS_P (decl))
7402 static int explained = 0;
7404 if (cxx_dialect < cxx11)
7405 error ("initializer invalid for static member with constructor");
7406 else if (cxx_dialect < cxx17)
7407 error ("non-constant in-class initialization invalid for static "
7408 "member %qD", decl);
7409 else
7410 error ("non-constant in-class initialization invalid for non-inline "
7411 "static member %qD", decl);
7412 if (!explained)
7414 inform (input_location,
7415 "(an out of class initialization is required)");
7416 explained = 1;
7418 return NULL_TREE;
7421 return init_code;
7424 /* If DECL is not a local variable, give it RTL. */
7426 static void
7427 make_rtl_for_nonlocal_decl (tree decl, tree init, const char* asmspec)
7429 int toplev = toplevel_bindings_p ();
7430 int defer_p;
7432 /* Set the DECL_ASSEMBLER_NAME for the object. */
7433 if (asmspec)
7435 /* The `register' keyword, when used together with an
7436 asm-specification, indicates that the variable should be
7437 placed in a particular register. */
7438 if (VAR_P (decl) && DECL_REGISTER (decl))
7440 set_user_assembler_name (decl, asmspec);
7441 DECL_HARD_REGISTER (decl) = 1;
7443 else
7445 if (TREE_CODE (decl) == FUNCTION_DECL
7446 && fndecl_built_in_p (decl, BUILT_IN_NORMAL))
7447 set_builtin_user_assembler_name (decl, asmspec);
7448 set_user_assembler_name (decl, asmspec);
7449 if (DECL_LOCAL_DECL_P (decl))
7450 if (auto ns_decl = DECL_LOCAL_DECL_ALIAS (decl))
7451 /* We have to propagate the name to the ns-alias.
7452 This is horrible, as we're affecting a
7453 possibly-shared decl. Again, a one-true-decl
7454 model breaks down. */
7455 if (ns_decl != error_mark_node)
7456 set_user_assembler_name (ns_decl, asmspec);
7460 /* Handle non-variables up front. */
7461 if (!VAR_P (decl))
7463 rest_of_decl_compilation (decl, toplev, at_eof);
7464 return;
7467 /* If we see a class member here, it should be a static data
7468 member. */
7469 if (DECL_LANG_SPECIFIC (decl) && DECL_IN_AGGR_P (decl))
7471 gcc_assert (TREE_STATIC (decl));
7472 /* An in-class declaration of a static data member should be
7473 external; it is only a declaration, and not a definition. */
7474 if (init == NULL_TREE)
7475 gcc_assert (DECL_EXTERNAL (decl)
7476 || !TREE_PUBLIC (decl));
7479 /* We don't create any RTL for local variables. */
7480 if (DECL_FUNCTION_SCOPE_P (decl) && !TREE_STATIC (decl))
7481 return;
7483 /* We defer emission of local statics until the corresponding
7484 DECL_EXPR is expanded. But with constexpr its function might never
7485 be expanded, so go ahead and tell cgraph about the variable now. */
7486 defer_p = ((DECL_FUNCTION_SCOPE_P (decl)
7487 && !var_in_maybe_constexpr_fn (decl))
7488 || DECL_VIRTUAL_P (decl));
7490 /* Defer template instantiations. */
7491 if (DECL_LANG_SPECIFIC (decl)
7492 && DECL_IMPLICIT_INSTANTIATION (decl))
7493 defer_p = 1;
7495 /* If we're not deferring, go ahead and assemble the variable. */
7496 if (!defer_p)
7497 rest_of_decl_compilation (decl, toplev, at_eof);
7500 /* walk_tree helper for wrap_temporary_cleanups, below. */
7502 static tree
7503 wrap_cleanups_r (tree *stmt_p, int *walk_subtrees, void *data)
7505 /* Stop at types or full-expression boundaries. */
7506 if (TYPE_P (*stmt_p)
7507 || TREE_CODE (*stmt_p) == CLEANUP_POINT_EXPR)
7509 *walk_subtrees = 0;
7510 return NULL_TREE;
7513 if (TREE_CODE (*stmt_p) == TARGET_EXPR)
7515 tree guard = (tree)data;
7516 tree tcleanup = TARGET_EXPR_CLEANUP (*stmt_p);
7518 if (tcleanup && !CLEANUP_EH_ONLY (*stmt_p)
7519 && !expr_noexcept_p (tcleanup, tf_none))
7521 tcleanup = build2 (TRY_CATCH_EXPR, void_type_node, tcleanup, guard);
7522 /* Tell honor_protect_cleanup_actions to handle this as a separate
7523 cleanup. */
7524 TRY_CATCH_IS_CLEANUP (tcleanup) = 1;
7525 TARGET_EXPR_CLEANUP (*stmt_p) = tcleanup;
7529 return NULL_TREE;
7532 /* We're initializing a local variable which has a cleanup GUARD. If there
7533 are any temporaries used in the initializer INIT of this variable, we
7534 need to wrap their cleanups with TRY_CATCH_EXPR (, GUARD) so that the
7535 variable will be cleaned up properly if one of them throws.
7537 Unfortunately, there's no way to express this properly in terms of
7538 nesting, as the regions for the temporaries overlap the region for the
7539 variable itself; if there are two temporaries, the variable needs to be
7540 the first thing destroyed if either of them throws. However, we only
7541 want to run the variable's cleanup if it actually got constructed. So
7542 we need to guard the temporary cleanups with the variable's cleanup if
7543 they are run on the normal path, but not if they are run on the
7544 exceptional path. We implement this by telling
7545 honor_protect_cleanup_actions to strip the variable cleanup from the
7546 exceptional path.
7548 Another approach could be to make the variable cleanup region enclose
7549 initialization, but depend on a flag to indicate that the variable is
7550 initialized; that's effectively what we do for arrays. But the current
7551 approach works fine for non-arrays, and has no code overhead in the usual
7552 case where the temporary destructors are noexcept. */
7554 static void
7555 wrap_temporary_cleanups (tree init, tree guard)
7557 if (TREE_CODE (guard) == BIND_EXPR)
7559 /* An array cleanup region already encloses any temporary cleanups,
7560 don't wrap it around them again. */
7561 gcc_checking_assert (BIND_EXPR_VEC_DTOR (guard));
7562 return;
7564 cp_walk_tree_without_duplicates (&init, wrap_cleanups_r, (void *)guard);
7567 /* Generate code to initialize DECL (a local variable). */
7569 static void
7570 initialize_local_var (tree decl, tree init)
7572 tree type = TREE_TYPE (decl);
7573 tree cleanup;
7574 int already_used;
7576 gcc_assert (VAR_P (decl)
7577 || TREE_CODE (decl) == RESULT_DECL);
7578 gcc_assert (!TREE_STATIC (decl));
7580 if (DECL_SIZE (decl) == NULL_TREE)
7582 /* If we used it already as memory, it must stay in memory. */
7583 DECL_INITIAL (decl) = NULL_TREE;
7584 TREE_ADDRESSABLE (decl) = TREE_USED (decl);
7585 return;
7588 if (type == error_mark_node)
7589 return;
7591 /* Compute and store the initial value. */
7592 already_used = TREE_USED (decl) || TREE_USED (type);
7593 if (TREE_USED (type))
7594 DECL_READ_P (decl) = 1;
7596 /* Generate a cleanup, if necessary. */
7597 cleanup = cxx_maybe_build_cleanup (decl, tf_warning_or_error);
7599 /* Perform the initialization. */
7600 if (init)
7602 tree rinit = (TREE_CODE (init) == INIT_EXPR
7603 ? TREE_OPERAND (init, 1) : NULL_TREE);
7604 if (rinit && !TREE_SIDE_EFFECTS (rinit)
7605 && TREE_OPERAND (init, 0) == decl)
7607 /* Stick simple initializers in DECL_INITIAL so that
7608 -Wno-init-self works (c++/34772). */
7609 DECL_INITIAL (decl) = rinit;
7611 if (warn_init_self && TYPE_REF_P (type))
7613 STRIP_NOPS (rinit);
7614 if (rinit == decl)
7615 warning_at (DECL_SOURCE_LOCATION (decl),
7616 OPT_Winit_self,
7617 "reference %qD is initialized with itself", decl);
7620 else
7622 int saved_stmts_are_full_exprs_p;
7624 /* If we're only initializing a single object, guard the
7625 destructors of any temporaries used in its initializer with
7626 its destructor. */
7627 if (cleanup)
7628 wrap_temporary_cleanups (init, cleanup);
7630 gcc_assert (building_stmt_list_p ());
7631 saved_stmts_are_full_exprs_p = stmts_are_full_exprs_p ();
7632 current_stmt_tree ()->stmts_are_full_exprs_p = 1;
7633 finish_expr_stmt (init);
7634 current_stmt_tree ()->stmts_are_full_exprs_p =
7635 saved_stmts_are_full_exprs_p;
7639 /* Set this to 0 so we can tell whether an aggregate which was
7640 initialized was ever used. Don't do this if it has a
7641 destructor, so we don't complain about the 'resource
7642 allocation is initialization' idiom. Now set
7643 attribute((unused)) on types so decls of that type will be
7644 marked used. (see TREE_USED, above.) */
7645 if (TYPE_NEEDS_CONSTRUCTING (type)
7646 && ! already_used
7647 && TYPE_HAS_TRIVIAL_DESTRUCTOR (type)
7648 && DECL_NAME (decl))
7649 TREE_USED (decl) = 0;
7650 else if (already_used)
7651 TREE_USED (decl) = 1;
7653 if (cleanup)
7654 finish_decl_cleanup (decl, cleanup);
7657 /* DECL is a VAR_DECL for a compiler-generated variable with static
7658 storage duration (like a virtual table) whose initializer is a
7659 compile-time constant. Initialize the variable and provide it to the
7660 back end. */
7662 void
7663 initialize_artificial_var (tree decl, vec<constructor_elt, va_gc> *v)
7665 tree init;
7666 gcc_assert (DECL_ARTIFICIAL (decl));
7667 init = build_constructor (TREE_TYPE (decl), v);
7668 gcc_assert (TREE_CODE (init) == CONSTRUCTOR);
7669 DECL_INITIAL (decl) = init;
7670 DECL_INITIALIZED_P (decl) = 1;
7671 /* Mark the decl as constexpr so that we can access its content
7672 at compile time. */
7673 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = true;
7674 DECL_DECLARED_CONSTEXPR_P (decl) = true;
7675 determine_visibility (decl);
7676 layout_var_decl (decl);
7677 maybe_commonize_var (decl);
7678 make_rtl_for_nonlocal_decl (decl, init, /*asmspec=*/NULL);
7681 /* INIT is the initializer for a variable, as represented by the
7682 parser. Returns true iff INIT is value-dependent. */
7684 static bool
7685 value_dependent_init_p (tree init)
7687 if (TREE_CODE (init) == TREE_LIST)
7688 /* A parenthesized initializer, e.g.: int i (3, 2); ? */
7689 return any_value_dependent_elements_p (init);
7690 else if (TREE_CODE (init) == CONSTRUCTOR)
7691 /* A brace-enclosed initializer, e.g.: int i = { 3 }; ? */
7693 if (dependent_type_p (TREE_TYPE (init)))
7694 return true;
7696 vec<constructor_elt, va_gc> *elts;
7697 size_t nelts;
7698 size_t i;
7700 elts = CONSTRUCTOR_ELTS (init);
7701 nelts = vec_safe_length (elts);
7702 for (i = 0; i < nelts; ++i)
7703 if (value_dependent_init_p ((*elts)[i].value))
7704 return true;
7706 else
7707 /* It must be a simple expression, e.g., int i = 3; */
7708 return value_dependent_expression_p (init);
7710 return false;
7713 // Returns true if a DECL is VAR_DECL with the concept specifier.
7714 static inline bool
7715 is_concept_var (tree decl)
7717 return (VAR_P (decl)
7718 // Not all variables have DECL_LANG_SPECIFIC.
7719 && DECL_LANG_SPECIFIC (decl)
7720 && DECL_DECLARED_CONCEPT_P (decl));
7723 /* A helper function to be called via walk_tree. If any label exists
7724 under *TP, it is (going to be) forced. Set has_forced_label_in_static. */
7726 static tree
7727 notice_forced_label_r (tree *tp, int *walk_subtrees, void *)
7729 if (TYPE_P (*tp))
7730 *walk_subtrees = 0;
7731 if (TREE_CODE (*tp) == LABEL_DECL)
7732 cfun->has_forced_label_in_static = 1;
7733 return NULL_TREE;
7736 /* Return true if DECL has either a trivial destructor, or for C++20
7737 is constexpr and has a constexpr destructor. */
7739 static bool
7740 decl_maybe_constant_destruction (tree decl, tree type)
7742 return (TYPE_HAS_TRIVIAL_DESTRUCTOR (type)
7743 || (cxx_dialect >= cxx20
7744 && VAR_P (decl)
7745 && DECL_DECLARED_CONSTEXPR_P (decl)
7746 && type_has_constexpr_destructor (strip_array_types (type))));
7749 static tree declare_simd_adjust_this (tree *, int *, void *);
7751 /* Helper function of omp_declare_variant_finalize. Finalize one
7752 "omp declare variant base" attribute. Return true if it should be
7753 removed. */
7755 static bool
7756 omp_declare_variant_finalize_one (tree decl, tree attr)
7758 if (TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
7760 walk_tree (&TREE_VALUE (TREE_VALUE (attr)), declare_simd_adjust_this,
7761 DECL_ARGUMENTS (decl), NULL);
7762 walk_tree (&TREE_PURPOSE (TREE_VALUE (attr)), declare_simd_adjust_this,
7763 DECL_ARGUMENTS (decl), NULL);
7766 tree ctx = TREE_VALUE (TREE_VALUE (attr));
7767 tree simd = omp_get_context_selector (ctx, "construct", "simd");
7768 if (simd)
7770 TREE_VALUE (simd)
7771 = c_omp_declare_simd_clauses_to_numbers (DECL_ARGUMENTS (decl),
7772 TREE_VALUE (simd));
7773 /* FIXME, adjusting simd args unimplemented. */
7774 return true;
7777 tree chain = TREE_CHAIN (TREE_VALUE (attr));
7778 location_t varid_loc
7779 = cp_expr_loc_or_input_loc (TREE_PURPOSE (TREE_CHAIN (chain)));
7780 location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
7781 cp_id_kind idk = (cp_id_kind) tree_to_uhwi (TREE_VALUE (chain));
7782 tree variant = TREE_PURPOSE (TREE_VALUE (attr));
7784 location_t save_loc = input_location;
7785 input_location = varid_loc;
7787 releasing_vec args;
7788 tree parm = DECL_ARGUMENTS (decl);
7789 if (TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
7790 parm = DECL_CHAIN (parm);
7791 for (; parm; parm = DECL_CHAIN (parm))
7792 if (type_dependent_expression_p (parm))
7793 vec_safe_push (args, build_constructor (TREE_TYPE (parm), NULL));
7794 else if (MAYBE_CLASS_TYPE_P (TREE_TYPE (parm)))
7795 vec_safe_push (args, build_local_temp (TREE_TYPE (parm)));
7796 else
7797 vec_safe_push (args, build_zero_cst (TREE_TYPE (parm)));
7799 bool koenig_p = false;
7800 if (idk == CP_ID_KIND_UNQUALIFIED || idk == CP_ID_KIND_TEMPLATE_ID)
7802 if (identifier_p (variant)
7803 /* In C++20, we may need to perform ADL for a template
7804 name. */
7805 || (TREE_CODE (variant) == TEMPLATE_ID_EXPR
7806 && identifier_p (TREE_OPERAND (variant, 0))))
7808 if (!args->is_empty ())
7810 koenig_p = true;
7811 if (!any_type_dependent_arguments_p (args))
7812 variant = perform_koenig_lookup (variant, args,
7813 tf_warning_or_error);
7815 else
7816 variant = unqualified_fn_lookup_error (variant);
7818 else if (!args->is_empty () && is_overloaded_fn (variant))
7820 tree fn = get_first_fn (variant);
7821 fn = STRIP_TEMPLATE (fn);
7822 if (!((TREE_CODE (fn) == USING_DECL && DECL_DEPENDENT_P (fn))
7823 || DECL_FUNCTION_MEMBER_P (fn)
7824 || DECL_LOCAL_DECL_P (fn)))
7826 koenig_p = true;
7827 if (!any_type_dependent_arguments_p (args))
7828 variant = perform_koenig_lookup (variant, args,
7829 tf_warning_or_error);
7834 if (idk == CP_ID_KIND_QUALIFIED)
7835 variant = finish_call_expr (variant, &args, /*disallow_virtual=*/true,
7836 koenig_p, tf_warning_or_error);
7837 else
7838 variant = finish_call_expr (variant, &args, /*disallow_virtual=*/false,
7839 koenig_p, tf_warning_or_error);
7840 if (variant == error_mark_node && !processing_template_decl)
7841 return true;
7843 variant = cp_get_callee_fndecl_nofold (variant);
7844 input_location = save_loc;
7846 if (variant)
7848 const char *varname = IDENTIFIER_POINTER (DECL_NAME (variant));
7849 if (!comptypes (TREE_TYPE (decl), TREE_TYPE (variant), 0))
7851 error_at (varid_loc, "variant %qD and base %qD have incompatible "
7852 "types", variant, decl);
7853 return true;
7855 if (fndecl_built_in_p (variant)
7856 && (startswith (varname, "__builtin_")
7857 || startswith (varname, "__sync_")
7858 || startswith (varname, "__atomic_")))
7860 error_at (varid_loc, "variant %qD is a built-in", variant);
7861 return true;
7863 else
7865 tree construct = omp_get_context_selector (ctx, "construct", NULL);
7866 omp_mark_declare_variant (match_loc, variant, construct);
7867 if (!omp_context_selector_matches (ctx))
7868 return true;
7869 TREE_PURPOSE (TREE_VALUE (attr)) = variant;
7872 else if (!processing_template_decl)
7874 error_at (varid_loc, "could not find variant declaration");
7875 return true;
7878 return false;
7881 /* Helper function, finish up "omp declare variant base" attribute
7882 now that there is a DECL. ATTR is the first "omp declare variant base"
7883 attribute. */
7885 void
7886 omp_declare_variant_finalize (tree decl, tree attr)
7888 size_t attr_len = strlen ("omp declare variant base");
7889 tree *list = &DECL_ATTRIBUTES (decl);
7890 bool remove_all = false;
7891 location_t match_loc = DECL_SOURCE_LOCATION (decl);
7892 if (TREE_CHAIN (TREE_VALUE (attr))
7893 && TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr)))
7894 && EXPR_HAS_LOCATION (TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr)))))
7895 match_loc = EXPR_LOCATION (TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr))));
7896 if (DECL_CONSTRUCTOR_P (decl))
7898 error_at (match_loc, "%<declare variant%> on constructor %qD", decl);
7899 remove_all = true;
7901 else if (DECL_DESTRUCTOR_P (decl))
7903 error_at (match_loc, "%<declare variant%> on destructor %qD", decl);
7904 remove_all = true;
7906 else if (DECL_DEFAULTED_FN (decl))
7908 error_at (match_loc, "%<declare variant%> on defaulted %qD", decl);
7909 remove_all = true;
7911 else if (DECL_DELETED_FN (decl))
7913 error_at (match_loc, "%<declare variant%> on deleted %qD", decl);
7914 remove_all = true;
7916 else if (DECL_VIRTUAL_P (decl))
7918 error_at (match_loc, "%<declare variant%> on virtual %qD", decl);
7919 remove_all = true;
7921 /* This loop is like private_lookup_attribute, except that it works
7922 with tree * rather than tree, as we might want to remove the
7923 attributes that are diagnosed as errorneous. */
7924 while (*list)
7926 tree attr = get_attribute_name (*list);
7927 size_t ident_len = IDENTIFIER_LENGTH (attr);
7928 if (cmp_attribs ("omp declare variant base", attr_len,
7929 IDENTIFIER_POINTER (attr), ident_len))
7931 if (remove_all || omp_declare_variant_finalize_one (decl, *list))
7933 *list = TREE_CHAIN (*list);
7934 continue;
7937 list = &TREE_CHAIN (*list);
7941 /* Finish processing of a declaration;
7942 install its line number and initial value.
7943 If the length of an array type is not known before,
7944 it must be determined now, from the initial value, or it is an error.
7946 INIT is the initializer (if any) for DECL. If INIT_CONST_EXPR_P is
7947 true, then INIT is an integral constant expression.
7949 FLAGS is LOOKUP_ONLYCONVERTING if the = init syntax was used, else 0
7950 if the (init) syntax was used. */
7952 void
7953 cp_finish_decl (tree decl, tree init, bool init_const_expr_p,
7954 tree asmspec_tree, int flags)
7956 tree type;
7957 vec<tree, va_gc> *cleanups = NULL;
7958 const char *asmspec = NULL;
7959 int was_readonly = 0;
7960 bool var_definition_p = false;
7961 tree auto_node;
7963 if (decl == error_mark_node)
7964 return;
7965 else if (! decl)
7967 if (init)
7968 error ("assignment (not initialization) in declaration");
7969 return;
7972 gcc_assert (TREE_CODE (decl) != RESULT_DECL);
7973 /* Parameters are handled by store_parm_decls, not cp_finish_decl. */
7974 gcc_assert (TREE_CODE (decl) != PARM_DECL);
7976 type = TREE_TYPE (decl);
7977 if (type == error_mark_node)
7978 return;
7980 if (VAR_P (decl) && is_copy_initialization (init))
7981 flags |= LOOKUP_ONLYCONVERTING;
7983 /* Warn about register storage specifiers except when in GNU global
7984 or local register variable extension. */
7985 if (VAR_P (decl) && DECL_REGISTER (decl) && asmspec_tree == NULL_TREE)
7987 if (cxx_dialect >= cxx17)
7988 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
7989 "ISO C++17 does not allow %<register%> storage "
7990 "class specifier");
7991 else
7992 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
7993 "%<register%> storage class specifier used");
7996 /* If a name was specified, get the string. */
7997 if (at_namespace_scope_p ())
7998 asmspec_tree = maybe_apply_renaming_pragma (decl, asmspec_tree);
7999 if (asmspec_tree && asmspec_tree != error_mark_node)
8000 asmspec = TREE_STRING_POINTER (asmspec_tree);
8002 bool in_class_decl
8003 = (current_class_type
8004 && CP_DECL_CONTEXT (decl) == current_class_type
8005 && TYPE_BEING_DEFINED (current_class_type)
8006 && !CLASSTYPE_TEMPLATE_INSTANTIATION (current_class_type));
8008 if (in_class_decl
8009 && (DECL_INITIAL (decl) || init))
8010 DECL_INITIALIZED_IN_CLASS_P (decl) = 1;
8012 if (TREE_CODE (decl) != FUNCTION_DECL
8013 && (auto_node = type_uses_auto (type)))
8015 tree d_init;
8016 if (init == NULL_TREE)
8018 if (DECL_LANG_SPECIFIC (decl)
8019 && DECL_TEMPLATE_INSTANTIATION (decl)
8020 && !DECL_TEMPLATE_INSTANTIATED (decl))
8022 /* init is null because we're deferring instantiating the
8023 initializer until we need it. Well, we need it now. */
8024 instantiate_decl (decl, /*defer_ok*/true, /*expl*/false);
8025 return;
8028 gcc_assert (CLASS_PLACEHOLDER_TEMPLATE (auto_node));
8030 d_init = init;
8031 if (d_init)
8033 if (TREE_CODE (d_init) == TREE_LIST
8034 && !CLASS_PLACEHOLDER_TEMPLATE (auto_node))
8035 d_init = build_x_compound_expr_from_list (d_init, ELK_INIT,
8036 tf_warning_or_error);
8037 d_init = resolve_nondeduced_context (d_init, tf_warning_or_error);
8039 enum auto_deduction_context adc = adc_variable_type;
8040 if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
8041 adc = adc_decomp_type;
8042 tree outer_targs = NULL_TREE;
8043 if (PLACEHOLDER_TYPE_CONSTRAINTS_INFO (auto_node)
8044 && VAR_P (decl)
8045 && DECL_LANG_SPECIFIC (decl)
8046 && DECL_TEMPLATE_INFO (decl)
8047 && !DECL_FUNCTION_SCOPE_P (decl))
8048 /* The outer template arguments might be needed for satisfaction.
8049 (For function scope variables, do_auto_deduction will obtain the
8050 outer template arguments from current_function_decl.) */
8051 outer_targs = DECL_TI_ARGS (decl);
8052 type = TREE_TYPE (decl) = do_auto_deduction (type, d_init, auto_node,
8053 tf_warning_or_error, adc,
8054 outer_targs, flags);
8055 if (type == error_mark_node)
8056 return;
8057 if (TREE_CODE (type) == FUNCTION_TYPE)
8059 error ("initializer for %<decltype(auto) %D%> has function type; "
8060 "did you forget the %<()%>?", decl);
8061 TREE_TYPE (decl) = error_mark_node;
8062 return;
8064 cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
8067 if (ensure_literal_type_for_constexpr_object (decl) == error_mark_node)
8069 DECL_DECLARED_CONSTEXPR_P (decl) = 0;
8070 if (VAR_P (decl) && DECL_CLASS_SCOPE_P (decl))
8072 init = NULL_TREE;
8073 DECL_EXTERNAL (decl) = 1;
8077 if (VAR_P (decl)
8078 && DECL_CLASS_SCOPE_P (decl)
8079 && verify_type_context (DECL_SOURCE_LOCATION (decl),
8080 TCTX_STATIC_STORAGE, type)
8081 && DECL_INITIALIZED_IN_CLASS_P (decl))
8082 check_static_variable_definition (decl, type);
8084 if (!processing_template_decl && VAR_P (decl) && is_global_var (decl))
8086 type_context_kind context = (DECL_THREAD_LOCAL_P (decl)
8087 ? TCTX_THREAD_STORAGE
8088 : TCTX_STATIC_STORAGE);
8089 verify_type_context (input_location, context, TREE_TYPE (decl));
8092 if (init && TREE_CODE (decl) == FUNCTION_DECL)
8094 tree clone;
8095 if (init == ridpointers[(int)RID_DELETE])
8097 /* FIXME check this is 1st decl. */
8098 DECL_DELETED_FN (decl) = 1;
8099 DECL_DECLARED_INLINE_P (decl) = 1;
8100 DECL_INITIAL (decl) = error_mark_node;
8101 FOR_EACH_CLONE (clone, decl)
8103 DECL_DELETED_FN (clone) = 1;
8104 DECL_DECLARED_INLINE_P (clone) = 1;
8105 DECL_INITIAL (clone) = error_mark_node;
8107 init = NULL_TREE;
8109 else if (init == ridpointers[(int)RID_DEFAULT])
8111 if (defaultable_fn_check (decl))
8112 DECL_DEFAULTED_FN (decl) = 1;
8113 else
8114 DECL_INITIAL (decl) = NULL_TREE;
8118 if (init && VAR_P (decl))
8120 DECL_NONTRIVIALLY_INITIALIZED_P (decl) = 1;
8121 /* If DECL is a reference, then we want to know whether init is a
8122 reference constant; init_const_expr_p as passed tells us whether
8123 it's an rvalue constant. */
8124 if (TYPE_REF_P (type))
8125 init_const_expr_p = potential_constant_expression (init);
8126 if (init_const_expr_p)
8128 /* Set these flags now for templates. We'll update the flags in
8129 store_init_value for instantiations. */
8130 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = 1;
8131 if (decl_maybe_constant_var_p (decl)
8132 /* FIXME setting TREE_CONSTANT on refs breaks the back end. */
8133 && !TYPE_REF_P (type))
8134 TREE_CONSTANT (decl) = 1;
8138 if (flag_openmp
8139 && TREE_CODE (decl) == FUNCTION_DECL
8140 /* #pragma omp declare variant on methods handled in finish_struct
8141 instead. */
8142 && (!DECL_NONSTATIC_MEMBER_FUNCTION_P (decl)
8143 || COMPLETE_TYPE_P (DECL_CONTEXT (decl))))
8144 if (tree attr = lookup_attribute ("omp declare variant base",
8145 DECL_ATTRIBUTES (decl)))
8146 omp_declare_variant_finalize (decl, attr);
8148 if (processing_template_decl)
8150 bool type_dependent_p;
8152 /* Add this declaration to the statement-tree. */
8153 if (at_function_scope_p ())
8154 add_decl_expr (decl);
8156 type_dependent_p = dependent_type_p (type);
8158 if (check_for_bare_parameter_packs (init))
8160 init = NULL_TREE;
8161 DECL_INITIAL (decl) = NULL_TREE;
8164 /* Generally, initializers in templates are expanded when the
8165 template is instantiated. But, if DECL is a variable constant
8166 then it can be used in future constant expressions, so its value
8167 must be available. */
8169 bool dep_init = false;
8171 if (!VAR_P (decl) || type_dependent_p)
8172 /* We can't do anything if the decl has dependent type. */;
8173 else if (!init && is_concept_var (decl))
8175 error ("variable concept has no initializer");
8176 init = boolean_true_node;
8178 else if (init
8179 && (init_const_expr_p || DECL_DECLARED_CONSTEXPR_P (decl))
8180 && !TYPE_REF_P (type)
8181 && decl_maybe_constant_var_p (decl)
8182 && !(dep_init = value_dependent_init_p (init)))
8184 /* This variable seems to be a non-dependent constant, so process
8185 its initializer. If check_initializer returns non-null the
8186 initialization wasn't constant after all. */
8187 tree init_code;
8188 cleanups = make_tree_vector ();
8189 init_code = check_initializer (decl, init, flags, &cleanups);
8190 if (init_code == NULL_TREE)
8191 init = NULL_TREE;
8192 release_tree_vector (cleanups);
8194 else
8196 gcc_assert (!DECL_PRETTY_FUNCTION_P (decl));
8197 /* Try to deduce array size. */
8198 maybe_deduce_size_from_array_init (decl, init);
8199 /* And complain about multiple initializers. */
8200 if (init && TREE_CODE (init) == TREE_LIST && TREE_CHAIN (init)
8201 && !MAYBE_CLASS_TYPE_P (type))
8202 init = build_x_compound_expr_from_list (init, ELK_INIT,
8203 tf_warning_or_error);
8206 if (init)
8207 DECL_INITIAL (decl) = init;
8209 if (dep_init)
8211 retrofit_lang_decl (decl);
8212 SET_DECL_DEPENDENT_INIT_P (decl, true);
8215 if (VAR_P (decl) && DECL_REGISTER (decl) && asmspec)
8217 set_user_assembler_name (decl, asmspec);
8218 DECL_HARD_REGISTER (decl) = 1;
8220 return;
8223 /* Just store non-static data member initializers for later. */
8224 if (init && TREE_CODE (decl) == FIELD_DECL)
8225 DECL_INITIAL (decl) = init;
8227 /* Take care of TYPE_DECLs up front. */
8228 if (TREE_CODE (decl) == TYPE_DECL)
8230 if (type != error_mark_node
8231 && MAYBE_CLASS_TYPE_P (type) && DECL_NAME (decl))
8233 if (TREE_TYPE (DECL_NAME (decl)) && TREE_TYPE (decl) != type)
8234 warning (0, "shadowing previous type declaration of %q#D", decl);
8235 set_identifier_type_value (DECL_NAME (decl), decl);
8238 /* If we have installed this as the canonical typedef for this
8239 type, and that type has not been defined yet, delay emitting
8240 the debug information for it, as we will emit it later. */
8241 if (TYPE_MAIN_DECL (TREE_TYPE (decl)) == decl
8242 && !COMPLETE_TYPE_P (TREE_TYPE (decl)))
8243 TYPE_DECL_SUPPRESS_DEBUG (decl) = 1;
8245 rest_of_decl_compilation (decl, DECL_FILE_SCOPE_P (decl),
8246 at_eof);
8247 return;
8250 /* A reference will be modified here, as it is initialized. */
8251 if (! DECL_EXTERNAL (decl)
8252 && TREE_READONLY (decl)
8253 && TYPE_REF_P (type))
8255 was_readonly = 1;
8256 TREE_READONLY (decl) = 0;
8259 /* This needs to happen before extend_ref_init_temps. */
8260 if (VAR_OR_FUNCTION_DECL_P (decl))
8262 if (VAR_P (decl))
8263 maybe_commonize_var (decl);
8264 determine_visibility (decl);
8267 if (VAR_P (decl))
8269 duration_kind dk = decl_storage_duration (decl);
8270 /* [dcl.constinit]/1 "The constinit specifier shall be applied
8271 only to a declaration of a variable with static or thread storage
8272 duration." */
8273 if (DECL_DECLARED_CONSTINIT_P (decl)
8274 && !(dk == dk_thread || dk == dk_static))
8276 error_at (DECL_SOURCE_LOCATION (decl),
8277 "%<constinit%> can only be applied to a variable with "
8278 "static or thread storage duration");
8279 return;
8282 /* If this is a local variable that will need a mangled name,
8283 register it now. We must do this before processing the
8284 initializer for the variable, since the initialization might
8285 require a guard variable, and since the mangled name of the
8286 guard variable will depend on the mangled name of this
8287 variable. */
8288 if (DECL_FUNCTION_SCOPE_P (decl)
8289 && TREE_STATIC (decl)
8290 && !DECL_ARTIFICIAL (decl))
8292 /* The variable holding an anonymous union will have had its
8293 discriminator set in finish_anon_union, after which it's
8294 NAME will have been cleared. */
8295 if (DECL_NAME (decl))
8296 determine_local_discriminator (decl);
8297 /* Normally has_forced_label_in_static is set during GIMPLE
8298 lowering, but [cd]tors are never actually compiled directly.
8299 We need to set this early so we can deal with the label
8300 address extension. */
8301 if ((DECL_CONSTRUCTOR_P (current_function_decl)
8302 || DECL_DESTRUCTOR_P (current_function_decl))
8303 && init)
8305 walk_tree (&init, notice_forced_label_r, NULL, NULL);
8306 add_local_decl (cfun, decl);
8308 /* And make sure it's in the symbol table for
8309 c_parse_final_cleanups to find. */
8310 varpool_node::get_create (decl);
8313 /* Convert the initializer to the type of DECL, if we have not
8314 already initialized DECL. */
8315 if (!DECL_INITIALIZED_P (decl)
8316 /* If !DECL_EXTERNAL then DECL is being defined. In the
8317 case of a static data member initialized inside the
8318 class-specifier, there can be an initializer even if DECL
8319 is *not* defined. */
8320 && (!DECL_EXTERNAL (decl) || init))
8322 cleanups = make_tree_vector ();
8323 init = check_initializer (decl, init, flags, &cleanups);
8325 /* Handle:
8327 [dcl.init]
8329 The memory occupied by any object of static storage
8330 duration is zero-initialized at program startup before
8331 any other initialization takes place.
8333 We cannot create an appropriate initializer until after
8334 the type of DECL is finalized. If DECL_INITIAL is set,
8335 then the DECL is statically initialized, and any
8336 necessary zero-initialization has already been performed. */
8337 if (TREE_STATIC (decl) && !DECL_INITIAL (decl))
8338 DECL_INITIAL (decl) = build_zero_init (TREE_TYPE (decl),
8339 /*nelts=*/NULL_TREE,
8340 /*static_storage_p=*/true);
8341 /* Remember that the initialization for this variable has
8342 taken place. */
8343 DECL_INITIALIZED_P (decl) = 1;
8344 /* This declaration is the definition of this variable,
8345 unless we are initializing a static data member within
8346 the class specifier. */
8347 if (!DECL_EXTERNAL (decl))
8348 var_definition_p = true;
8350 /* If the variable has an array type, lay out the type, even if
8351 there is no initializer. It is valid to index through the
8352 array, and we must get TYPE_ALIGN set correctly on the array
8353 type. */
8354 else if (TREE_CODE (type) == ARRAY_TYPE)
8355 layout_type (type);
8357 if (TREE_STATIC (decl)
8358 && !at_function_scope_p ()
8359 && current_function_decl == NULL)
8360 /* So decl is a global variable or a static member of a
8361 non local class. Record the types it uses
8362 so that we can decide later to emit debug info for them. */
8363 record_types_used_by_current_var_decl (decl);
8366 /* Add this declaration to the statement-tree. This needs to happen
8367 after the call to check_initializer so that the DECL_EXPR for a
8368 reference temp is added before the DECL_EXPR for the reference itself. */
8369 if (DECL_FUNCTION_SCOPE_P (decl))
8371 /* If we're building a variable sized type, and we might be
8372 reachable other than via the top of the current binding
8373 level, then create a new BIND_EXPR so that we deallocate
8374 the object at the right time. */
8375 if (VAR_P (decl)
8376 && DECL_SIZE (decl)
8377 && !TREE_CONSTANT (DECL_SIZE (decl))
8378 && STATEMENT_LIST_HAS_LABEL (cur_stmt_list))
8380 tree bind;
8381 bind = build3 (BIND_EXPR, void_type_node, NULL, NULL, NULL);
8382 TREE_SIDE_EFFECTS (bind) = 1;
8383 add_stmt (bind);
8384 BIND_EXPR_BODY (bind) = push_stmt_list ();
8386 add_decl_expr (decl);
8389 /* Let the middle end know about variables and functions -- but not
8390 static data members in uninstantiated class templates. */
8391 if (VAR_OR_FUNCTION_DECL_P (decl))
8393 if (VAR_P (decl))
8395 layout_var_decl (decl);
8396 if (!flag_weak)
8397 /* Check again now that we have an initializer. */
8398 maybe_commonize_var (decl);
8399 /* A class-scope constexpr variable with an out-of-class declaration.
8400 C++17 makes them implicitly inline, but still force it out. */
8401 if (DECL_INLINE_VAR_P (decl)
8402 && !DECL_VAR_DECLARED_INLINE_P (decl)
8403 && !DECL_TEMPLATE_INSTANTIATION (decl)
8404 && !in_class_decl)
8405 mark_needed (decl);
8408 if (var_definition_p
8409 /* With -fmerge-all-constants, gimplify_init_constructor
8410 might add TREE_STATIC to the variable. */
8411 && (TREE_STATIC (decl) || flag_merge_constants >= 2))
8413 /* If a TREE_READONLY variable needs initialization
8414 at runtime, it is no longer readonly and we need to
8415 avoid MEM_READONLY_P being set on RTL created for it. */
8416 if (init)
8418 if (TREE_READONLY (decl))
8419 TREE_READONLY (decl) = 0;
8420 was_readonly = 0;
8422 else if (was_readonly)
8423 TREE_READONLY (decl) = 1;
8425 /* Likewise if it needs destruction. */
8426 if (!decl_maybe_constant_destruction (decl, type))
8427 TREE_READONLY (decl) = 0;
8430 make_rtl_for_nonlocal_decl (decl, init, asmspec);
8432 /* Check for abstractness of the type. */
8433 if (var_definition_p)
8434 abstract_virtuals_error (decl, type);
8436 if (TREE_TYPE (decl) == error_mark_node)
8437 /* No initialization required. */
8439 else if (TREE_CODE (decl) == FUNCTION_DECL)
8441 if (init)
8443 if (init == ridpointers[(int)RID_DEFAULT])
8445 /* An out-of-class default definition is defined at
8446 the point where it is explicitly defaulted. */
8447 if (DECL_DELETED_FN (decl))
8448 maybe_explain_implicit_delete (decl);
8449 else if (DECL_INITIAL (decl) == error_mark_node)
8450 synthesize_method (decl);
8452 else
8453 error_at (cp_expr_loc_or_loc (init,
8454 DECL_SOURCE_LOCATION (decl)),
8455 "function %q#D is initialized like a variable",
8456 decl);
8458 /* else no initialization required. */
8460 else if (DECL_EXTERNAL (decl)
8461 && ! (DECL_LANG_SPECIFIC (decl)
8462 && DECL_NOT_REALLY_EXTERN (decl)))
8464 /* check_initializer will have done any constant initialization. */
8466 /* A variable definition. */
8467 else if (DECL_FUNCTION_SCOPE_P (decl) && !TREE_STATIC (decl))
8468 /* Initialize the local variable. */
8469 initialize_local_var (decl, init);
8471 /* If a variable is defined, and then a subsequent
8472 definition with external linkage is encountered, we will
8473 get here twice for the same variable. We want to avoid
8474 calling expand_static_init more than once. For variables
8475 that are not static data members, we can call
8476 expand_static_init only when we actually process the
8477 initializer. It is not legal to redeclare a static data
8478 member, so this issue does not arise in that case. */
8479 else if (var_definition_p && TREE_STATIC (decl))
8480 expand_static_init (decl, init);
8483 /* If a CLEANUP_STMT was created to destroy a temporary bound to a
8484 reference, insert it in the statement-tree now. */
8485 if (cleanups)
8487 for (tree t : *cleanups)
8489 push_cleanup (decl, t, false);
8490 /* As in initialize_local_var. */
8491 wrap_temporary_cleanups (init, t);
8493 release_tree_vector (cleanups);
8496 if (was_readonly)
8497 TREE_READONLY (decl) = 1;
8499 if (flag_openmp
8500 && VAR_P (decl)
8501 && lookup_attribute ("omp declare target implicit",
8502 DECL_ATTRIBUTES (decl)))
8504 DECL_ATTRIBUTES (decl)
8505 = remove_attribute ("omp declare target implicit",
8506 DECL_ATTRIBUTES (decl));
8507 complete_type (TREE_TYPE (decl));
8508 if (!cp_omp_mappable_type (TREE_TYPE (decl)))
8510 error ("%q+D in declare target directive does not have mappable"
8511 " type", decl);
8512 cp_omp_emit_unmappable_type_notes (TREE_TYPE (decl));
8514 else if (!lookup_attribute ("omp declare target",
8515 DECL_ATTRIBUTES (decl))
8516 && !lookup_attribute ("omp declare target link",
8517 DECL_ATTRIBUTES (decl)))
8519 DECL_ATTRIBUTES (decl)
8520 = tree_cons (get_identifier ("omp declare target"),
8521 NULL_TREE, DECL_ATTRIBUTES (decl));
8522 symtab_node *node = symtab_node::get (decl);
8523 if (node != NULL)
8525 node->offloadable = 1;
8526 if (ENABLE_OFFLOADING)
8528 g->have_offload = true;
8529 if (is_a <varpool_node *> (node))
8530 vec_safe_push (offload_vars, decl);
8536 /* This is the last point we can lower alignment so give the target the
8537 chance to do so. */
8538 if (VAR_P (decl)
8539 && !is_global_var (decl)
8540 && !DECL_HARD_REGISTER (decl))
8541 targetm.lower_local_decl_alignment (decl);
8543 invoke_plugin_callbacks (PLUGIN_FINISH_DECL, decl);
8546 /* For class TYPE return itself or some its bases that contain
8547 any direct non-static data members. Return error_mark_node if an
8548 error has been diagnosed. */
8550 static tree
8551 find_decomp_class_base (location_t loc, tree type, tree ret)
8553 bool member_seen = false;
8554 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
8555 if (TREE_CODE (field) != FIELD_DECL
8556 || DECL_ARTIFICIAL (field)
8557 || DECL_UNNAMED_BIT_FIELD (field))
8558 continue;
8559 else if (ret)
8560 return type;
8561 else if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
8563 if (TREE_CODE (TREE_TYPE (field)) == RECORD_TYPE)
8564 error_at (loc, "cannot decompose class type %qT because it has an "
8565 "anonymous struct member", type);
8566 else
8567 error_at (loc, "cannot decompose class type %qT because it has an "
8568 "anonymous union member", type);
8569 inform (DECL_SOURCE_LOCATION (field), "declared here");
8570 return error_mark_node;
8572 else if (!accessible_p (type, field, true))
8574 error_at (loc, "cannot decompose inaccessible member %qD of %qT",
8575 field, type);
8576 inform (DECL_SOURCE_LOCATION (field),
8577 TREE_PRIVATE (field)
8578 ? G_("declared private here")
8579 : G_("declared protected here"));
8580 return error_mark_node;
8582 else
8583 member_seen = true;
8585 tree base_binfo, binfo;
8586 tree orig_ret = ret;
8587 int i;
8588 if (member_seen)
8589 ret = type;
8590 for (binfo = TYPE_BINFO (type), i = 0;
8591 BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
8593 tree t = find_decomp_class_base (loc, TREE_TYPE (base_binfo), ret);
8594 if (t == error_mark_node)
8595 return error_mark_node;
8596 if (t != NULL_TREE && t != ret)
8598 if (ret == type)
8600 error_at (loc, "cannot decompose class type %qT: both it and "
8601 "its base class %qT have non-static data members",
8602 type, t);
8603 return error_mark_node;
8605 else if (orig_ret != NULL_TREE)
8606 return t;
8607 else if (ret != NULL_TREE)
8609 error_at (loc, "cannot decompose class type %qT: its base "
8610 "classes %qT and %qT have non-static data "
8611 "members", type, ret, t);
8612 return error_mark_node;
8614 else
8615 ret = t;
8618 return ret;
8621 /* Return std::tuple_size<TYPE>::value. */
8623 static tree
8624 get_tuple_size (tree type)
8626 tree args = make_tree_vec (1);
8627 TREE_VEC_ELT (args, 0) = type;
8628 tree inst = lookup_template_class (tuple_size_identifier, args,
8629 /*in_decl*/NULL_TREE,
8630 /*context*/std_node,
8631 /*entering_scope*/false, tf_none);
8632 inst = complete_type (inst);
8633 if (inst == error_mark_node || !COMPLETE_TYPE_P (inst))
8634 return NULL_TREE;
8635 tree val = lookup_qualified_name (inst, value_identifier,
8636 LOOK_want::NORMAL, /*complain*/false);
8637 if (TREE_CODE (val) == VAR_DECL || TREE_CODE (val) == CONST_DECL)
8638 val = maybe_constant_value (val);
8639 if (TREE_CODE (val) == INTEGER_CST)
8640 return val;
8641 else
8642 return error_mark_node;
8645 /* Return std::tuple_element<I,TYPE>::type. */
8647 static tree
8648 get_tuple_element_type (tree type, unsigned i)
8650 tree args = make_tree_vec (2);
8651 TREE_VEC_ELT (args, 0) = build_int_cst (integer_type_node, i);
8652 TREE_VEC_ELT (args, 1) = type;
8653 tree inst = lookup_template_class (tuple_element_identifier, args,
8654 /*in_decl*/NULL_TREE,
8655 /*context*/std_node,
8656 /*entering_scope*/false,
8657 tf_warning_or_error);
8658 return make_typename_type (inst, type_identifier,
8659 none_type, tf_warning_or_error);
8662 /* Return e.get<i>() or get<i>(e). */
8664 static tree
8665 get_tuple_decomp_init (tree decl, unsigned i)
8667 tree targs = make_tree_vec (1);
8668 TREE_VEC_ELT (targs, 0) = build_int_cst (integer_type_node, i);
8670 tree etype = TREE_TYPE (decl);
8671 tree e = convert_from_reference (decl);
8673 /* [The id-expression] e is an lvalue if the type of the entity e is an
8674 lvalue reference and an xvalue otherwise. */
8675 if (!TYPE_REF_P (etype)
8676 || TYPE_REF_IS_RVALUE (etype))
8677 e = move (e);
8679 tree fns = lookup_qualified_name (TREE_TYPE (e), get__identifier,
8680 LOOK_want::NORMAL, /*complain*/false);
8681 bool use_member_get = false;
8683 /* To use a member get, member lookup must find at least one
8684 declaration that is a function template
8685 whose first template parameter is a non-type parameter. */
8686 for (lkp_iterator iter (MAYBE_BASELINK_FUNCTIONS (fns)); iter; ++iter)
8688 tree fn = *iter;
8689 if (TREE_CODE (fn) == TEMPLATE_DECL)
8691 tree tparms = DECL_TEMPLATE_PARMS (fn);
8692 tree parm = TREE_VEC_ELT (INNERMOST_TEMPLATE_PARMS (tparms), 0);
8693 if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
8695 use_member_get = true;
8696 break;
8701 if (use_member_get)
8703 fns = lookup_template_function (fns, targs);
8704 return build_new_method_call (e, fns, /*args*/NULL,
8705 /*path*/NULL_TREE, LOOKUP_NORMAL,
8706 /*fn_p*/NULL, tf_warning_or_error);
8708 else
8710 releasing_vec args (make_tree_vector_single (e));
8711 fns = lookup_template_function (get__identifier, targs);
8712 fns = perform_koenig_lookup (fns, args, tf_warning_or_error);
8713 return finish_call_expr (fns, &args, /*novirt*/false,
8714 /*koenig*/true, tf_warning_or_error);
8718 /* It's impossible to recover the decltype of a tuple decomposition variable
8719 based on the actual type of the variable, so store it in a hash table. */
8721 static GTY((cache)) decl_tree_cache_map *decomp_type_table;
8723 tree
8724 lookup_decomp_type (tree v)
8726 return *decomp_type_table->get (v);
8729 /* Mangle a decomposition declaration if needed. Arguments like
8730 in cp_finish_decomp. */
8732 void
8733 cp_maybe_mangle_decomp (tree decl, tree first, unsigned int count)
8735 if (!processing_template_decl
8736 && !error_operand_p (decl)
8737 && TREE_STATIC (decl))
8739 auto_vec<tree, 16> v;
8740 v.safe_grow (count, true);
8741 tree d = first;
8742 for (unsigned int i = 0; i < count; i++, d = DECL_CHAIN (d))
8743 v[count - i - 1] = d;
8744 SET_DECL_ASSEMBLER_NAME (decl, mangle_decomp (decl, v));
8745 maybe_apply_pragma_weak (decl);
8749 /* Finish a decomposition declaration. DECL is the underlying declaration
8750 "e", FIRST is the head of a chain of decls for the individual identifiers
8751 chained through DECL_CHAIN in reverse order and COUNT is the number of
8752 those decls. */
8754 void
8755 cp_finish_decomp (tree decl, tree first, unsigned int count)
8757 if (error_operand_p (decl))
8759 error_out:
8760 while (count--)
8762 TREE_TYPE (first) = error_mark_node;
8763 if (DECL_HAS_VALUE_EXPR_P (first))
8765 SET_DECL_VALUE_EXPR (first, NULL_TREE);
8766 DECL_HAS_VALUE_EXPR_P (first) = 0;
8768 first = DECL_CHAIN (first);
8770 if (DECL_P (decl) && DECL_NAMESPACE_SCOPE_P (decl))
8771 SET_DECL_ASSEMBLER_NAME (decl, get_identifier ("<decomp>"));
8772 return;
8775 location_t loc = DECL_SOURCE_LOCATION (decl);
8776 if (type_dependent_expression_p (decl)
8777 /* This happens for range for when not in templates.
8778 Still add the DECL_VALUE_EXPRs for later processing. */
8779 || (!processing_template_decl
8780 && type_uses_auto (TREE_TYPE (decl))))
8782 for (unsigned int i = 0; i < count; i++)
8784 if (!DECL_HAS_VALUE_EXPR_P (first))
8786 tree v = build_nt (ARRAY_REF, decl,
8787 size_int (count - i - 1),
8788 NULL_TREE, NULL_TREE);
8789 SET_DECL_VALUE_EXPR (first, v);
8790 DECL_HAS_VALUE_EXPR_P (first) = 1;
8792 if (processing_template_decl)
8793 fit_decomposition_lang_decl (first, decl);
8794 first = DECL_CHAIN (first);
8796 return;
8799 auto_vec<tree, 16> v;
8800 v.safe_grow (count, true);
8801 tree d = first;
8802 for (unsigned int i = 0; i < count; i++, d = DECL_CHAIN (d))
8804 v[count - i - 1] = d;
8805 fit_decomposition_lang_decl (d, decl);
8808 tree type = TREE_TYPE (decl);
8809 tree dexp = decl;
8811 if (TYPE_REF_P (type))
8813 dexp = convert_from_reference (dexp);
8814 type = complete_type (TREE_TYPE (type));
8815 if (type == error_mark_node)
8816 goto error_out;
8817 if (!COMPLETE_TYPE_P (type))
8819 error_at (loc, "structured binding refers to incomplete type %qT",
8820 type);
8821 goto error_out;
8825 tree eltype = NULL_TREE;
8826 unsigned HOST_WIDE_INT eltscnt = 0;
8827 if (TREE_CODE (type) == ARRAY_TYPE)
8829 tree nelts;
8830 nelts = array_type_nelts_top (type);
8831 if (nelts == error_mark_node)
8832 goto error_out;
8833 if (!tree_fits_uhwi_p (nelts))
8835 error_at (loc, "cannot decompose variable length array %qT", type);
8836 goto error_out;
8838 eltscnt = tree_to_uhwi (nelts);
8839 if (count != eltscnt)
8841 cnt_mismatch:
8842 if (count > eltscnt)
8843 error_n (loc, count,
8844 "%u name provided for structured binding",
8845 "%u names provided for structured binding", count);
8846 else
8847 error_n (loc, count,
8848 "only %u name provided for structured binding",
8849 "only %u names provided for structured binding", count);
8850 inform_n (loc, eltscnt,
8851 "while %qT decomposes into %wu element",
8852 "while %qT decomposes into %wu elements",
8853 type, eltscnt);
8854 goto error_out;
8856 eltype = TREE_TYPE (type);
8857 for (unsigned int i = 0; i < count; i++)
8859 TREE_TYPE (v[i]) = eltype;
8860 layout_decl (v[i], 0);
8861 if (processing_template_decl)
8862 continue;
8863 tree t = unshare_expr (dexp);
8864 t = build4_loc (DECL_SOURCE_LOCATION (v[i]), ARRAY_REF,
8865 eltype, t, size_int (i), NULL_TREE,
8866 NULL_TREE);
8867 SET_DECL_VALUE_EXPR (v[i], t);
8868 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
8871 /* 2 GNU extensions. */
8872 else if (TREE_CODE (type) == COMPLEX_TYPE)
8874 eltscnt = 2;
8875 if (count != eltscnt)
8876 goto cnt_mismatch;
8877 eltype = cp_build_qualified_type (TREE_TYPE (type), TYPE_QUALS (type));
8878 for (unsigned int i = 0; i < count; i++)
8880 TREE_TYPE (v[i]) = eltype;
8881 layout_decl (v[i], 0);
8882 if (processing_template_decl)
8883 continue;
8884 tree t = unshare_expr (dexp);
8885 t = build1_loc (DECL_SOURCE_LOCATION (v[i]),
8886 i ? IMAGPART_EXPR : REALPART_EXPR, eltype,
8888 SET_DECL_VALUE_EXPR (v[i], t);
8889 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
8892 else if (TREE_CODE (type) == VECTOR_TYPE)
8894 if (!TYPE_VECTOR_SUBPARTS (type).is_constant (&eltscnt))
8896 error_at (loc, "cannot decompose variable length vector %qT", type);
8897 goto error_out;
8899 if (count != eltscnt)
8900 goto cnt_mismatch;
8901 eltype = cp_build_qualified_type (TREE_TYPE (type), TYPE_QUALS (type));
8902 for (unsigned int i = 0; i < count; i++)
8904 TREE_TYPE (v[i]) = eltype;
8905 layout_decl (v[i], 0);
8906 if (processing_template_decl)
8907 continue;
8908 tree t = unshare_expr (dexp);
8909 convert_vector_to_array_for_subscript (DECL_SOURCE_LOCATION (v[i]),
8910 &t, size_int (i));
8911 t = build4_loc (DECL_SOURCE_LOCATION (v[i]), ARRAY_REF,
8912 eltype, t, size_int (i), NULL_TREE,
8913 NULL_TREE);
8914 SET_DECL_VALUE_EXPR (v[i], t);
8915 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
8918 else if (tree tsize = get_tuple_size (type))
8920 if (tsize == error_mark_node)
8922 error_at (loc, "%<std::tuple_size<%T>::value%> is not an integral "
8923 "constant expression", type);
8924 goto error_out;
8926 if (!tree_fits_uhwi_p (tsize))
8928 error_n (loc, count,
8929 "%u name provided for structured binding",
8930 "%u names provided for structured binding", count);
8931 inform (loc, "while %qT decomposes into %E elements",
8932 type, tsize);
8933 goto error_out;
8935 eltscnt = tree_to_uhwi (tsize);
8936 if (count != eltscnt)
8937 goto cnt_mismatch;
8938 int save_read = DECL_READ_P (decl);
8939 for (unsigned i = 0; i < count; ++i)
8941 location_t sloc = input_location;
8942 location_t dloc = DECL_SOURCE_LOCATION (v[i]);
8944 input_location = dloc;
8945 tree init = get_tuple_decomp_init (decl, i);
8946 tree eltype = (init == error_mark_node ? error_mark_node
8947 : get_tuple_element_type (type, i));
8948 input_location = sloc;
8950 if (VOID_TYPE_P (eltype))
8952 error ("%<std::tuple_element<%u, %T>::type%> is %<void%>",
8953 i, type);
8954 eltype = error_mark_node;
8956 if (init == error_mark_node || eltype == error_mark_node)
8958 inform (dloc, "in initialization of structured binding "
8959 "variable %qD", v[i]);
8960 goto error_out;
8962 /* Save the decltype away before reference collapse. */
8963 hash_map_safe_put<hm_ggc> (decomp_type_table, v[i], eltype);
8964 eltype = cp_build_reference_type (eltype, !lvalue_p (init));
8965 TREE_TYPE (v[i]) = eltype;
8966 layout_decl (v[i], 0);
8967 if (DECL_HAS_VALUE_EXPR_P (v[i]))
8969 /* In this case the names are variables, not just proxies. */
8970 SET_DECL_VALUE_EXPR (v[i], NULL_TREE);
8971 DECL_HAS_VALUE_EXPR_P (v[i]) = 0;
8973 if (!processing_template_decl)
8975 copy_linkage (v[i], decl);
8976 cp_finish_decl (v[i], init, /*constexpr*/false,
8977 /*asm*/NULL_TREE, LOOKUP_NORMAL);
8980 /* Ignore reads from the underlying decl performed during initialization
8981 of the individual variables. If those will be read, we'll mark
8982 the underlying decl as read at that point. */
8983 DECL_READ_P (decl) = save_read;
8985 else if (TREE_CODE (type) == UNION_TYPE)
8987 error_at (loc, "cannot decompose union type %qT", type);
8988 goto error_out;
8990 else if (!CLASS_TYPE_P (type))
8992 error_at (loc, "cannot decompose non-array non-class type %qT", type);
8993 goto error_out;
8995 else if (LAMBDA_TYPE_P (type))
8997 error_at (loc, "cannot decompose lambda closure type %qT", type);
8998 goto error_out;
9000 else if (processing_template_decl && complete_type (type) == error_mark_node)
9001 goto error_out;
9002 else if (processing_template_decl && !COMPLETE_TYPE_P (type))
9003 pedwarn (loc, 0, "structured binding refers to incomplete class type %qT",
9004 type);
9005 else
9007 tree btype = find_decomp_class_base (loc, type, NULL_TREE);
9008 if (btype == error_mark_node)
9009 goto error_out;
9010 else if (btype == NULL_TREE)
9012 error_at (loc, "cannot decompose class type %qT without non-static "
9013 "data members", type);
9014 goto error_out;
9016 for (tree field = TYPE_FIELDS (btype); field; field = TREE_CHAIN (field))
9017 if (TREE_CODE (field) != FIELD_DECL
9018 || DECL_ARTIFICIAL (field)
9019 || DECL_UNNAMED_BIT_FIELD (field))
9020 continue;
9021 else
9022 eltscnt++;
9023 if (count != eltscnt)
9024 goto cnt_mismatch;
9025 tree t = dexp;
9026 if (type != btype)
9028 t = convert_to_base (t, btype, /*check_access*/true,
9029 /*nonnull*/false, tf_warning_or_error);
9030 type = btype;
9032 unsigned int i = 0;
9033 for (tree field = TYPE_FIELDS (btype); field; field = TREE_CHAIN (field))
9034 if (TREE_CODE (field) != FIELD_DECL
9035 || DECL_ARTIFICIAL (field)
9036 || DECL_UNNAMED_BIT_FIELD (field))
9037 continue;
9038 else
9040 tree tt = finish_non_static_data_member (field, unshare_expr (t),
9041 NULL_TREE);
9042 if (REFERENCE_REF_P (tt))
9043 tt = TREE_OPERAND (tt, 0);
9044 TREE_TYPE (v[i]) = TREE_TYPE (tt);
9045 layout_decl (v[i], 0);
9046 if (!processing_template_decl)
9048 SET_DECL_VALUE_EXPR (v[i], tt);
9049 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9051 i++;
9054 if (processing_template_decl)
9056 for (unsigned int i = 0; i < count; i++)
9057 if (!DECL_HAS_VALUE_EXPR_P (v[i]))
9059 tree a = build_nt (ARRAY_REF, decl, size_int (i),
9060 NULL_TREE, NULL_TREE);
9061 SET_DECL_VALUE_EXPR (v[i], a);
9062 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
9067 /* Returns a declaration for a VAR_DECL as if:
9069 extern "C" TYPE NAME;
9071 had been seen. Used to create compiler-generated global
9072 variables. */
9074 static tree
9075 declare_global_var (tree name, tree type)
9077 auto cookie = push_abi_namespace (global_namespace);
9078 tree decl = build_decl (input_location, VAR_DECL, name, type);
9079 TREE_PUBLIC (decl) = 1;
9080 DECL_EXTERNAL (decl) = 1;
9081 DECL_ARTIFICIAL (decl) = 1;
9082 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
9083 /* If the user has explicitly declared this variable (perhaps
9084 because the code we are compiling is part of a low-level runtime
9085 library), then it is possible that our declaration will be merged
9086 with theirs by pushdecl. */
9087 decl = pushdecl (decl);
9088 cp_finish_decl (decl, NULL_TREE, false, NULL_TREE, 0);
9089 pop_abi_namespace (cookie, global_namespace);
9091 return decl;
9094 /* Returns the type for the argument to "__cxa_atexit" (or "atexit",
9095 if "__cxa_atexit" is not being used) corresponding to the function
9096 to be called when the program exits. */
9098 static tree
9099 get_atexit_fn_ptr_type (void)
9101 tree fn_type;
9103 if (!atexit_fn_ptr_type_node)
9105 tree arg_type;
9106 if (flag_use_cxa_atexit
9107 && !targetm.cxx.use_atexit_for_cxa_atexit ())
9108 /* The parameter to "__cxa_atexit" is "void (*)(void *)". */
9109 arg_type = ptr_type_node;
9110 else
9111 /* The parameter to "atexit" is "void (*)(void)". */
9112 arg_type = NULL_TREE;
9114 fn_type = build_function_type_list (void_type_node,
9115 arg_type, NULL_TREE);
9116 atexit_fn_ptr_type_node = build_pointer_type (fn_type);
9119 return atexit_fn_ptr_type_node;
9122 /* Returns a pointer to the `atexit' function. Note that if
9123 FLAG_USE_CXA_ATEXIT is nonzero, then this will actually be the new
9124 `__cxa_atexit' function specified in the IA64 C++ ABI. */
9126 static tree
9127 get_atexit_node (void)
9129 tree atexit_fndecl;
9130 tree fn_type;
9131 tree fn_ptr_type;
9132 const char *name;
9133 bool use_aeabi_atexit;
9134 tree ctx = global_namespace;
9136 if (atexit_node)
9137 return atexit_node;
9139 if (flag_use_cxa_atexit && !targetm.cxx.use_atexit_for_cxa_atexit ())
9141 /* The declaration for `__cxa_atexit' is:
9143 int __cxa_atexit (void (*)(void *), void *, void *)
9145 We build up the argument types and then the function type
9146 itself. */
9147 tree argtype0, argtype1, argtype2;
9149 use_aeabi_atexit = targetm.cxx.use_aeabi_atexit ();
9150 /* First, build the pointer-to-function type for the first
9151 argument. */
9152 fn_ptr_type = get_atexit_fn_ptr_type ();
9153 /* Then, build the rest of the argument types. */
9154 argtype2 = ptr_type_node;
9155 if (use_aeabi_atexit)
9157 argtype1 = fn_ptr_type;
9158 argtype0 = ptr_type_node;
9160 else
9162 argtype1 = ptr_type_node;
9163 argtype0 = fn_ptr_type;
9165 /* And the final __cxa_atexit type. */
9166 fn_type = build_function_type_list (integer_type_node,
9167 argtype0, argtype1, argtype2,
9168 NULL_TREE);
9169 /* ... which needs noexcept. */
9170 fn_type = build_exception_variant (fn_type, noexcept_true_spec);
9171 if (use_aeabi_atexit)
9173 name = "__aeabi_atexit";
9174 push_to_top_level ();
9175 int n = push_namespace (get_identifier ("__aeabiv1"), false);
9176 ctx = current_namespace;
9177 while (n--)
9178 pop_namespace ();
9179 pop_from_top_level ();
9181 else
9183 name = "__cxa_atexit";
9184 ctx = abi_node;
9187 else
9189 /* The declaration for `atexit' is:
9191 int atexit (void (*)());
9193 We build up the argument types and then the function type
9194 itself. */
9195 fn_ptr_type = get_atexit_fn_ptr_type ();
9196 /* Build the final atexit type. */
9197 fn_type = build_function_type_list (integer_type_node,
9198 fn_ptr_type, NULL_TREE);
9199 /* ... which needs noexcept. */
9200 fn_type = build_exception_variant (fn_type, noexcept_true_spec);
9201 name = "atexit";
9204 /* Now, build the function declaration. */
9205 push_lang_context (lang_name_c);
9206 auto cookie = push_abi_namespace (ctx);
9207 atexit_fndecl = build_library_fn_ptr (name, fn_type, ECF_LEAF | ECF_NOTHROW);
9208 DECL_CONTEXT (atexit_fndecl) = FROB_CONTEXT (current_namespace);
9209 /* Install as hidden builtin so we're (a) more relaxed about
9210 exception spec matching and (b) will not give a confusing location
9211 in diagnostic and (c) won't magically appear in user-visible name
9212 lookups. */
9213 DECL_SOURCE_LOCATION (atexit_fndecl) = BUILTINS_LOCATION;
9214 atexit_fndecl = pushdecl (atexit_fndecl, /*hiding=*/true);
9215 pop_abi_namespace (cookie, ctx);
9216 mark_used (atexit_fndecl);
9217 pop_lang_context ();
9218 atexit_node = decay_conversion (atexit_fndecl, tf_warning_or_error);
9220 return atexit_node;
9223 /* Like get_atexit_node, but for thread-local cleanups. */
9225 static tree
9226 get_thread_atexit_node (void)
9228 /* The declaration for `__cxa_thread_atexit' is:
9230 int __cxa_thread_atexit (void (*)(void *), void *, void *) */
9231 tree fn_type = build_function_type_list (integer_type_node,
9232 get_atexit_fn_ptr_type (),
9233 ptr_type_node, ptr_type_node,
9234 NULL_TREE);
9236 /* Now, build the function declaration. */
9237 tree atexit_fndecl = build_library_fn_ptr ("__cxa_thread_atexit", fn_type,
9238 ECF_LEAF | ECF_NOTHROW);
9239 return decay_conversion (atexit_fndecl, tf_warning_or_error);
9242 /* Returns the __dso_handle VAR_DECL. */
9244 static tree
9245 get_dso_handle_node (void)
9247 if (dso_handle_node)
9248 return dso_handle_node;
9250 /* Declare the variable. */
9251 dso_handle_node = declare_global_var (get_identifier ("__dso_handle"),
9252 ptr_type_node);
9254 #ifdef HAVE_GAS_HIDDEN
9255 if (dso_handle_node != error_mark_node)
9257 DECL_VISIBILITY (dso_handle_node) = VISIBILITY_HIDDEN;
9258 DECL_VISIBILITY_SPECIFIED (dso_handle_node) = 1;
9260 #endif
9262 return dso_handle_node;
9265 /* Begin a new function with internal linkage whose job will be simply
9266 to destroy some particular variable. */
9268 static GTY(()) int start_cleanup_cnt;
9270 static tree
9271 start_cleanup_fn (void)
9273 char name[32];
9275 push_to_top_level ();
9277 /* No need to mangle this. */
9278 push_lang_context (lang_name_c);
9280 /* Build the name of the function. */
9281 sprintf (name, "__tcf_%d", start_cleanup_cnt++);
9282 /* Build the function declaration. */
9283 tree fntype = TREE_TYPE (get_atexit_fn_ptr_type ());
9284 tree fndecl = build_lang_decl (FUNCTION_DECL, get_identifier (name), fntype);
9285 DECL_CONTEXT (fndecl) = FROB_CONTEXT (current_namespace);
9286 /* It's a function with internal linkage, generated by the
9287 compiler. */
9288 TREE_PUBLIC (fndecl) = 0;
9289 DECL_ARTIFICIAL (fndecl) = 1;
9290 /* Make the function `inline' so that it is only emitted if it is
9291 actually needed. It is unlikely that it will be inlined, since
9292 it is only called via a function pointer, but we avoid unnecessary
9293 emissions this way. */
9294 DECL_DECLARED_INLINE_P (fndecl) = 1;
9295 DECL_INTERFACE_KNOWN (fndecl) = 1;
9296 if (flag_use_cxa_atexit && !targetm.cxx.use_atexit_for_cxa_atexit ())
9298 /* Build the parameter. */
9299 tree parmdecl = cp_build_parm_decl (fndecl, NULL_TREE, ptr_type_node);
9300 TREE_USED (parmdecl) = 1;
9301 DECL_READ_P (parmdecl) = 1;
9302 DECL_ARGUMENTS (fndecl) = parmdecl;
9305 fndecl = pushdecl (fndecl, /*hidden=*/true);
9306 start_preparsed_function (fndecl, NULL_TREE, SF_PRE_PARSED);
9308 pop_lang_context ();
9310 return current_function_decl;
9313 /* Finish the cleanup function begun by start_cleanup_fn. */
9315 static void
9316 end_cleanup_fn (void)
9318 expand_or_defer_fn (finish_function (/*inline_p=*/false));
9320 pop_from_top_level ();
9323 /* Generate code to handle the destruction of DECL, an object with
9324 static storage duration. */
9326 tree
9327 register_dtor_fn (tree decl)
9329 tree cleanup;
9330 tree addr;
9331 tree compound_stmt;
9332 tree fcall;
9333 tree type;
9334 bool ob_parm, dso_parm, use_dtor;
9335 tree arg0, arg1, arg2;
9336 tree atex_node;
9338 type = TREE_TYPE (decl);
9339 if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
9340 return void_node;
9342 if (decl_maybe_constant_destruction (decl, type)
9343 && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
9345 cxx_maybe_build_cleanup (decl, tf_warning_or_error);
9346 return void_node;
9349 /* If we're using "__cxa_atexit" (or "__cxa_thread_atexit" or
9350 "__aeabi_atexit"), and DECL is a class object, we can just pass the
9351 destructor to "__cxa_atexit"; we don't have to build a temporary
9352 function to do the cleanup. */
9353 dso_parm = (flag_use_cxa_atexit
9354 && !targetm.cxx.use_atexit_for_cxa_atexit ());
9355 ob_parm = (CP_DECL_THREAD_LOCAL_P (decl) || dso_parm);
9356 use_dtor = ob_parm && CLASS_TYPE_P (type);
9357 if (use_dtor)
9359 cleanup = get_class_binding (type, complete_dtor_identifier);
9361 /* Make sure it is accessible. */
9362 perform_or_defer_access_check (TYPE_BINFO (type), cleanup, cleanup,
9363 tf_warning_or_error);
9365 else
9367 /* Call build_cleanup before we enter the anonymous function so
9368 that any access checks will be done relative to the current
9369 scope, rather than the scope of the anonymous function. */
9370 build_cleanup (decl);
9372 /* Now start the function. */
9373 cleanup = start_cleanup_fn ();
9375 /* Now, recompute the cleanup. It may contain SAVE_EXPRs that refer
9376 to the original function, rather than the anonymous one. That
9377 will make the back end think that nested functions are in use,
9378 which causes confusion. */
9379 push_deferring_access_checks (dk_no_check);
9380 fcall = build_cleanup (decl);
9381 pop_deferring_access_checks ();
9383 /* Create the body of the anonymous function. */
9384 compound_stmt = begin_compound_stmt (BCS_FN_BODY);
9385 finish_expr_stmt (fcall);
9386 finish_compound_stmt (compound_stmt);
9387 end_cleanup_fn ();
9390 /* Call atexit with the cleanup function. */
9391 mark_used (cleanup);
9392 cleanup = build_address (cleanup);
9394 if (CP_DECL_THREAD_LOCAL_P (decl))
9395 atex_node = get_thread_atexit_node ();
9396 else
9397 atex_node = get_atexit_node ();
9399 if (use_dtor)
9401 /* We must convert CLEANUP to the type that "__cxa_atexit"
9402 expects. */
9403 cleanup = build_nop (get_atexit_fn_ptr_type (), cleanup);
9404 /* "__cxa_atexit" will pass the address of DECL to the
9405 cleanup function. */
9406 mark_used (decl);
9407 addr = build_address (decl);
9408 /* The declared type of the parameter to "__cxa_atexit" is
9409 "void *". For plain "T*", we could just let the
9410 machinery in cp_build_function_call convert it -- but if the
9411 type is "cv-qualified T *", then we need to convert it
9412 before passing it in, to avoid spurious errors. */
9413 addr = build_nop (ptr_type_node, addr);
9415 else
9416 /* Since the cleanup functions we build ignore the address
9417 they're given, there's no reason to pass the actual address
9418 in, and, in general, it's cheaper to pass NULL than any
9419 other value. */
9420 addr = null_pointer_node;
9422 if (dso_parm)
9423 arg2 = cp_build_addr_expr (get_dso_handle_node (),
9424 tf_warning_or_error);
9425 else if (ob_parm)
9426 /* Just pass NULL to the dso handle parm if we don't actually
9427 have a DSO handle on this target. */
9428 arg2 = null_pointer_node;
9429 else
9430 arg2 = NULL_TREE;
9432 if (ob_parm)
9434 if (!CP_DECL_THREAD_LOCAL_P (decl)
9435 && targetm.cxx.use_aeabi_atexit ())
9437 arg1 = cleanup;
9438 arg0 = addr;
9440 else
9442 arg1 = addr;
9443 arg0 = cleanup;
9446 else
9448 arg0 = cleanup;
9449 arg1 = NULL_TREE;
9451 return cp_build_function_call_nary (atex_node, tf_warning_or_error,
9452 arg0, arg1, arg2, NULL_TREE);
9455 /* DECL is a VAR_DECL with static storage duration. INIT, if present,
9456 is its initializer. Generate code to handle the construction
9457 and destruction of DECL. */
9459 static void
9460 expand_static_init (tree decl, tree init)
9462 gcc_assert (VAR_P (decl));
9463 gcc_assert (TREE_STATIC (decl));
9465 /* Some variables require no dynamic initialization. */
9466 if (decl_maybe_constant_destruction (decl, TREE_TYPE (decl)))
9468 /* Make sure the destructor is callable. */
9469 cxx_maybe_build_cleanup (decl, tf_warning_or_error);
9470 if (!init)
9471 return;
9474 if (CP_DECL_THREAD_LOCAL_P (decl) && DECL_GNU_TLS_P (decl)
9475 && !DECL_FUNCTION_SCOPE_P (decl))
9477 location_t dloc = DECL_SOURCE_LOCATION (decl);
9478 if (init)
9479 error_at (dloc, "non-local variable %qD declared %<__thread%> "
9480 "needs dynamic initialization", decl);
9481 else
9482 error_at (dloc, "non-local variable %qD declared %<__thread%> "
9483 "has a non-trivial destructor", decl);
9484 static bool informed;
9485 if (!informed)
9487 inform (dloc, "C++11 %<thread_local%> allows dynamic "
9488 "initialization and destruction");
9489 informed = true;
9491 return;
9494 if (DECL_FUNCTION_SCOPE_P (decl))
9496 /* Emit code to perform this initialization but once. */
9497 tree if_stmt = NULL_TREE, inner_if_stmt = NULL_TREE;
9498 tree then_clause = NULL_TREE, inner_then_clause = NULL_TREE;
9499 tree guard, guard_addr;
9500 tree flag, begin;
9501 /* We don't need thread-safety code for thread-local vars. */
9502 bool thread_guard = (flag_threadsafe_statics
9503 && !CP_DECL_THREAD_LOCAL_P (decl));
9505 /* Emit code to perform this initialization but once. This code
9506 looks like:
9508 static <type> guard;
9509 if (!__atomic_load (guard.first_byte)) {
9510 if (__cxa_guard_acquire (&guard)) {
9511 bool flag = false;
9512 try {
9513 // Do initialization.
9514 flag = true; __cxa_guard_release (&guard);
9515 // Register variable for destruction at end of program.
9516 } catch {
9517 if (!flag) __cxa_guard_abort (&guard);
9522 Note that the `flag' variable is only set to 1 *after* the
9523 initialization is complete. This ensures that an exception,
9524 thrown during the construction, will cause the variable to
9525 reinitialized when we pass through this code again, as per:
9527 [stmt.dcl]
9529 If the initialization exits by throwing an exception, the
9530 initialization is not complete, so it will be tried again
9531 the next time control enters the declaration.
9533 This process should be thread-safe, too; multiple threads
9534 should not be able to initialize the variable more than
9535 once. */
9537 /* Create the guard variable. */
9538 guard = get_guard (decl);
9540 /* Begin the conditional initialization. */
9541 if_stmt = begin_if_stmt ();
9543 finish_if_stmt_cond (get_guard_cond (guard, thread_guard), if_stmt);
9544 then_clause = begin_compound_stmt (BCS_NO_SCOPE);
9546 if (thread_guard)
9548 tree vfntype = NULL_TREE;
9549 tree acquire_name, release_name, abort_name;
9550 tree acquire_fn, release_fn, abort_fn;
9551 guard_addr = build_address (guard);
9553 acquire_name = get_identifier ("__cxa_guard_acquire");
9554 release_name = get_identifier ("__cxa_guard_release");
9555 abort_name = get_identifier ("__cxa_guard_abort");
9556 acquire_fn = get_global_binding (acquire_name);
9557 release_fn = get_global_binding (release_name);
9558 abort_fn = get_global_binding (abort_name);
9559 if (!acquire_fn)
9560 acquire_fn = push_library_fn
9561 (acquire_name, build_function_type_list (integer_type_node,
9562 TREE_TYPE (guard_addr),
9563 NULL_TREE),
9564 NULL_TREE, ECF_NOTHROW);
9565 if (!release_fn || !abort_fn)
9566 vfntype = build_function_type_list (void_type_node,
9567 TREE_TYPE (guard_addr),
9568 NULL_TREE);
9569 if (!release_fn)
9570 release_fn = push_library_fn (release_name, vfntype, NULL_TREE,
9571 ECF_NOTHROW);
9572 if (!abort_fn)
9573 abort_fn = push_library_fn (abort_name, vfntype, NULL_TREE,
9574 ECF_NOTHROW | ECF_LEAF);
9576 inner_if_stmt = begin_if_stmt ();
9577 finish_if_stmt_cond (build_call_n (acquire_fn, 1, guard_addr),
9578 inner_if_stmt);
9580 inner_then_clause = begin_compound_stmt (BCS_NO_SCOPE);
9581 begin = get_target_expr (boolean_false_node);
9582 flag = TARGET_EXPR_SLOT (begin);
9584 TARGET_EXPR_CLEANUP (begin)
9585 = build3 (COND_EXPR, void_type_node, flag,
9586 void_node,
9587 build_call_n (abort_fn, 1, guard_addr));
9588 CLEANUP_EH_ONLY (begin) = 1;
9590 /* Do the initialization itself. */
9591 init = add_stmt_to_compound (begin, init);
9592 init = add_stmt_to_compound (init,
9593 build2 (MODIFY_EXPR, void_type_node,
9594 flag, boolean_true_node));
9596 /* Use atexit to register a function for destroying this static
9597 variable. Do this before calling __cxa_guard_release. */
9598 init = add_stmt_to_compound (init, register_dtor_fn (decl));
9600 init = add_stmt_to_compound (init, build_call_n (release_fn, 1,
9601 guard_addr));
9603 else
9605 init = add_stmt_to_compound (init, set_guard (guard));
9607 /* Use atexit to register a function for destroying this static
9608 variable. */
9609 init = add_stmt_to_compound (init, register_dtor_fn (decl));
9612 finish_expr_stmt (init);
9614 if (thread_guard)
9616 finish_compound_stmt (inner_then_clause);
9617 finish_then_clause (inner_if_stmt);
9618 finish_if_stmt (inner_if_stmt);
9621 finish_compound_stmt (then_clause);
9622 finish_then_clause (if_stmt);
9623 finish_if_stmt (if_stmt);
9625 else if (CP_DECL_THREAD_LOCAL_P (decl))
9626 tls_aggregates = tree_cons (init, decl, tls_aggregates);
9627 else
9628 static_aggregates = tree_cons (init, decl, static_aggregates);
9632 /* Make TYPE a complete type based on INITIAL_VALUE.
9633 Return 0 if successful, 1 if INITIAL_VALUE can't be deciphered,
9634 2 if there was no information (in which case assume 0 if DO_DEFAULT),
9635 3 if the initializer list is empty (in pedantic mode). */
9638 cp_complete_array_type (tree *ptype, tree initial_value, bool do_default)
9640 int failure;
9641 tree type, elt_type;
9643 /* Don't get confused by a CONSTRUCTOR for some other type. */
9644 if (initial_value && TREE_CODE (initial_value) == CONSTRUCTOR
9645 && !BRACE_ENCLOSED_INITIALIZER_P (initial_value)
9646 && TREE_CODE (TREE_TYPE (initial_value)) != ARRAY_TYPE)
9647 return 1;
9649 if (initial_value)
9651 /* An array of character type can be initialized from a
9652 brace-enclosed string constant so call reshape_init to
9653 remove the optional braces from a braced string literal. */
9654 if (char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (*ptype)))
9655 && BRACE_ENCLOSED_INITIALIZER_P (initial_value))
9656 initial_value = reshape_init (*ptype, initial_value,
9657 tf_warning_or_error);
9659 /* If any of the elements are parameter packs, we can't actually
9660 complete this type now because the array size is dependent. */
9661 if (TREE_CODE (initial_value) == CONSTRUCTOR)
9662 for (auto &e: CONSTRUCTOR_ELTS (initial_value))
9663 if (PACK_EXPANSION_P (e.value))
9664 return 0;
9667 failure = complete_array_type (ptype, initial_value, do_default);
9669 /* We can create the array before the element type is complete, which
9670 means that we didn't have these two bits set in the original type
9671 either. In completing the type, we are expected to propagate these
9672 bits. See also complete_type which does the same thing for arrays
9673 of fixed size. */
9674 type = *ptype;
9675 if (type != error_mark_node && TYPE_DOMAIN (type))
9677 elt_type = TREE_TYPE (type);
9678 TYPE_NEEDS_CONSTRUCTING (type) = TYPE_NEEDS_CONSTRUCTING (elt_type);
9679 TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
9680 = TYPE_HAS_NONTRIVIAL_DESTRUCTOR (elt_type);
9683 return failure;
9686 /* As above, but either give an error or reject zero-size arrays, depending
9687 on COMPLAIN. */
9690 cp_complete_array_type_or_error (tree *ptype, tree initial_value,
9691 bool do_default, tsubst_flags_t complain)
9693 int failure;
9694 bool sfinae = !(complain & tf_error);
9695 /* In SFINAE context we can't be lenient about zero-size arrays. */
9696 if (sfinae)
9697 ++pedantic;
9698 failure = cp_complete_array_type (ptype, initial_value, do_default);
9699 if (sfinae)
9700 --pedantic;
9701 if (failure)
9703 if (sfinae)
9704 /* Not an error. */;
9705 else if (failure == 1)
9706 error ("initializer fails to determine size of %qT", *ptype);
9707 else if (failure == 2)
9709 if (do_default)
9710 error ("array size missing in %qT", *ptype);
9712 else if (failure == 3)
9713 error ("zero-size array %qT", *ptype);
9714 *ptype = error_mark_node;
9716 return failure;
9719 /* Return zero if something is declared to be a member of type
9720 CTYPE when in the context of CUR_TYPE. STRING is the error
9721 message to print in that case. Otherwise, quietly return 1. */
9723 static int
9724 member_function_or_else (tree ctype, tree cur_type, enum overload_flags flags)
9726 if (ctype && ctype != cur_type)
9728 if (flags == DTOR_FLAG)
9729 error ("destructor for alien class %qT cannot be a member", ctype);
9730 else
9731 error ("constructor for alien class %qT cannot be a member", ctype);
9732 return 0;
9734 return 1;
9737 /* Subroutine of `grokdeclarator'. */
9739 /* Generate errors possibly applicable for a given set of specifiers.
9740 This is for ARM $7.1.2. */
9742 static void
9743 bad_specifiers (tree object,
9744 enum bad_spec_place type,
9745 int virtualp,
9746 int quals,
9747 int inlinep,
9748 int friendp,
9749 int raises,
9750 const location_t* locations)
9752 switch (type)
9754 case BSP_VAR:
9755 if (virtualp)
9756 error_at (locations[ds_virtual],
9757 "%qD declared as a %<virtual%> variable", object);
9758 if (quals)
9759 error ("%<const%> and %<volatile%> function specifiers on "
9760 "%qD invalid in variable declaration", object);
9761 break;
9762 case BSP_PARM:
9763 if (virtualp)
9764 error_at (locations[ds_virtual],
9765 "%qD declared as a %<virtual%> parameter", object);
9766 if (inlinep)
9767 error_at (locations[ds_inline],
9768 "%qD declared as an %<inline%> parameter", object);
9769 if (quals)
9770 error ("%<const%> and %<volatile%> function specifiers on "
9771 "%qD invalid in parameter declaration", object);
9772 break;
9773 case BSP_TYPE:
9774 if (virtualp)
9775 error_at (locations[ds_virtual],
9776 "%qD declared as a %<virtual%> type", object);
9777 if (inlinep)
9778 error_at (locations[ds_inline],
9779 "%qD declared as an %<inline%> type", object);
9780 if (quals)
9781 error ("%<const%> and %<volatile%> function specifiers on "
9782 "%qD invalid in type declaration", object);
9783 break;
9784 case BSP_FIELD:
9785 if (virtualp)
9786 error_at (locations[ds_virtual],
9787 "%qD declared as a %<virtual%> field", object);
9788 if (inlinep)
9789 error_at (locations[ds_inline],
9790 "%qD declared as an %<inline%> field", object);
9791 if (quals)
9792 error ("%<const%> and %<volatile%> function specifiers on "
9793 "%qD invalid in field declaration", object);
9794 break;
9795 default:
9796 gcc_unreachable();
9798 if (friendp)
9799 error ("%q+D declared as a friend", object);
9800 if (raises
9801 && !flag_noexcept_type
9802 && (TREE_CODE (object) == TYPE_DECL
9803 || (!TYPE_PTRFN_P (TREE_TYPE (object))
9804 && !TYPE_REFFN_P (TREE_TYPE (object))
9805 && !TYPE_PTRMEMFUNC_P (TREE_TYPE (object)))))
9806 error ("%q+D declared with an exception specification", object);
9809 /* DECL is a member function or static data member and is presently
9810 being defined. Check that the definition is taking place in a
9811 valid namespace. */
9813 static void
9814 check_class_member_definition_namespace (tree decl)
9816 /* These checks only apply to member functions and static data
9817 members. */
9818 gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
9819 /* We check for problems with specializations in pt.cc in
9820 check_specialization_namespace, where we can issue better
9821 diagnostics. */
9822 if (processing_specialization)
9823 return;
9824 /* We check this in check_explicit_instantiation_namespace. */
9825 if (processing_explicit_instantiation)
9826 return;
9827 /* [class.mfct]
9829 A member function definition that appears outside of the
9830 class definition shall appear in a namespace scope enclosing
9831 the class definition.
9833 [class.static.data]
9835 The definition for a static data member shall appear in a
9836 namespace scope enclosing the member's class definition. */
9837 if (!is_ancestor (current_namespace, DECL_CONTEXT (decl)))
9838 permerror (input_location, "definition of %qD is not in namespace enclosing %qT",
9839 decl, DECL_CONTEXT (decl));
9842 /* Build a PARM_DECL for the "this" parameter of FN. TYPE is the
9843 METHOD_TYPE for a non-static member function; QUALS are the
9844 cv-qualifiers that apply to the function. */
9846 tree
9847 build_this_parm (tree fn, tree type, cp_cv_quals quals)
9849 tree this_type;
9850 tree qual_type;
9851 tree parm;
9852 cp_cv_quals this_quals;
9854 if (CLASS_TYPE_P (type))
9856 this_type
9857 = cp_build_qualified_type (type, quals & ~TYPE_QUAL_RESTRICT);
9858 this_type = build_pointer_type (this_type);
9860 else
9861 this_type = type_of_this_parm (type);
9862 /* The `this' parameter is implicitly `const'; it cannot be
9863 assigned to. */
9864 this_quals = (quals & TYPE_QUAL_RESTRICT) | TYPE_QUAL_CONST;
9865 qual_type = cp_build_qualified_type (this_type, this_quals);
9866 parm = build_artificial_parm (fn, this_identifier, qual_type);
9867 cp_apply_type_quals_to_decl (this_quals, parm);
9868 return parm;
9871 /* DECL is a static member function. Complain if it was declared
9872 with function-cv-quals. */
9874 static void
9875 check_static_quals (tree decl, cp_cv_quals quals)
9877 if (quals != TYPE_UNQUALIFIED)
9878 error ("static member function %q#D declared with type qualifiers",
9879 decl);
9882 // Check that FN takes no arguments and returns bool.
9883 static void
9884 check_concept_fn (tree fn)
9886 // A constraint is nullary.
9887 if (DECL_ARGUMENTS (fn))
9888 error_at (DECL_SOURCE_LOCATION (fn),
9889 "concept %q#D declared with function parameters", fn);
9891 // The declared return type of the concept shall be bool, and
9892 // it shall not be deduced from it definition.
9893 tree type = TREE_TYPE (TREE_TYPE (fn));
9894 if (is_auto (type))
9895 error_at (DECL_SOURCE_LOCATION (fn),
9896 "concept %q#D declared with a deduced return type", fn);
9897 else if (type != boolean_type_node)
9898 error_at (DECL_SOURCE_LOCATION (fn),
9899 "concept %q#D with non-%<bool%> return type %qT", fn, type);
9902 /* Helper function. Replace the temporary this parameter injected
9903 during cp_finish_omp_declare_simd with the real this parameter. */
9905 static tree
9906 declare_simd_adjust_this (tree *tp, int *walk_subtrees, void *data)
9908 tree this_parm = (tree) data;
9909 if (TREE_CODE (*tp) == PARM_DECL
9910 && DECL_NAME (*tp) == this_identifier
9911 && *tp != this_parm)
9912 *tp = this_parm;
9913 else if (TYPE_P (*tp))
9914 *walk_subtrees = 0;
9915 return NULL_TREE;
9918 /* CTYPE is class type, or null if non-class.
9919 TYPE is type this FUNCTION_DECL should have, either FUNCTION_TYPE
9920 or METHOD_TYPE.
9921 DECLARATOR is the function's name.
9922 PARMS is a chain of PARM_DECLs for the function.
9923 VIRTUALP is truthvalue of whether the function is virtual or not.
9924 FLAGS are to be passed through to `grokclassfn'.
9925 QUALS are qualifiers indicating whether the function is `const'
9926 or `volatile'.
9927 RAISES is a list of exceptions that this function can raise.
9928 CHECK is 1 if we must find this method in CTYPE, 0 if we should
9929 not look, and -1 if we should not call `grokclassfn' at all.
9931 SFK is the kind of special function (if any) for the new function.
9933 Returns `NULL_TREE' if something goes wrong, after issuing
9934 applicable error messages. */
9936 static tree
9937 grokfndecl (tree ctype,
9938 tree type,
9939 tree declarator,
9940 tree parms,
9941 tree orig_declarator,
9942 const cp_decl_specifier_seq *declspecs,
9943 tree decl_reqs,
9944 int virtualp,
9945 enum overload_flags flags,
9946 cp_cv_quals quals,
9947 cp_ref_qualifier rqual,
9948 tree raises,
9949 int check,
9950 int friendp,
9951 int publicp,
9952 int inlinep,
9953 bool deletedp,
9954 special_function_kind sfk,
9955 bool funcdef_flag,
9956 bool late_return_type_p,
9957 int template_count,
9958 tree in_namespace,
9959 tree* attrlist,
9960 location_t location)
9962 tree decl;
9963 int staticp = ctype && TREE_CODE (type) == FUNCTION_TYPE;
9964 tree t;
9966 if (location == UNKNOWN_LOCATION)
9967 location = input_location;
9969 /* Was the concept specifier present? */
9970 bool concept_p = inlinep & 4;
9972 /* Concept declarations must have a corresponding definition. */
9973 if (concept_p && !funcdef_flag)
9975 error_at (location, "concept %qD has no definition", declarator);
9976 return NULL_TREE;
9979 type = build_cp_fntype_variant (type, rqual, raises, late_return_type_p);
9981 decl = build_lang_decl_loc (location, FUNCTION_DECL, declarator, type);
9983 /* Set the constraints on the declaration. */
9984 if (flag_concepts)
9986 tree tmpl_reqs = NULL_TREE;
9987 tree ctx = friendp ? current_class_type : ctype;
9988 bool block_local = TREE_CODE (current_scope ()) == FUNCTION_DECL;
9989 bool memtmpl = (!block_local
9990 && (current_template_depth
9991 > template_class_depth (ctx)));
9992 if (memtmpl)
9994 if (!current_template_parms)
9995 /* If there are no template parameters, something must have
9996 gone wrong. */
9997 gcc_assert (seen_error ());
9998 else
9999 tmpl_reqs = TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
10001 tree ci = build_constraints (tmpl_reqs, decl_reqs);
10002 if (concept_p && ci)
10004 error_at (location, "a function concept cannot be constrained");
10005 ci = NULL_TREE;
10007 /* C++20 CA378: Remove non-templated constrained functions. */
10008 if (ci
10009 && (block_local
10010 || (!flag_concepts_ts
10011 && (!processing_template_decl
10012 || (friendp && !memtmpl && !funcdef_flag)))))
10014 error_at (location, "constraints on a non-templated function");
10015 ci = NULL_TREE;
10017 set_constraints (decl, ci);
10020 if (TREE_CODE (type) == METHOD_TYPE)
10022 tree parm = build_this_parm (decl, type, quals);
10023 DECL_CHAIN (parm) = parms;
10024 parms = parm;
10026 /* Allocate space to hold the vptr bit if needed. */
10027 SET_DECL_ALIGN (decl, MINIMUM_METHOD_BOUNDARY);
10030 DECL_ARGUMENTS (decl) = parms;
10031 for (t = parms; t; t = DECL_CHAIN (t))
10032 DECL_CONTEXT (t) = decl;
10034 /* Propagate volatile out from type to decl. */
10035 if (TYPE_VOLATILE (type))
10036 TREE_THIS_VOLATILE (decl) = 1;
10038 /* Setup decl according to sfk. */
10039 switch (sfk)
10041 case sfk_constructor:
10042 case sfk_copy_constructor:
10043 case sfk_move_constructor:
10044 DECL_CXX_CONSTRUCTOR_P (decl) = 1;
10045 DECL_NAME (decl) = ctor_identifier;
10046 break;
10047 case sfk_destructor:
10048 DECL_CXX_DESTRUCTOR_P (decl) = 1;
10049 DECL_NAME (decl) = dtor_identifier;
10050 break;
10051 default:
10052 break;
10055 if (friendp && TREE_CODE (orig_declarator) == TEMPLATE_ID_EXPR)
10057 if (funcdef_flag)
10058 error_at (location,
10059 "defining explicit specialization %qD in friend declaration",
10060 orig_declarator);
10061 else
10063 tree fns = TREE_OPERAND (orig_declarator, 0);
10064 tree args = TREE_OPERAND (orig_declarator, 1);
10066 if (PROCESSING_REAL_TEMPLATE_DECL_P ())
10068 /* Something like `template <class T> friend void f<T>()'. */
10069 error_at (location,
10070 "invalid use of template-id %qD in declaration "
10071 "of primary template",
10072 orig_declarator);
10073 return NULL_TREE;
10077 /* A friend declaration of the form friend void f<>(). Record
10078 the information in the TEMPLATE_ID_EXPR. */
10079 SET_DECL_IMPLICIT_INSTANTIATION (decl);
10081 gcc_assert (identifier_p (fns) || OVL_P (fns));
10082 DECL_TEMPLATE_INFO (decl) = build_template_info (fns, args);
10084 for (t = TYPE_ARG_TYPES (TREE_TYPE (decl)); t; t = TREE_CHAIN (t))
10085 if (TREE_PURPOSE (t)
10086 && TREE_CODE (TREE_PURPOSE (t)) == DEFERRED_PARSE)
10088 error_at (defparse_location (TREE_PURPOSE (t)),
10089 "default arguments are not allowed in declaration "
10090 "of friend template specialization %qD",
10091 decl);
10092 return NULL_TREE;
10095 if (inlinep & 1)
10097 error_at (declspecs->locations[ds_inline],
10098 "%<inline%> is not allowed in declaration of friend "
10099 "template specialization %qD",
10100 decl);
10101 return NULL_TREE;
10106 /* C++17 11.3.6/4: "If a friend declaration specifies a default argument
10107 expression, that declaration shall be a definition..." */
10108 if (friendp && !funcdef_flag)
10110 for (tree t = FUNCTION_FIRST_USER_PARMTYPE (decl);
10111 t && t != void_list_node; t = TREE_CHAIN (t))
10112 if (TREE_PURPOSE (t))
10114 permerror (DECL_SOURCE_LOCATION (decl),
10115 "friend declaration of %qD specifies default "
10116 "arguments and isn%'t a definition", decl);
10117 break;
10121 /* If this decl has namespace scope, set that up. */
10122 if (in_namespace)
10123 set_decl_namespace (decl, in_namespace, friendp);
10124 else if (ctype)
10125 DECL_CONTEXT (decl) = ctype;
10126 else
10127 DECL_CONTEXT (decl) = FROB_CONTEXT (current_decl_namespace ());
10129 /* `main' and builtins have implicit 'C' linkage. */
10130 if (ctype == NULL_TREE
10131 && DECL_FILE_SCOPE_P (decl)
10132 && current_lang_name == lang_name_cplusplus
10133 && (MAIN_NAME_P (declarator)
10134 || (IDENTIFIER_LENGTH (declarator) > 10
10135 && IDENTIFIER_POINTER (declarator)[0] == '_'
10136 && IDENTIFIER_POINTER (declarator)[1] == '_'
10137 && startswith (IDENTIFIER_POINTER (declarator) + 2,
10138 "builtin_"))
10139 || (targetcm.cxx_implicit_extern_c
10140 && (targetcm.cxx_implicit_extern_c
10141 (IDENTIFIER_POINTER (declarator))))))
10142 SET_DECL_LANGUAGE (decl, lang_c);
10144 /* Should probably propagate const out from type to decl I bet (mrs). */
10145 if (staticp)
10147 DECL_STATIC_FUNCTION_P (decl) = 1;
10148 DECL_CONTEXT (decl) = ctype;
10151 if (deletedp)
10152 DECL_DELETED_FN (decl) = 1;
10154 if (ctype && funcdef_flag)
10155 check_class_member_definition_namespace (decl);
10157 if (ctype == NULL_TREE && DECL_MAIN_P (decl))
10159 if (PROCESSING_REAL_TEMPLATE_DECL_P())
10160 error_at (location, "cannot declare %<::main%> to be a template");
10161 if (inlinep & 1)
10162 error_at (declspecs->locations[ds_inline],
10163 "cannot declare %<::main%> to be inline");
10164 if (inlinep & 2)
10165 error_at (declspecs->locations[ds_constexpr],
10166 "cannot declare %<::main%> to be %qs", "constexpr");
10167 if (inlinep & 8)
10168 error_at (declspecs->locations[ds_consteval],
10169 "cannot declare %<::main%> to be %qs", "consteval");
10170 if (!publicp)
10171 error_at (location, "cannot declare %<::main%> to be static");
10172 inlinep = 0;
10173 publicp = 1;
10176 /* Members of anonymous types and local classes have no linkage; make
10177 them internal. If a typedef is made later, this will be changed. */
10178 if (ctype && (!TREE_PUBLIC (TYPE_MAIN_DECL (ctype))
10179 || decl_function_context (TYPE_MAIN_DECL (ctype))))
10180 publicp = 0;
10182 if (publicp && cxx_dialect == cxx98)
10184 /* [basic.link]: A name with no linkage (notably, the name of a class
10185 or enumeration declared in a local scope) shall not be used to
10186 declare an entity with linkage.
10188 DR 757 relaxes this restriction for C++0x. */
10189 no_linkage_error (decl);
10192 TREE_PUBLIC (decl) = publicp;
10193 if (! publicp)
10195 DECL_INTERFACE_KNOWN (decl) = 1;
10196 DECL_NOT_REALLY_EXTERN (decl) = 1;
10199 /* If the declaration was declared inline, mark it as such. */
10200 if (inlinep)
10202 DECL_DECLARED_INLINE_P (decl) = 1;
10203 if (publicp)
10204 DECL_COMDAT (decl) = 1;
10206 if (inlinep & 2)
10207 DECL_DECLARED_CONSTEXPR_P (decl) = true;
10208 else if (inlinep & 8)
10210 DECL_DECLARED_CONSTEXPR_P (decl) = true;
10211 SET_DECL_IMMEDIATE_FUNCTION_P (decl);
10214 // If the concept declaration specifier was found, check
10215 // that the declaration satisfies the necessary requirements.
10216 if (concept_p)
10218 DECL_DECLARED_CONCEPT_P (decl) = true;
10219 check_concept_fn (decl);
10222 DECL_EXTERNAL (decl) = 1;
10223 if (TREE_CODE (type) == FUNCTION_TYPE)
10225 if (quals || rqual)
10226 TREE_TYPE (decl) = apply_memfn_quals (TREE_TYPE (decl),
10227 TYPE_UNQUALIFIED,
10228 REF_QUAL_NONE);
10230 if (quals)
10232 error (ctype
10233 ? G_("static member function %qD cannot have cv-qualifier")
10234 : G_("non-member function %qD cannot have cv-qualifier"),
10235 decl);
10236 quals = TYPE_UNQUALIFIED;
10239 if (rqual)
10241 error (ctype
10242 ? G_("static member function %qD cannot have ref-qualifier")
10243 : G_("non-member function %qD cannot have ref-qualifier"),
10244 decl);
10245 rqual = REF_QUAL_NONE;
10249 if (deduction_guide_p (decl))
10251 tree type = TREE_TYPE (DECL_NAME (decl));
10252 if (in_namespace == NULL_TREE
10253 && CP_DECL_CONTEXT (decl) != CP_TYPE_CONTEXT (type))
10255 error_at (location, "deduction guide %qD must be declared in the "
10256 "same scope as %qT", decl, type);
10257 inform (location_of (type), " declared here");
10258 return NULL_TREE;
10260 if (DECL_CLASS_SCOPE_P (decl)
10261 && current_access_specifier != declared_access (TYPE_NAME (type)))
10263 error_at (location, "deduction guide %qD must have the same access "
10264 "as %qT", decl, type);
10265 inform (location_of (type), " declared here");
10267 if (funcdef_flag)
10268 error_at (location,
10269 "deduction guide %qD must not have a function body", decl);
10271 else if (IDENTIFIER_ANY_OP_P (DECL_NAME (decl))
10272 && !grok_op_properties (decl, /*complain=*/true))
10273 return NULL_TREE;
10274 else if (UDLIT_OPER_P (DECL_NAME (decl)))
10276 bool long_long_unsigned_p;
10277 bool long_double_p;
10278 const char *suffix = NULL;
10279 /* [over.literal]/6: Literal operators shall not have C linkage. */
10280 if (DECL_LANGUAGE (decl) == lang_c)
10282 error_at (location, "literal operator with C linkage");
10283 maybe_show_extern_c_location ();
10284 return NULL_TREE;
10287 if (DECL_NAMESPACE_SCOPE_P (decl))
10289 if (!check_literal_operator_args (decl, &long_long_unsigned_p,
10290 &long_double_p))
10292 error_at (location, "%qD has invalid argument list", decl);
10293 return NULL_TREE;
10296 suffix = UDLIT_OP_SUFFIX (DECL_NAME (decl));
10297 if (long_long_unsigned_p)
10299 if (cpp_interpret_int_suffix (parse_in, suffix, strlen (suffix)))
10300 warning_at (location, 0, "integer suffix %qs"
10301 " shadowed by implementation", suffix);
10303 else if (long_double_p)
10305 if (cpp_interpret_float_suffix (parse_in, suffix, strlen (suffix)))
10306 warning_at (location, 0, "floating-point suffix %qs"
10307 " shadowed by implementation", suffix);
10309 /* 17.6.3.3.5 */
10310 if (suffix[0] != '_'
10311 && !current_function_decl && !(friendp && !funcdef_flag))
10312 warning_at (location, OPT_Wliteral_suffix,
10313 "literal operator suffixes not preceded by %<_%>"
10314 " are reserved for future standardization");
10316 else
10318 error_at (location, "%qD must be a non-member function", decl);
10319 return NULL_TREE;
10323 if (funcdef_flag)
10324 /* Make the init_value nonzero so pushdecl knows this is not
10325 tentative. error_mark_node is replaced later with the BLOCK. */
10326 DECL_INITIAL (decl) = error_mark_node;
10328 if (TYPE_NOTHROW_P (type) || nothrow_libfn_p (decl))
10329 TREE_NOTHROW (decl) = 1;
10331 if (flag_openmp || flag_openmp_simd)
10333 /* Adjust "omp declare simd" attributes. */
10334 tree ods = lookup_attribute ("omp declare simd", *attrlist);
10335 if (ods)
10337 tree attr;
10338 for (attr = ods; attr;
10339 attr = lookup_attribute ("omp declare simd", TREE_CHAIN (attr)))
10341 if (TREE_CODE (type) == METHOD_TYPE)
10342 walk_tree (&TREE_VALUE (attr), declare_simd_adjust_this,
10343 DECL_ARGUMENTS (decl), NULL);
10344 if (TREE_VALUE (attr) != NULL_TREE)
10346 tree cl = TREE_VALUE (TREE_VALUE (attr));
10347 cl = c_omp_declare_simd_clauses_to_numbers
10348 (DECL_ARGUMENTS (decl), cl);
10349 if (cl)
10350 TREE_VALUE (TREE_VALUE (attr)) = cl;
10351 else
10352 TREE_VALUE (attr) = NULL_TREE;
10358 /* Caller will do the rest of this. */
10359 if (check < 0)
10360 return decl;
10362 if (ctype != NULL_TREE)
10363 grokclassfn (ctype, decl, flags);
10365 /* 12.4/3 */
10366 if (cxx_dialect >= cxx11
10367 && DECL_DESTRUCTOR_P (decl)
10368 && !TYPE_BEING_DEFINED (DECL_CONTEXT (decl))
10369 && !processing_template_decl)
10370 deduce_noexcept_on_destructor (decl);
10372 set_originating_module (decl);
10374 decl = check_explicit_specialization (orig_declarator, decl,
10375 template_count,
10376 2 * funcdef_flag +
10377 4 * (friendp != 0) +
10378 8 * concept_p,
10379 *attrlist);
10380 if (decl == error_mark_node)
10381 return NULL_TREE;
10383 if (DECL_STATIC_FUNCTION_P (decl))
10384 check_static_quals (decl, quals);
10386 if (attrlist)
10388 cplus_decl_attributes (&decl, *attrlist, 0);
10389 *attrlist = NULL_TREE;
10392 /* Check main's type after attributes have been applied. */
10393 if (ctype == NULL_TREE && DECL_MAIN_P (decl))
10395 if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
10396 integer_type_node))
10398 tree oldtypeargs = TYPE_ARG_TYPES (TREE_TYPE (decl));
10399 tree newtype;
10400 error_at (declspecs->locations[ds_type_spec],
10401 "%<::main%> must return %<int%>");
10402 newtype = build_function_type (integer_type_node, oldtypeargs);
10403 TREE_TYPE (decl) = newtype;
10405 if (warn_main)
10406 check_main_parameter_types (decl);
10409 if (ctype != NULL_TREE && check)
10411 tree old_decl = check_classfn (ctype, decl,
10412 (current_template_depth
10413 > template_class_depth (ctype))
10414 ? current_template_parms
10415 : NULL_TREE);
10417 if (old_decl == error_mark_node)
10418 return NULL_TREE;
10420 if (old_decl)
10422 tree ok;
10423 tree pushed_scope;
10425 if (TREE_CODE (old_decl) == TEMPLATE_DECL)
10426 /* Because grokfndecl is always supposed to return a
10427 FUNCTION_DECL, we pull out the DECL_TEMPLATE_RESULT
10428 here. We depend on our callers to figure out that its
10429 really a template that's being returned. */
10430 old_decl = DECL_TEMPLATE_RESULT (old_decl);
10432 if (DECL_STATIC_FUNCTION_P (old_decl)
10433 && TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
10435 /* Remove the `this' parm added by grokclassfn. */
10436 revert_static_member_fn (decl);
10437 check_static_quals (decl, quals);
10439 if (DECL_ARTIFICIAL (old_decl))
10441 error ("definition of implicitly-declared %qD", old_decl);
10442 return NULL_TREE;
10444 else if (DECL_DEFAULTED_FN (old_decl))
10446 error ("definition of explicitly-defaulted %q+D", decl);
10447 inform (DECL_SOURCE_LOCATION (old_decl),
10448 "%q#D explicitly defaulted here", old_decl);
10449 return NULL_TREE;
10452 /* Since we've smashed OLD_DECL to its
10453 DECL_TEMPLATE_RESULT, we must do the same to DECL. */
10454 if (TREE_CODE (decl) == TEMPLATE_DECL)
10455 decl = DECL_TEMPLATE_RESULT (decl);
10457 /* Attempt to merge the declarations. This can fail, in
10458 the case of some invalid specialization declarations. */
10459 pushed_scope = push_scope (ctype);
10460 ok = duplicate_decls (decl, old_decl);
10461 if (pushed_scope)
10462 pop_scope (pushed_scope);
10463 if (!ok)
10465 error ("no %q#D member function declared in class %qT",
10466 decl, ctype);
10467 return NULL_TREE;
10469 if (ok == error_mark_node)
10470 return NULL_TREE;
10471 return old_decl;
10475 if (DECL_CONSTRUCTOR_P (decl) && !grok_ctor_properties (ctype, decl))
10476 return NULL_TREE;
10478 if (ctype == NULL_TREE || check)
10479 return decl;
10481 if (virtualp)
10482 DECL_VIRTUAL_P (decl) = 1;
10484 return decl;
10487 /* decl is a FUNCTION_DECL.
10488 specifiers are the parsed virt-specifiers.
10490 Set flags to reflect the virt-specifiers.
10492 Returns decl. */
10494 static tree
10495 set_virt_specifiers (tree decl, cp_virt_specifiers specifiers)
10497 if (decl == NULL_TREE)
10498 return decl;
10499 if (specifiers & VIRT_SPEC_OVERRIDE)
10500 DECL_OVERRIDE_P (decl) = 1;
10501 if (specifiers & VIRT_SPEC_FINAL)
10502 DECL_FINAL_P (decl) = 1;
10503 return decl;
10506 /* DECL is a VAR_DECL for a static data member. Set flags to reflect
10507 the linkage that DECL will receive in the object file. */
10509 static void
10510 set_linkage_for_static_data_member (tree decl)
10512 /* A static data member always has static storage duration and
10513 external linkage. Note that static data members are forbidden in
10514 local classes -- the only situation in which a class has
10515 non-external linkage. */
10516 TREE_PUBLIC (decl) = 1;
10517 TREE_STATIC (decl) = 1;
10518 /* For non-template classes, static data members are always put
10519 out in exactly those files where they are defined, just as
10520 with ordinary namespace-scope variables. */
10521 if (!processing_template_decl)
10522 DECL_INTERFACE_KNOWN (decl) = 1;
10525 /* Create a VAR_DECL named NAME with the indicated TYPE.
10527 If SCOPE is non-NULL, it is the class type or namespace containing
10528 the variable. If SCOPE is NULL, the variable should is created in
10529 the innermost enclosing scope. */
10531 static tree
10532 grokvardecl (tree type,
10533 tree name,
10534 tree orig_declarator,
10535 const cp_decl_specifier_seq *declspecs,
10536 int initialized,
10537 int type_quals,
10538 int inlinep,
10539 bool conceptp,
10540 int template_count,
10541 tree scope,
10542 location_t location)
10544 tree decl;
10545 tree explicit_scope;
10547 gcc_assert (!name || identifier_p (name));
10549 bool constp = (type_quals & TYPE_QUAL_CONST) != 0;
10550 bool volatilep = (type_quals & TYPE_QUAL_VOLATILE) != 0;
10552 /* Compute the scope in which to place the variable, but remember
10553 whether or not that scope was explicitly specified by the user. */
10554 explicit_scope = scope;
10555 if (!scope)
10557 /* An explicit "extern" specifier indicates a namespace-scope
10558 variable. */
10559 if (declspecs->storage_class == sc_extern)
10560 scope = current_decl_namespace ();
10561 else if (!at_function_scope_p ())
10562 scope = current_scope ();
10565 if (scope
10566 && (/* If the variable is a namespace-scope variable declared in a
10567 template, we need DECL_LANG_SPECIFIC. */
10568 (TREE_CODE (scope) == NAMESPACE_DECL && processing_template_decl)
10569 /* Similarly for namespace-scope variables with language linkage
10570 other than C++. */
10571 || (TREE_CODE (scope) == NAMESPACE_DECL
10572 && current_lang_name != lang_name_cplusplus)
10573 /* Similarly for static data members. */
10574 || TYPE_P (scope)
10575 /* Similarly for explicit specializations. */
10576 || (orig_declarator
10577 && TREE_CODE (orig_declarator) == TEMPLATE_ID_EXPR)))
10578 decl = build_lang_decl_loc (location, VAR_DECL, name, type);
10579 else
10580 decl = build_decl (location, VAR_DECL, name, type);
10582 if (explicit_scope && TREE_CODE (explicit_scope) == NAMESPACE_DECL)
10583 set_decl_namespace (decl, explicit_scope, 0);
10584 else
10585 DECL_CONTEXT (decl) = FROB_CONTEXT (scope);
10587 if (declspecs->storage_class == sc_extern)
10589 DECL_THIS_EXTERN (decl) = 1;
10590 DECL_EXTERNAL (decl) = !initialized;
10593 if (DECL_CLASS_SCOPE_P (decl))
10595 set_linkage_for_static_data_member (decl);
10596 /* This function is only called with out-of-class definitions. */
10597 DECL_EXTERNAL (decl) = 0;
10598 check_class_member_definition_namespace (decl);
10600 /* At top level, either `static' or no s.c. makes a definition
10601 (perhaps tentative), and absence of `static' makes it public. */
10602 else if (toplevel_bindings_p ())
10604 TREE_PUBLIC (decl) = (declspecs->storage_class != sc_static
10605 && (DECL_THIS_EXTERN (decl)
10606 || ! constp
10607 || volatilep
10608 || inlinep));
10609 TREE_STATIC (decl) = ! DECL_EXTERNAL (decl);
10611 /* Not at top level, only `static' makes a static definition. */
10612 else
10614 TREE_STATIC (decl) = declspecs->storage_class == sc_static;
10615 TREE_PUBLIC (decl) = DECL_EXTERNAL (decl);
10618 set_originating_module (decl);
10620 if (decl_spec_seq_has_spec_p (declspecs, ds_thread))
10622 if (DECL_EXTERNAL (decl) || TREE_STATIC (decl))
10624 CP_DECL_THREAD_LOCAL_P (decl) = true;
10625 if (!processing_template_decl)
10626 set_decl_tls_model (decl, decl_default_tls_model (decl));
10628 if (declspecs->gnu_thread_keyword_p)
10629 SET_DECL_GNU_TLS_P (decl);
10632 /* If the type of the decl has no linkage, make sure that we'll
10633 notice that in mark_used. */
10634 if (cxx_dialect > cxx98
10635 && decl_linkage (decl) != lk_none
10636 && DECL_LANG_SPECIFIC (decl) == NULL
10637 && !DECL_EXTERN_C_P (decl)
10638 && no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false))
10639 retrofit_lang_decl (decl);
10641 if (TREE_PUBLIC (decl))
10643 /* [basic.link]: A name with no linkage (notably, the name of a class
10644 or enumeration declared in a local scope) shall not be used to
10645 declare an entity with linkage.
10647 DR 757 relaxes this restriction for C++0x. */
10648 if (cxx_dialect < cxx11)
10649 no_linkage_error (decl);
10651 else
10652 DECL_INTERFACE_KNOWN (decl) = 1;
10654 if (DECL_NAME (decl)
10655 && MAIN_NAME_P (DECL_NAME (decl))
10656 && scope == global_namespace)
10657 error_at (DECL_SOURCE_LOCATION (decl),
10658 "cannot declare %<::main%> to be a global variable");
10660 /* Check that the variable can be safely declared as a concept.
10661 Note that this also forbids explicit specializations. */
10662 if (conceptp)
10664 if (!processing_template_decl)
10666 error_at (declspecs->locations[ds_concept],
10667 "a non-template variable cannot be %<concept%>");
10668 return NULL_TREE;
10670 else if (!at_namespace_scope_p ())
10672 error_at (declspecs->locations[ds_concept],
10673 "concept must be defined at namespace scope");
10674 return NULL_TREE;
10676 else
10677 DECL_DECLARED_CONCEPT_P (decl) = true;
10678 if (!same_type_ignoring_top_level_qualifiers_p (type, boolean_type_node))
10679 error_at (declspecs->locations[ds_type_spec],
10680 "concept must have type %<bool%>");
10681 if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
10683 error_at (location, "a variable concept cannot be constrained");
10684 TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
10687 else if (flag_concepts
10688 && current_template_depth > template_class_depth (scope))
10690 tree reqs = TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
10691 tree ci = build_constraints (reqs, NULL_TREE);
10693 set_constraints (decl, ci);
10696 // Handle explicit specializations and instantiations of variable templates.
10697 if (orig_declarator)
10698 decl = check_explicit_specialization (orig_declarator, decl,
10699 template_count, conceptp * 8);
10701 return decl != error_mark_node ? decl : NULL_TREE;
10704 /* Create and return a canonical pointer to member function type, for
10705 TYPE, which is a POINTER_TYPE to a METHOD_TYPE. */
10707 tree
10708 build_ptrmemfunc_type (tree type)
10710 tree field, fields;
10711 tree t;
10713 if (type == error_mark_node)
10714 return type;
10716 /* Make sure that we always have the unqualified pointer-to-member
10717 type first. */
10718 if (cp_cv_quals quals = cp_type_quals (type))
10720 tree unqual = build_ptrmemfunc_type (TYPE_MAIN_VARIANT (type));
10721 return cp_build_qualified_type (unqual, quals);
10724 /* If a canonical type already exists for this type, use it. We use
10725 this method instead of type_hash_canon, because it only does a
10726 simple equality check on the list of field members. */
10728 t = TYPE_PTRMEMFUNC_TYPE (type);
10729 if (t)
10730 return t;
10732 t = make_node (RECORD_TYPE);
10734 /* Let the front end know this is a pointer to member function. */
10735 TYPE_PTRMEMFUNC_FLAG (t) = 1;
10737 field = build_decl (input_location, FIELD_DECL, pfn_identifier, type);
10738 DECL_NONADDRESSABLE_P (field) = 1;
10739 fields = field;
10741 field = build_decl (input_location, FIELD_DECL, delta_identifier,
10742 delta_type_node);
10743 DECL_NONADDRESSABLE_P (field) = 1;
10744 DECL_CHAIN (field) = fields;
10745 fields = field;
10747 finish_builtin_struct (t, "__ptrmemfunc_type", fields, ptr_type_node);
10749 /* Zap out the name so that the back end will give us the debugging
10750 information for this anonymous RECORD_TYPE. */
10751 TYPE_NAME (t) = NULL_TREE;
10753 /* Cache this pointer-to-member type so that we can find it again
10754 later. */
10755 TYPE_PTRMEMFUNC_TYPE (type) = t;
10757 if (TYPE_STRUCTURAL_EQUALITY_P (type))
10758 SET_TYPE_STRUCTURAL_EQUALITY (t);
10759 else if (TYPE_CANONICAL (type) != type)
10760 TYPE_CANONICAL (t) = build_ptrmemfunc_type (TYPE_CANONICAL (type));
10762 return t;
10765 /* Create and return a pointer to data member type. */
10767 tree
10768 build_ptrmem_type (tree class_type, tree member_type)
10770 if (TREE_CODE (member_type) == METHOD_TYPE)
10772 cp_cv_quals quals = type_memfn_quals (member_type);
10773 cp_ref_qualifier rqual = type_memfn_rqual (member_type);
10774 member_type = build_memfn_type (member_type, class_type, quals, rqual);
10775 return build_ptrmemfunc_type (build_pointer_type (member_type));
10777 else
10779 gcc_assert (TREE_CODE (member_type) != FUNCTION_TYPE);
10780 return build_offset_type (class_type, member_type);
10784 /* DECL is a VAR_DECL defined in-class, whose TYPE is also given.
10785 Check to see that the definition is valid. Issue appropriate error
10786 messages. */
10788 static void
10789 check_static_variable_definition (tree decl, tree type)
10791 /* Avoid redundant diagnostics on out-of-class definitions. */
10792 if (!current_class_type || !TYPE_BEING_DEFINED (current_class_type))
10794 /* Can't check yet if we don't know the type. */
10795 else if (dependent_type_p (type))
10797 /* If DECL is declared constexpr, we'll do the appropriate checks
10798 in check_initializer. Similarly for inline static data members. */
10799 else if (DECL_P (decl)
10800 && (DECL_DECLARED_CONSTEXPR_P (decl)
10801 || DECL_VAR_DECLARED_INLINE_P (decl)))
10803 else if (cxx_dialect >= cxx11 && !INTEGRAL_OR_ENUMERATION_TYPE_P (type))
10805 if (!COMPLETE_TYPE_P (type))
10806 error_at (DECL_SOURCE_LOCATION (decl),
10807 "in-class initialization of static data member %q#D of "
10808 "incomplete type", decl);
10809 else if (literal_type_p (type))
10810 permerror (DECL_SOURCE_LOCATION (decl),
10811 "%<constexpr%> needed for in-class initialization of "
10812 "static data member %q#D of non-integral type", decl);
10813 else
10814 error_at (DECL_SOURCE_LOCATION (decl),
10815 "in-class initialization of static data member %q#D of "
10816 "non-literal type", decl);
10818 /* Motion 10 at San Diego: If a static const integral data member is
10819 initialized with an integral constant expression, the initializer
10820 may appear either in the declaration (within the class), or in
10821 the definition, but not both. If it appears in the class, the
10822 member is a member constant. The file-scope definition is always
10823 required. */
10824 else if (!ARITHMETIC_TYPE_P (type) && TREE_CODE (type) != ENUMERAL_TYPE)
10825 error_at (DECL_SOURCE_LOCATION (decl),
10826 "invalid in-class initialization of static data member "
10827 "of non-integral type %qT",
10828 type);
10829 else if (!CP_TYPE_CONST_P (type))
10830 error_at (DECL_SOURCE_LOCATION (decl),
10831 "ISO C++ forbids in-class initialization of non-const "
10832 "static member %qD",
10833 decl);
10834 else if (!INTEGRAL_OR_ENUMERATION_TYPE_P (type))
10835 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wpedantic,
10836 "ISO C++ forbids initialization of member constant "
10837 "%qD of non-integral type %qT", decl, type);
10840 /* *expr_p is part of the TYPE_SIZE of a variably-sized array. If any
10841 SAVE_EXPRs in *expr_p wrap expressions with side-effects, break those
10842 expressions out into temporary variables so that walk_tree doesn't
10843 step into them (c++/15764). */
10845 static tree
10846 stabilize_save_expr_r (tree *expr_p, int *walk_subtrees, void *data)
10848 hash_set<tree> *pset = (hash_set<tree> *)data;
10849 tree expr = *expr_p;
10850 if (TREE_CODE (expr) == SAVE_EXPR)
10852 tree op = TREE_OPERAND (expr, 0);
10853 cp_walk_tree (&op, stabilize_save_expr_r, data, pset);
10854 if (TREE_SIDE_EFFECTS (op))
10855 TREE_OPERAND (expr, 0) = get_temp_regvar (TREE_TYPE (op), op);
10856 *walk_subtrees = 0;
10858 else if (!EXPR_P (expr) || !TREE_SIDE_EFFECTS (expr))
10859 *walk_subtrees = 0;
10860 return NULL;
10863 /* Entry point for the above. */
10865 static void
10866 stabilize_vla_size (tree size)
10868 hash_set<tree> pset;
10869 /* Break out any function calls into temporary variables. */
10870 cp_walk_tree (&size, stabilize_save_expr_r, &pset, &pset);
10873 /* Reduce a SIZEOF_EXPR to its value. */
10875 tree
10876 fold_sizeof_expr (tree t)
10878 tree r;
10879 if (SIZEOF_EXPR_TYPE_P (t))
10880 r = cxx_sizeof_or_alignof_type (EXPR_LOCATION (t),
10881 TREE_TYPE (TREE_OPERAND (t, 0)),
10882 SIZEOF_EXPR, false, false);
10883 else if (TYPE_P (TREE_OPERAND (t, 0)))
10884 r = cxx_sizeof_or_alignof_type (EXPR_LOCATION (t),
10885 TREE_OPERAND (t, 0), SIZEOF_EXPR,
10886 false, false);
10887 else
10888 r = cxx_sizeof_or_alignof_expr (EXPR_LOCATION (t),
10889 TREE_OPERAND (t, 0), SIZEOF_EXPR,
10890 false, false);
10891 if (r == error_mark_node)
10892 r = size_one_node;
10893 return r;
10896 /* Given the SIZE (i.e., number of elements) in an array, compute
10897 an appropriate index type for the array. If non-NULL, NAME is
10898 the name of the entity being declared. */
10900 static tree
10901 compute_array_index_type_loc (location_t name_loc, tree name, tree size,
10902 tsubst_flags_t complain)
10904 if (error_operand_p (size))
10905 return error_mark_node;
10907 /* The type of the index being computed. */
10908 tree itype;
10910 /* The original numeric size as seen in the source code before
10911 conversion to size_t. */
10912 tree origsize = size;
10914 location_t loc = cp_expr_loc_or_loc (size, name ? name_loc : input_location);
10916 if (!type_dependent_expression_p (size))
10918 origsize = size = mark_rvalue_use (size);
10920 if (cxx_dialect < cxx11 && TREE_CODE (size) == NOP_EXPR
10921 && TREE_SIDE_EFFECTS (size))
10922 /* In C++98, we mark a non-constant array bound with a magic
10923 NOP_EXPR with TREE_SIDE_EFFECTS; don't fold in that case. */;
10924 else
10926 size = build_converted_constant_expr (size_type_node, size, complain);
10927 /* Pedantically a constant expression is required here and so
10928 __builtin_is_constant_evaluated () should fold to true if it
10929 is successfully folded into a constant. */
10930 size = fold_non_dependent_expr (size, complain,
10931 /*manifestly_const_eval=*/true);
10933 if (!TREE_CONSTANT (size))
10934 size = origsize;
10937 if (error_operand_p (size))
10938 return error_mark_node;
10940 /* The array bound must be an integer type. */
10941 tree type = TREE_TYPE (size);
10942 if (!INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
10944 if (!(complain & tf_error))
10945 return error_mark_node;
10946 if (name)
10947 error_at (loc, "size of array %qD has non-integral type %qT",
10948 name, type);
10949 else
10950 error_at (loc, "size of array has non-integral type %qT", type);
10951 size = integer_one_node;
10955 /* A type is dependent if it is...an array type constructed from any
10956 dependent type or whose size is specified by a constant expression
10957 that is value-dependent. */
10958 /* We can only call value_dependent_expression_p on integral constant
10959 expressions. */
10960 if (processing_template_decl
10961 && potential_constant_expression (size)
10962 && value_dependent_expression_p (size))
10964 /* Just build the index type and mark that it requires
10965 structural equality checks. */
10966 in_template:
10967 itype = build_index_type (build_min (MINUS_EXPR, sizetype,
10968 size, size_one_node));
10969 TYPE_DEPENDENT_P (itype) = 1;
10970 TYPE_DEPENDENT_P_VALID (itype) = 1;
10971 SET_TYPE_STRUCTURAL_EQUALITY (itype);
10972 return itype;
10975 if (TREE_CODE (size) != INTEGER_CST)
10977 tree folded = cp_fully_fold (size);
10978 if (TREE_CODE (folded) == INTEGER_CST)
10980 if (name)
10981 pedwarn (loc, OPT_Wpedantic, "size of array %qD is not an "
10982 "integral constant-expression", name);
10983 else
10984 pedwarn (loc, OPT_Wpedantic,
10985 "size of array is not an integral constant-expression");
10987 if (TREE_CONSTANT (size) && !TREE_CONSTANT (folded))
10988 /* We might have lost the TREE_CONSTANT flag e.g. when we are
10989 folding a conversion from a pointer to integral type. In that
10990 case issue an error below and don't treat this as a VLA. */;
10991 else
10992 /* Use the folded result for VLAs, too; it will have resolved
10993 SIZEOF_EXPR. */
10994 size = folded;
10997 /* Normally, the array-bound will be a constant. */
10998 if (TREE_CODE (size) == INTEGER_CST)
11000 /* The size to use in diagnostics that reflects the constant
11001 size used in the source, rather than SIZE massaged above. */
11002 tree diagsize = size;
11004 /* If the original size before conversion to size_t was signed
11005 and negative, convert it to ssizetype to restore the sign. */
11006 if (!TYPE_UNSIGNED (TREE_TYPE (origsize))
11007 && TREE_CODE (size) == INTEGER_CST
11008 && tree_int_cst_sign_bit (size))
11010 diagsize = fold_convert (ssizetype, size);
11012 /* Clear the overflow bit that may have been set as a result
11013 of the conversion from the sizetype of the new size to
11014 ssizetype. */
11015 TREE_OVERFLOW (diagsize) = false;
11018 /* Verify that the array has a positive number of elements
11019 and issue the appropriate diagnostic if it doesn't. */
11020 if (!valid_array_size_p (loc, diagsize, name, (complain & tf_error)))
11022 if (!(complain & tf_error))
11023 return error_mark_node;
11024 size = integer_one_node;
11026 /* As an extension we allow zero-sized arrays. */
11027 else if (integer_zerop (size))
11029 if (!(complain & tf_error))
11030 /* We must fail if performing argument deduction (as
11031 indicated by the state of complain), so that
11032 another substitution can be found. */
11033 return error_mark_node;
11034 else if (name)
11035 pedwarn (loc, OPT_Wpedantic,
11036 "ISO C++ forbids zero-size array %qD", name);
11037 else
11038 pedwarn (loc, OPT_Wpedantic,
11039 "ISO C++ forbids zero-size array");
11042 else if (TREE_CONSTANT (size)
11043 /* We don't allow VLAs at non-function scopes, or during
11044 tentative template substitution. */
11045 || !at_function_scope_p ()
11046 || !(complain & tf_error))
11048 if (!(complain & tf_error))
11049 return error_mark_node;
11050 /* `(int) &fn' is not a valid array bound. */
11051 if (name)
11052 error_at (loc,
11053 "size of array %qD is not an integral constant-expression",
11054 name);
11055 else
11056 error_at (loc, "size of array is not an integral constant-expression");
11057 size = integer_one_node;
11059 else if (pedantic && warn_vla != 0)
11061 if (name)
11062 pedwarn (name_loc, OPT_Wvla,
11063 "ISO C++ forbids variable length array %qD", name);
11064 else
11065 pedwarn (input_location, OPT_Wvla,
11066 "ISO C++ forbids variable length array");
11068 else if (warn_vla > 0)
11070 if (name)
11071 warning_at (name_loc, OPT_Wvla,
11072 "variable length array %qD is used", name);
11073 else
11074 warning (OPT_Wvla,
11075 "variable length array is used");
11078 if (processing_template_decl && !TREE_CONSTANT (size))
11079 goto in_template;
11080 else
11082 if (!TREE_CONSTANT (size))
11084 /* A variable sized array. Arrange for the SAVE_EXPR on the inside
11085 of the MINUS_EXPR, which allows the -1 to get folded with the +1
11086 that happens when building TYPE_SIZE. */
11087 size = variable_size (size);
11088 stabilize_vla_size (size);
11091 /* Compute the index of the largest element in the array. It is
11092 one less than the number of elements in the array. We save
11093 and restore PROCESSING_TEMPLATE_DECL so that computations in
11094 cp_build_binary_op will be appropriately folded. */
11096 processing_template_decl_sentinel s;
11097 itype = cp_build_binary_op (input_location,
11098 MINUS_EXPR,
11099 cp_convert (ssizetype, size, complain),
11100 cp_convert (ssizetype, integer_one_node,
11101 complain),
11102 complain);
11103 itype = maybe_constant_value (itype, NULL_TREE, true);
11106 if (!TREE_CONSTANT (itype))
11108 if (sanitize_flags_p (SANITIZE_VLA)
11109 && current_function_decl != NULL_TREE)
11111 /* We have to add 1 -- in the ubsan routine we generate
11112 LE_EXPR rather than LT_EXPR. */
11113 tree t = fold_build2 (PLUS_EXPR, TREE_TYPE (itype), itype,
11114 build_one_cst (TREE_TYPE (itype)));
11115 t = ubsan_instrument_vla (input_location, t);
11116 finish_expr_stmt (t);
11119 /* Make sure that there was no overflow when creating to a signed
11120 index type. (For example, on a 32-bit machine, an array with
11121 size 2^32 - 1 is too big.) */
11122 else if (TREE_CODE (itype) == INTEGER_CST
11123 && TREE_OVERFLOW (itype))
11125 if (!(complain & tf_error))
11126 return error_mark_node;
11127 error ("overflow in array dimension");
11128 TREE_OVERFLOW (itype) = 0;
11132 /* Create and return the appropriate index type. */
11133 itype = build_index_type (itype);
11135 /* If the index type were dependent, we would have returned early, so
11136 remember that it isn't. */
11137 TYPE_DEPENDENT_P (itype) = 0;
11138 TYPE_DEPENDENT_P_VALID (itype) = 1;
11139 return itype;
11142 tree
11143 compute_array_index_type (tree name, tree size, tsubst_flags_t complain)
11145 return compute_array_index_type_loc (input_location, name, size, complain);
11148 /* Returns the scope (if any) in which the entity declared by
11149 DECLARATOR will be located. If the entity was declared with an
11150 unqualified name, NULL_TREE is returned. */
11152 tree
11153 get_scope_of_declarator (const cp_declarator *declarator)
11155 while (declarator && declarator->kind != cdk_id)
11156 declarator = declarator->declarator;
11158 /* If the declarator-id is a SCOPE_REF, the scope in which the
11159 declaration occurs is the first operand. */
11160 if (declarator
11161 && declarator->u.id.qualifying_scope)
11162 return declarator->u.id.qualifying_scope;
11164 /* Otherwise, the declarator is not a qualified name; the entity will
11165 be declared in the current scope. */
11166 return NULL_TREE;
11169 /* Returns an ARRAY_TYPE for an array with SIZE elements of the
11170 indicated TYPE. If non-NULL, NAME is the NAME of the declaration
11171 with this type. */
11173 static tree
11174 create_array_type_for_decl (tree name, tree type, tree size, location_t loc)
11176 tree itype = NULL_TREE;
11178 /* If things have already gone awry, bail now. */
11179 if (type == error_mark_node || size == error_mark_node)
11180 return error_mark_node;
11182 /* [dcl.type.class.deduct] prohibits forming an array of placeholder
11183 for a deduced class type. */
11184 if (template_placeholder_p (type))
11186 if (name)
11187 error_at (loc, "%qD declared as array of template placeholder "
11188 "type %qT", name, type);
11189 else
11190 error ("creating array of template placeholder type %qT", type);
11191 return error_mark_node;
11194 /* If there are some types which cannot be array elements,
11195 issue an error-message and return. */
11196 switch (TREE_CODE (type))
11198 case VOID_TYPE:
11199 if (name)
11200 error_at (loc, "declaration of %qD as array of void", name);
11201 else
11202 error ("creating array of void");
11203 return error_mark_node;
11205 case FUNCTION_TYPE:
11206 if (name)
11207 error_at (loc, "declaration of %qD as array of functions", name);
11208 else
11209 error ("creating array of functions");
11210 return error_mark_node;
11212 case REFERENCE_TYPE:
11213 if (name)
11214 error_at (loc, "declaration of %qD as array of references", name);
11215 else
11216 error ("creating array of references");
11217 return error_mark_node;
11219 case METHOD_TYPE:
11220 if (name)
11221 error_at (loc, "declaration of %qD as array of function members",
11222 name);
11223 else
11224 error ("creating array of function members");
11225 return error_mark_node;
11227 default:
11228 break;
11231 if (!verify_type_context (name ? loc : input_location,
11232 TCTX_ARRAY_ELEMENT, type))
11233 return error_mark_node;
11235 /* [dcl.array]
11237 The constant expressions that specify the bounds of the arrays
11238 can be omitted only for the first member of the sequence. */
11239 if (TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type))
11241 if (name)
11242 error_at (loc, "declaration of %qD as multidimensional array must "
11243 "have bounds for all dimensions except the first",
11244 name);
11245 else
11246 error ("multidimensional array must have bounds for all "
11247 "dimensions except the first");
11249 return error_mark_node;
11252 /* Figure out the index type for the array. */
11253 if (size)
11255 itype = compute_array_index_type_loc (loc, name, size,
11256 tf_warning_or_error);
11257 if (type_uses_auto (type)
11258 && variably_modified_type_p (itype, /*fn=*/NULL_TREE))
11260 sorry_at (loc, "variable-length array of %<auto%>");
11261 return error_mark_node;
11265 return build_cplus_array_type (type, itype);
11268 /* Returns the smallest location that is not UNKNOWN_LOCATION. */
11270 static location_t
11271 min_location (location_t loca, location_t locb)
11273 if (loca == UNKNOWN_LOCATION
11274 || (locb != UNKNOWN_LOCATION
11275 && linemap_location_before_p (line_table, locb, loca)))
11276 return locb;
11277 return loca;
11280 /* Returns the smallest location != UNKNOWN_LOCATION among the
11281 three stored in LOCATIONS[ds_const], LOCATIONS[ds_volatile],
11282 and LOCATIONS[ds_restrict]. */
11284 static location_t
11285 smallest_type_quals_location (int type_quals, const location_t* locations)
11287 location_t loc = UNKNOWN_LOCATION;
11289 if (type_quals & TYPE_QUAL_CONST)
11290 loc = locations[ds_const];
11292 if (type_quals & TYPE_QUAL_VOLATILE)
11293 loc = min_location (loc, locations[ds_volatile]);
11295 if (type_quals & TYPE_QUAL_RESTRICT)
11296 loc = min_location (loc, locations[ds_restrict]);
11298 return loc;
11301 /* Returns the smallest among the latter and locations[ds_type_spec]. */
11303 static location_t
11304 smallest_type_location (int type_quals, const location_t* locations)
11306 location_t loc = smallest_type_quals_location (type_quals, locations);
11307 return min_location (loc, locations[ds_type_spec]);
11310 static location_t
11311 smallest_type_location (const cp_decl_specifier_seq *declspecs)
11313 int type_quals = get_type_quals (declspecs);
11314 return smallest_type_location (type_quals, declspecs->locations);
11317 /* Check that it's OK to declare a function with the indicated TYPE
11318 and TYPE_QUALS. SFK indicates the kind of special function (if any)
11319 that this function is. OPTYPE is the type given in a conversion
11320 operator declaration, or the class type for a constructor/destructor.
11321 Returns the actual return type of the function; that may be different
11322 than TYPE if an error occurs, or for certain special functions. */
11324 static tree
11325 check_special_function_return_type (special_function_kind sfk,
11326 tree type,
11327 tree optype,
11328 int type_quals,
11329 const location_t* locations)
11331 switch (sfk)
11333 case sfk_constructor:
11334 if (type)
11335 error_at (smallest_type_location (type_quals, locations),
11336 "return type specification for constructor invalid");
11337 else if (type_quals != TYPE_UNQUALIFIED)
11338 error_at (smallest_type_quals_location (type_quals, locations),
11339 "qualifiers are not allowed on constructor declaration");
11341 if (targetm.cxx.cdtor_returns_this ())
11342 type = build_pointer_type (optype);
11343 else
11344 type = void_type_node;
11345 break;
11347 case sfk_destructor:
11348 if (type)
11349 error_at (smallest_type_location (type_quals, locations),
11350 "return type specification for destructor invalid");
11351 else if (type_quals != TYPE_UNQUALIFIED)
11352 error_at (smallest_type_quals_location (type_quals, locations),
11353 "qualifiers are not allowed on destructor declaration");
11355 /* We can't use the proper return type here because we run into
11356 problems with ambiguous bases and covariant returns. */
11357 if (targetm.cxx.cdtor_returns_this ())
11358 type = build_pointer_type (void_type_node);
11359 else
11360 type = void_type_node;
11361 break;
11363 case sfk_conversion:
11364 if (type)
11365 error_at (smallest_type_location (type_quals, locations),
11366 "return type specified for %<operator %T%>", optype);
11367 else if (type_quals != TYPE_UNQUALIFIED)
11368 error_at (smallest_type_quals_location (type_quals, locations),
11369 "qualifiers are not allowed on declaration of "
11370 "%<operator %T%>", optype);
11372 type = optype;
11373 break;
11375 case sfk_deduction_guide:
11376 if (type)
11377 error_at (smallest_type_location (type_quals, locations),
11378 "return type specified for deduction guide");
11379 else if (type_quals != TYPE_UNQUALIFIED)
11380 error_at (smallest_type_quals_location (type_quals, locations),
11381 "qualifiers are not allowed on declaration of "
11382 "deduction guide");
11383 if (TREE_CODE (optype) == TEMPLATE_TEMPLATE_PARM)
11385 error ("template template parameter %qT in declaration of "
11386 "deduction guide", optype);
11387 type = error_mark_node;
11389 else
11390 type = make_template_placeholder (CLASSTYPE_TI_TEMPLATE (optype));
11391 for (int i = 0; i < ds_last; ++i)
11392 if (i != ds_explicit && locations[i])
11393 error_at (locations[i],
11394 "%<decl-specifier%> in declaration of deduction guide");
11395 break;
11397 default:
11398 gcc_unreachable ();
11401 return type;
11404 /* A variable or data member (whose unqualified name is IDENTIFIER)
11405 has been declared with the indicated TYPE. If the TYPE is not
11406 acceptable, issue an error message and return a type to use for
11407 error-recovery purposes. */
11409 tree
11410 check_var_type (tree identifier, tree type, location_t loc)
11412 if (VOID_TYPE_P (type))
11414 if (!identifier)
11415 error_at (loc, "unnamed variable or field declared void");
11416 else if (identifier_p (identifier))
11418 gcc_assert (!IDENTIFIER_ANY_OP_P (identifier));
11419 error_at (loc, "variable or field %qE declared void",
11420 identifier);
11422 else
11423 error_at (loc, "variable or field declared void");
11424 type = error_mark_node;
11427 return type;
11430 /* Handle declaring DECL as an inline variable. */
11432 static void
11433 mark_inline_variable (tree decl, location_t loc)
11435 bool inlinep = true;
11436 if (! toplevel_bindings_p ())
11438 error_at (loc, "%<inline%> specifier invalid for variable "
11439 "%qD declared at block scope", decl);
11440 inlinep = false;
11442 else if (cxx_dialect < cxx17)
11443 pedwarn (loc, OPT_Wc__17_extensions, "inline variables are only available "
11444 "with %<-std=c++17%> or %<-std=gnu++17%>");
11445 if (inlinep)
11447 retrofit_lang_decl (decl);
11448 SET_DECL_VAR_DECLARED_INLINE_P (decl);
11453 /* Assign a typedef-given name to a class or enumeration type declared
11454 as anonymous at first. This was split out of grokdeclarator
11455 because it is also used in libcc1. */
11457 void
11458 name_unnamed_type (tree type, tree decl)
11460 gcc_assert (TYPE_UNNAMED_P (type));
11462 /* Replace the anonymous decl with the real decl. Be careful not to
11463 rename other typedefs (such as the self-reference) of type. */
11464 tree orig = TYPE_NAME (type);
11465 for (tree t = TYPE_MAIN_VARIANT (type); t; t = TYPE_NEXT_VARIANT (t))
11466 if (TYPE_NAME (t) == orig)
11467 TYPE_NAME (t) = decl;
11469 /* If this is a typedef within a template class, the nested
11470 type is a (non-primary) template. The name for the
11471 template needs updating as well. */
11472 if (TYPE_LANG_SPECIFIC (type) && CLASSTYPE_TEMPLATE_INFO (type))
11473 DECL_NAME (CLASSTYPE_TI_TEMPLATE (type)) = DECL_NAME (decl);
11475 /* Adjust linkage now that we aren't unnamed anymore. */
11476 reset_type_linkage (type);
11478 /* FIXME remangle member functions; member functions of a
11479 type with external linkage have external linkage. */
11481 /* Check that our job is done, and that it would fail if we
11482 attempted to do it again. */
11483 gcc_assert (!TYPE_UNNAMED_P (type));
11486 /* Check that decltype(auto) was well-formed: only plain decltype(auto)
11487 is allowed. TYPE might contain a decltype(auto). Returns true if
11488 there was a problem, false otherwise. */
11490 static bool
11491 check_decltype_auto (location_t loc, tree type)
11493 if (tree a = type_uses_auto (type))
11495 if (AUTO_IS_DECLTYPE (a))
11497 if (a != type)
11499 error_at (loc, "%qT as type rather than plain "
11500 "%<decltype(auto)%>", type);
11501 return true;
11503 else if (TYPE_QUALS (type) != TYPE_UNQUALIFIED)
11505 error_at (loc, "%<decltype(auto)%> cannot be cv-qualified");
11506 return true;
11510 return false;
11513 /* Given declspecs and a declarator (abstract or otherwise), determine
11514 the name and type of the object declared and construct a DECL node
11515 for it.
11517 DECLSPECS points to the representation of declaration-specifier
11518 sequence that precedes declarator.
11520 DECL_CONTEXT says which syntactic context this declaration is in:
11521 NORMAL for most contexts. Make a VAR_DECL or FUNCTION_DECL or TYPE_DECL.
11522 FUNCDEF for a function definition. Like NORMAL but a few different
11523 error messages in each case. Return value may be zero meaning
11524 this definition is too screwy to try to parse.
11525 MEMFUNCDEF for a function definition. Like FUNCDEF but prepares to
11526 handle member functions (which have FIELD context).
11527 Return value may be zero meaning this definition is too screwy to
11528 try to parse.
11529 PARM for a parameter declaration (either within a function prototype
11530 or before a function body). Make a PARM_DECL, or return void_type_node.
11531 TPARM for a template parameter declaration.
11532 CATCHPARM for a parameter declaration before a catch clause.
11533 TYPENAME if for a typename (in a cast or sizeof).
11534 Don't make a DECL node; just return the ..._TYPE node.
11535 FIELD for a struct or union field; make a FIELD_DECL.
11536 BITFIELD for a field with specified width.
11538 INITIALIZED is as for start_decl.
11540 ATTRLIST is a pointer to the list of attributes, which may be NULL
11541 if there are none; *ATTRLIST may be modified if attributes from inside
11542 the declarator should be applied to the declaration.
11544 When this function is called, scoping variables (such as
11545 CURRENT_CLASS_TYPE) should reflect the scope in which the
11546 declaration occurs, not the scope in which the new declaration will
11547 be placed. For example, on:
11549 void S::f() { ... }
11551 when grokdeclarator is called for `S::f', the CURRENT_CLASS_TYPE
11552 should not be `S'.
11554 Returns a DECL (if a declarator is present), a TYPE (if there is no
11555 declarator, in cases like "struct S;"), or the ERROR_MARK_NODE if an
11556 error occurs. */
11558 tree
11559 grokdeclarator (const cp_declarator *declarator,
11560 cp_decl_specifier_seq *declspecs,
11561 enum decl_context decl_context,
11562 int initialized,
11563 tree* attrlist)
11565 tree type = NULL_TREE;
11566 int longlong = 0;
11567 int explicit_intN = 0;
11568 int int_n_alt = 0;
11569 int virtualp, explicitp, friendp, inlinep, staticp;
11570 int explicit_int = 0;
11571 int explicit_char = 0;
11572 int defaulted_int = 0;
11574 tree typedef_decl = NULL_TREE;
11575 const char *name = NULL;
11576 tree typedef_type = NULL_TREE;
11577 /* True if this declarator is a function definition. */
11578 bool funcdef_flag = false;
11579 cp_declarator_kind innermost_code = cdk_error;
11580 int bitfield = 0;
11581 #if 0
11582 /* See the code below that used this. */
11583 tree decl_attr = NULL_TREE;
11584 #endif
11586 /* Keep track of what sort of function is being processed
11587 so that we can warn about default return values, or explicit
11588 return values which do not match prescribed defaults. */
11589 special_function_kind sfk = sfk_none;
11591 tree dname = NULL_TREE;
11592 tree ctor_return_type = NULL_TREE;
11593 enum overload_flags flags = NO_SPECIAL;
11594 /* cv-qualifiers that apply to the declarator, for a declaration of
11595 a member function. */
11596 cp_cv_quals memfn_quals = TYPE_UNQUALIFIED;
11597 /* virt-specifiers that apply to the declarator, for a declaration of
11598 a member function. */
11599 cp_virt_specifiers virt_specifiers = VIRT_SPEC_UNSPECIFIED;
11600 /* ref-qualifier that applies to the declarator, for a declaration of
11601 a member function. */
11602 cp_ref_qualifier rqual = REF_QUAL_NONE;
11603 /* cv-qualifiers that apply to the type specified by the DECLSPECS. */
11604 int type_quals = get_type_quals (declspecs);
11605 tree raises = NULL_TREE;
11606 int template_count = 0;
11607 tree returned_attrs = NULL_TREE;
11608 tree parms = NULL_TREE;
11609 const cp_declarator *id_declarator;
11610 /* The unqualified name of the declarator; either an
11611 IDENTIFIER_NODE, BIT_NOT_EXPR, or TEMPLATE_ID_EXPR. */
11612 tree unqualified_id;
11613 /* The class type, if any, in which this entity is located,
11614 or NULL_TREE if none. Note that this value may be different from
11615 the current class type; for example if an attempt is made to declare
11616 "A::f" inside "B", this value will be "A". */
11617 tree ctype = current_class_type;
11618 /* The NAMESPACE_DECL for the namespace in which this entity is
11619 located. If an unqualified name is used to declare the entity,
11620 this value will be NULL_TREE, even if the entity is located at
11621 namespace scope. */
11622 tree in_namespace = NULL_TREE;
11623 cp_storage_class storage_class;
11624 bool unsigned_p, signed_p, short_p, long_p, thread_p;
11625 bool type_was_error_mark_node = false;
11626 bool parameter_pack_p = declarator ? declarator->parameter_pack_p : false;
11627 bool template_type_arg = false;
11628 bool template_parm_flag = false;
11629 bool typedef_p = decl_spec_seq_has_spec_p (declspecs, ds_typedef);
11630 bool constexpr_p = decl_spec_seq_has_spec_p (declspecs, ds_constexpr);
11631 bool constinit_p = decl_spec_seq_has_spec_p (declspecs, ds_constinit);
11632 bool consteval_p = decl_spec_seq_has_spec_p (declspecs, ds_consteval);
11633 bool late_return_type_p = false;
11634 bool array_parameter_p = false;
11635 tree reqs = NULL_TREE;
11637 signed_p = decl_spec_seq_has_spec_p (declspecs, ds_signed);
11638 unsigned_p = decl_spec_seq_has_spec_p (declspecs, ds_unsigned);
11639 short_p = decl_spec_seq_has_spec_p (declspecs, ds_short);
11640 long_p = decl_spec_seq_has_spec_p (declspecs, ds_long);
11641 longlong = decl_spec_seq_has_spec_p (declspecs, ds_long_long);
11642 explicit_intN = declspecs->explicit_intN_p;
11643 int_n_alt = declspecs->int_n_alt;
11644 thread_p = decl_spec_seq_has_spec_p (declspecs, ds_thread);
11646 // Was concept_p specified? Note that ds_concept
11647 // implies ds_constexpr!
11648 bool concept_p = decl_spec_seq_has_spec_p (declspecs, ds_concept);
11649 if (concept_p)
11650 constexpr_p = true;
11652 if (decl_context == FUNCDEF)
11653 funcdef_flag = true, decl_context = NORMAL;
11654 else if (decl_context == MEMFUNCDEF)
11655 funcdef_flag = true, decl_context = FIELD;
11656 else if (decl_context == BITFIELD)
11657 bitfield = 1, decl_context = FIELD;
11658 else if (decl_context == TEMPLATE_TYPE_ARG)
11659 template_type_arg = true, decl_context = TYPENAME;
11660 else if (decl_context == TPARM)
11661 template_parm_flag = true, decl_context = PARM;
11663 if (initialized == SD_DEFAULTED || initialized == SD_DELETED)
11664 funcdef_flag = true;
11666 location_t typespec_loc = loc_or_input_loc (smallest_type_location
11667 (type_quals,
11668 declspecs->locations));
11669 location_t id_loc;
11670 location_t init_loc;
11671 if (declarator)
11673 id_loc = loc_or_input_loc (declarator->id_loc);
11674 init_loc = loc_or_input_loc (declarator->init_loc);
11676 else
11677 init_loc = id_loc = input_location;
11679 /* Look inside a declarator for the name being declared
11680 and get it as a string, for an error message. */
11681 for (id_declarator = declarator;
11682 id_declarator;
11683 id_declarator = id_declarator->declarator)
11685 if (id_declarator->kind != cdk_id)
11686 innermost_code = id_declarator->kind;
11688 switch (id_declarator->kind)
11690 case cdk_function:
11691 if (id_declarator->declarator
11692 && id_declarator->declarator->kind == cdk_id)
11694 sfk = id_declarator->declarator->u.id.sfk;
11695 if (sfk == sfk_destructor)
11696 flags = DTOR_FLAG;
11698 break;
11700 case cdk_id:
11702 tree qualifying_scope = id_declarator->u.id.qualifying_scope;
11703 tree decl = id_declarator->u.id.unqualified_name;
11704 if (!decl)
11705 break;
11706 if (qualifying_scope)
11708 if (check_for_bare_parameter_packs (qualifying_scope,
11709 id_declarator->id_loc))
11710 return error_mark_node;
11711 if (at_function_scope_p ())
11713 /* [dcl.meaning]
11715 A declarator-id shall not be qualified except
11716 for ...
11718 None of the cases are permitted in block
11719 scope. */
11720 if (qualifying_scope == global_namespace)
11721 error ("invalid use of qualified-name %<::%D%>",
11722 decl);
11723 else if (TYPE_P (qualifying_scope))
11724 error ("invalid use of qualified-name %<%T::%D%>",
11725 qualifying_scope, decl);
11726 else
11727 error ("invalid use of qualified-name %<%D::%D%>",
11728 qualifying_scope, decl);
11729 return error_mark_node;
11731 else if (TYPE_P (qualifying_scope))
11733 ctype = qualifying_scope;
11734 if (!MAYBE_CLASS_TYPE_P (ctype))
11736 error_at (id_declarator->id_loc,
11737 "%q#T is not a class or namespace", ctype);
11738 ctype = NULL_TREE;
11740 else if (innermost_code != cdk_function
11741 && current_class_type
11742 && !uniquely_derived_from_p (ctype,
11743 current_class_type))
11745 error_at (id_declarator->id_loc,
11746 "invalid use of qualified-name %<%T::%D%>",
11747 qualifying_scope, decl);
11748 return error_mark_node;
11751 else if (TREE_CODE (qualifying_scope) == NAMESPACE_DECL)
11752 in_namespace = qualifying_scope;
11754 switch (TREE_CODE (decl))
11756 case BIT_NOT_EXPR:
11758 if (innermost_code != cdk_function)
11760 error_at (EXPR_LOCATION (decl),
11761 "declaration of %qE as non-function", decl);
11762 return error_mark_node;
11764 else if (!qualifying_scope
11765 && !(current_class_type && at_class_scope_p ()))
11767 error_at (EXPR_LOCATION (decl),
11768 "declaration of %qE as non-member", decl);
11769 return error_mark_node;
11772 tree type = TREE_OPERAND (decl, 0);
11773 if (TYPE_P (type))
11774 type = constructor_name (type);
11775 name = identifier_to_locale (IDENTIFIER_POINTER (type));
11776 dname = decl;
11778 break;
11780 case TEMPLATE_ID_EXPR:
11782 tree fns = TREE_OPERAND (decl, 0);
11784 dname = fns;
11785 if (!identifier_p (dname))
11786 dname = OVL_NAME (dname);
11788 /* Fall through. */
11790 case IDENTIFIER_NODE:
11791 if (identifier_p (decl))
11792 dname = decl;
11794 if (IDENTIFIER_KEYWORD_P (dname))
11796 error ("declarator-id missing; using reserved word %qD",
11797 dname);
11798 name = identifier_to_locale (IDENTIFIER_POINTER (dname));
11800 else if (!IDENTIFIER_CONV_OP_P (dname))
11801 name = identifier_to_locale (IDENTIFIER_POINTER (dname));
11802 else
11804 gcc_assert (flags == NO_SPECIAL);
11805 flags = TYPENAME_FLAG;
11806 sfk = sfk_conversion;
11807 tree glob = get_global_binding (dname);
11808 if (glob && TREE_CODE (glob) == TYPE_DECL)
11809 name = identifier_to_locale (IDENTIFIER_POINTER (dname));
11810 else
11811 name = "<invalid operator>";
11813 break;
11815 default:
11816 gcc_unreachable ();
11818 break;
11821 case cdk_array:
11822 case cdk_pointer:
11823 case cdk_reference:
11824 case cdk_ptrmem:
11825 break;
11827 case cdk_decomp:
11828 name = "structured binding";
11829 break;
11831 case cdk_error:
11832 return error_mark_node;
11834 default:
11835 gcc_unreachable ();
11837 if (id_declarator->kind == cdk_id)
11838 break;
11841 /* [dcl.fct.edf]
11843 The declarator in a function-definition shall have the form
11844 D1 ( parameter-declaration-clause) ... */
11845 if (funcdef_flag && innermost_code != cdk_function)
11847 error_at (id_loc, "function definition does not declare parameters");
11848 return error_mark_node;
11851 if (flags == TYPENAME_FLAG
11852 && innermost_code != cdk_function
11853 && ! (ctype && !declspecs->any_specifiers_p))
11855 error_at (id_loc, "declaration of %qD as non-function", dname);
11856 return error_mark_node;
11859 if (dname && identifier_p (dname))
11861 if (UDLIT_OPER_P (dname)
11862 && innermost_code != cdk_function)
11864 error_at (id_loc, "declaration of %qD as non-function", dname);
11865 return error_mark_node;
11868 if (IDENTIFIER_ANY_OP_P (dname))
11870 if (typedef_p)
11872 error_at (id_loc, "declaration of %qD as %<typedef%>", dname);
11873 return error_mark_node;
11875 else if (decl_context == PARM || decl_context == CATCHPARM)
11877 error_at (id_loc, "declaration of %qD as parameter", dname);
11878 return error_mark_node;
11883 /* Anything declared one level down from the top level
11884 must be one of the parameters of a function
11885 (because the body is at least two levels down). */
11887 /* This heuristic cannot be applied to C++ nodes! Fixed, however,
11888 by not allowing C++ class definitions to specify their parameters
11889 with xdecls (must be spec.d in the parmlist).
11891 Since we now wait to push a class scope until we are sure that
11892 we are in a legitimate method context, we must set oldcname
11893 explicitly (since current_class_name is not yet alive).
11895 We also want to avoid calling this a PARM if it is in a namespace. */
11897 if (decl_context == NORMAL && !toplevel_bindings_p ())
11899 cp_binding_level *b = current_binding_level;
11900 current_binding_level = b->level_chain;
11901 if (current_binding_level != 0 && toplevel_bindings_p ())
11902 decl_context = PARM;
11903 current_binding_level = b;
11906 if (name == NULL)
11907 name = decl_context == PARM ? "parameter" : "type name";
11909 if (consteval_p && constexpr_p)
11911 error_at (declspecs->locations[ds_consteval],
11912 "both %qs and %qs specified", "constexpr", "consteval");
11913 return error_mark_node;
11916 if (concept_p && typedef_p)
11918 error_at (declspecs->locations[ds_concept],
11919 "%qs cannot appear in a typedef declaration", "concept");
11920 return error_mark_node;
11923 if (constexpr_p && typedef_p)
11925 error_at (declspecs->locations[ds_constexpr],
11926 "%qs cannot appear in a typedef declaration", "constexpr");
11927 return error_mark_node;
11930 if (consteval_p && typedef_p)
11932 error_at (declspecs->locations[ds_consteval],
11933 "%qs cannot appear in a typedef declaration", "consteval");
11934 return error_mark_node;
11937 if (constinit_p && typedef_p)
11939 error_at (declspecs->locations[ds_constinit],
11940 "%qs cannot appear in a typedef declaration", "constinit");
11941 return error_mark_node;
11944 /* [dcl.spec]/2 "At most one of the constexpr, consteval, and constinit
11945 keywords shall appear in a decl-specifier-seq." */
11946 if (constinit_p && constexpr_p)
11948 gcc_rich_location richloc (declspecs->locations[ds_constinit]);
11949 richloc.add_range (declspecs->locations[ds_constexpr]);
11950 error_at (&richloc,
11951 "can use at most one of the %<constinit%> and %<constexpr%> "
11952 "specifiers");
11953 return error_mark_node;
11956 /* If there were multiple types specified in the decl-specifier-seq,
11957 issue an error message. */
11958 if (declspecs->multiple_types_p)
11960 error_at (typespec_loc,
11961 "two or more data types in declaration of %qs", name);
11962 return error_mark_node;
11965 if (declspecs->conflicting_specifiers_p)
11967 error_at (min_location (declspecs->locations[ds_typedef],
11968 declspecs->locations[ds_storage_class]),
11969 "conflicting specifiers in declaration of %qs", name);
11970 return error_mark_node;
11973 /* Extract the basic type from the decl-specifier-seq. */
11974 type = declspecs->type;
11975 if (type == error_mark_node)
11977 type = NULL_TREE;
11978 type_was_error_mark_node = true;
11981 /* Ignore erroneous attributes. */
11982 if (attrlist && *attrlist == error_mark_node)
11983 *attrlist = NULL_TREE;
11985 /* An object declared as __attribute__((unavailable)) suppresses
11986 any reports of being declared with unavailable or deprecated
11987 items. An object declared as __attribute__((deprecated))
11988 suppresses warnings of uses of other deprecated items. */
11989 auto ds = make_temp_override (deprecated_state);
11990 if (attrlist && lookup_attribute ("unavailable", *attrlist))
11991 deprecated_state = UNAVAILABLE_DEPRECATED_SUPPRESS;
11992 else if (attrlist && lookup_attribute ("deprecated", *attrlist))
11993 deprecated_state = DEPRECATED_SUPPRESS;
11995 cp_handle_deprecated_or_unavailable (type);
11996 if (type && TREE_CODE (type) == TYPE_DECL)
11998 cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (type));
11999 typedef_decl = type;
12000 type = TREE_TYPE (typedef_decl);
12001 if (DECL_ARTIFICIAL (typedef_decl))
12002 cp_handle_deprecated_or_unavailable (type);
12004 /* No type at all: default to `int', and set DEFAULTED_INT
12005 because it was not a user-defined typedef. */
12006 if (type == NULL_TREE)
12008 if (signed_p || unsigned_p || long_p || short_p)
12010 /* These imply 'int'. */
12011 type = integer_type_node;
12012 defaulted_int = 1;
12014 /* If we just have "complex", it is equivalent to "complex double". */
12015 else if (!longlong && !explicit_intN
12016 && decl_spec_seq_has_spec_p (declspecs, ds_complex))
12018 type = double_type_node;
12019 pedwarn (declspecs->locations[ds_complex], OPT_Wpedantic,
12020 "ISO C++ does not support plain %<complex%> meaning "
12021 "%<double complex%>");
12024 /* Gather flags. */
12025 explicit_int = declspecs->explicit_int_p;
12026 explicit_char = declspecs->explicit_char_p;
12028 #if 0
12029 /* See the code below that used this. */
12030 if (typedef_decl)
12031 decl_attr = DECL_ATTRIBUTES (typedef_decl);
12032 #endif
12033 typedef_type = type;
12035 if (sfk == sfk_conversion || sfk == sfk_deduction_guide)
12036 ctor_return_type = TREE_TYPE (dname);
12037 else
12038 ctor_return_type = ctype;
12040 if (sfk != sfk_none)
12042 type = check_special_function_return_type (sfk, type,
12043 ctor_return_type,
12044 type_quals,
12045 declspecs->locations);
12046 type_quals = TYPE_UNQUALIFIED;
12048 else if (type == NULL_TREE)
12050 int is_main;
12052 explicit_int = -1;
12054 /* We handle `main' specially here, because 'main () { }' is so
12055 common. With no options, it is allowed. With -Wreturn-type,
12056 it is a warning. It is only an error with -pedantic-errors. */
12057 is_main = (funcdef_flag
12058 && dname && identifier_p (dname)
12059 && MAIN_NAME_P (dname)
12060 && ctype == NULL_TREE
12061 && in_namespace == NULL_TREE
12062 && current_namespace == global_namespace);
12064 if (type_was_error_mark_node)
12065 /* We've already issued an error, don't complain more. */;
12066 else if (in_system_header_at (id_loc) || flag_ms_extensions)
12067 /* Allow it, sigh. */;
12068 else if (! is_main)
12069 permerror (id_loc, "ISO C++ forbids declaration of %qs with no type",
12070 name);
12071 else if (pedantic)
12072 pedwarn (id_loc, OPT_Wpedantic,
12073 "ISO C++ forbids declaration of %qs with no type", name);
12074 else
12075 warning_at (id_loc, OPT_Wreturn_type,
12076 "ISO C++ forbids declaration of %qs with no type", name);
12078 if (type_was_error_mark_node && template_parm_flag)
12079 /* FIXME we should be able to propagate the error_mark_node as is
12080 for other contexts too. */
12081 type = error_mark_node;
12082 else
12083 type = integer_type_node;
12086 ctype = NULL_TREE;
12088 if (explicit_intN)
12090 if (! int_n_enabled_p[declspecs->int_n_idx])
12092 error_at (declspecs->locations[ds_type_spec],
12093 "%<__int%d%> is not supported by this target",
12094 int_n_data[declspecs->int_n_idx].bitsize);
12095 explicit_intN = false;
12097 /* Don't pedwarn if the alternate "__intN__" form has been used instead
12098 of "__intN". */
12099 else if (!int_n_alt && pedantic)
12100 pedwarn (declspecs->locations[ds_type_spec], OPT_Wpedantic,
12101 "ISO C++ does not support %<__int%d%> for %qs",
12102 int_n_data[declspecs->int_n_idx].bitsize, name);
12105 /* Now process the modifiers that were specified
12106 and check for invalid combinations. */
12108 /* Long double is a special combination. */
12109 if (long_p && !longlong && TYPE_MAIN_VARIANT (type) == double_type_node)
12111 long_p = false;
12112 type = cp_build_qualified_type (long_double_type_node,
12113 cp_type_quals (type));
12116 /* Check all other uses of type modifiers. */
12118 if (unsigned_p || signed_p || long_p || short_p)
12120 location_t loc;
12121 const char *key;
12122 if (unsigned_p)
12124 key = "unsigned";
12125 loc = declspecs->locations[ds_unsigned];
12127 else if (signed_p)
12129 key = "signed";
12130 loc = declspecs->locations[ds_signed];
12132 else if (longlong)
12134 key = "long long";
12135 loc = declspecs->locations[ds_long_long];
12137 else if (long_p)
12139 key = "long";
12140 loc = declspecs->locations[ds_long];
12142 else /* if (short_p) */
12144 key = "short";
12145 loc = declspecs->locations[ds_short];
12148 int ok = 0;
12150 if (signed_p && unsigned_p)
12152 gcc_rich_location richloc (declspecs->locations[ds_signed]);
12153 richloc.add_range (declspecs->locations[ds_unsigned]);
12154 error_at (&richloc,
12155 "%<signed%> and %<unsigned%> specified together");
12157 else if (long_p && short_p)
12159 gcc_rich_location richloc (declspecs->locations[ds_long]);
12160 richloc.add_range (declspecs->locations[ds_short]);
12161 error_at (&richloc, "%<long%> and %<short%> specified together");
12163 else if (TREE_CODE (type) != INTEGER_TYPE
12164 || type == char8_type_node
12165 || type == char16_type_node
12166 || type == char32_type_node
12167 || ((long_p || short_p)
12168 && (explicit_char || explicit_intN)))
12169 error_at (loc, "%qs specified with %qT", key, type);
12170 else if (!explicit_int && !defaulted_int
12171 && !explicit_char && !explicit_intN)
12173 if (typedef_decl)
12175 pedwarn (loc, OPT_Wpedantic, "%qs specified with %qT",
12176 key, type);
12177 ok = !flag_pedantic_errors;
12179 else if (declspecs->decltype_p)
12180 error_at (loc, "%qs specified with %<decltype%>", key);
12181 else
12182 error_at (loc, "%qs specified with %<typeof%>", key);
12184 else
12185 ok = 1;
12187 /* Discard the type modifiers if they are invalid. */
12188 if (! ok)
12190 unsigned_p = false;
12191 signed_p = false;
12192 long_p = false;
12193 short_p = false;
12194 longlong = 0;
12198 /* Decide whether an integer type is signed or not.
12199 Optionally treat bitfields as signed by default. */
12200 if (unsigned_p
12201 /* [class.bit]
12203 It is implementation-defined whether a plain (neither
12204 explicitly signed or unsigned) char, short, int, or long
12205 bit-field is signed or unsigned.
12207 Naturally, we extend this to long long as well. Note that
12208 this does not include wchar_t. */
12209 || (bitfield && !flag_signed_bitfields
12210 && !signed_p
12211 /* A typedef for plain `int' without `signed' can be
12212 controlled just like plain `int', but a typedef for
12213 `signed int' cannot be so controlled. */
12214 && !(typedef_decl
12215 && C_TYPEDEF_EXPLICITLY_SIGNED (typedef_decl))
12216 && TREE_CODE (type) == INTEGER_TYPE
12217 && !same_type_p (TYPE_MAIN_VARIANT (type), wchar_type_node)))
12219 if (explicit_intN)
12220 type = int_n_trees[declspecs->int_n_idx].unsigned_type;
12221 else if (longlong)
12222 type = long_long_unsigned_type_node;
12223 else if (long_p)
12224 type = long_unsigned_type_node;
12225 else if (short_p)
12226 type = short_unsigned_type_node;
12227 else if (type == char_type_node)
12228 type = unsigned_char_type_node;
12229 else if (typedef_decl)
12230 type = unsigned_type_for (type);
12231 else
12232 type = unsigned_type_node;
12234 else if (signed_p && type == char_type_node)
12235 type = signed_char_type_node;
12236 else if (explicit_intN)
12237 type = int_n_trees[declspecs->int_n_idx].signed_type;
12238 else if (longlong)
12239 type = long_long_integer_type_node;
12240 else if (long_p)
12241 type = long_integer_type_node;
12242 else if (short_p)
12243 type = short_integer_type_node;
12245 if (decl_spec_seq_has_spec_p (declspecs, ds_complex))
12247 if (TREE_CODE (type) != INTEGER_TYPE && TREE_CODE (type) != REAL_TYPE)
12248 error_at (declspecs->locations[ds_complex],
12249 "complex invalid for %qs", name);
12250 /* If a modifier is specified, the resulting complex is the complex
12251 form of TYPE. E.g, "complex short" is "complex short int". */
12252 else if (type == integer_type_node)
12253 type = complex_integer_type_node;
12254 else if (type == float_type_node)
12255 type = complex_float_type_node;
12256 else if (type == double_type_node)
12257 type = complex_double_type_node;
12258 else if (type == long_double_type_node)
12259 type = complex_long_double_type_node;
12260 else
12261 type = build_complex_type (type);
12264 /* If we're using the injected-class-name to form a compound type or a
12265 declaration, replace it with the underlying class so we don't get
12266 redundant typedefs in the debug output. But if we are returning the
12267 type unchanged, leave it alone so that it's available to
12268 maybe_get_template_decl_from_type_decl. */
12269 if (CLASS_TYPE_P (type)
12270 && DECL_SELF_REFERENCE_P (TYPE_NAME (type))
12271 && type == TREE_TYPE (TYPE_NAME (type))
12272 && (declarator || type_quals))
12273 type = DECL_ORIGINAL_TYPE (TYPE_NAME (type));
12275 type_quals |= cp_type_quals (type);
12276 type = cp_build_qualified_type_real
12277 (type, type_quals, ((((typedef_decl && !DECL_ARTIFICIAL (typedef_decl))
12278 || declspecs->decltype_p)
12279 ? tf_ignore_bad_quals : 0) | tf_warning_or_error));
12280 /* We might have ignored or rejected some of the qualifiers. */
12281 type_quals = cp_type_quals (type);
12283 if (cxx_dialect >= cxx17 && type && is_auto (type)
12284 && innermost_code != cdk_function
12285 && id_declarator && declarator != id_declarator)
12286 if (tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (type))
12288 error_at (typespec_loc, "template placeholder type %qT must be followed "
12289 "by a simple declarator-id", type);
12290 inform (DECL_SOURCE_LOCATION (tmpl), "%qD declared here", tmpl);
12291 type = error_mark_node;
12294 staticp = 0;
12295 inlinep = decl_spec_seq_has_spec_p (declspecs, ds_inline);
12296 virtualp = decl_spec_seq_has_spec_p (declspecs, ds_virtual);
12297 explicitp = decl_spec_seq_has_spec_p (declspecs, ds_explicit);
12299 storage_class = declspecs->storage_class;
12300 if (storage_class == sc_static)
12301 staticp = 1 + (decl_context == FIELD);
12302 else if (decl_context == FIELD && sfk == sfk_deduction_guide)
12303 /* Treat class-scope deduction guides as static member functions
12304 so that they get a FUNCTION_TYPE instead of a METHOD_TYPE. */
12305 staticp = 2;
12307 if (virtualp)
12309 if (staticp == 2)
12311 gcc_rich_location richloc (declspecs->locations[ds_virtual]);
12312 richloc.add_range (declspecs->locations[ds_storage_class]);
12313 error_at (&richloc, "member %qD cannot be declared both %<virtual%> "
12314 "and %<static%>", dname);
12315 storage_class = sc_none;
12316 staticp = 0;
12318 if (constexpr_p && pedantic && cxx_dialect < cxx20)
12320 gcc_rich_location richloc (declspecs->locations[ds_virtual]);
12321 richloc.add_range (declspecs->locations[ds_constexpr]);
12322 pedwarn (&richloc, OPT_Wc__20_extensions, "member %qD can be "
12323 "declared both %<virtual%> and %<constexpr%> only in "
12324 "%<-std=c++20%> or %<-std=gnu++20%>", dname);
12327 friendp = decl_spec_seq_has_spec_p (declspecs, ds_friend);
12329 /* Issue errors about use of storage classes for parameters. */
12330 if (decl_context == PARM)
12332 if (typedef_p)
12334 error_at (declspecs->locations[ds_typedef],
12335 "typedef declaration invalid in parameter declaration");
12336 return error_mark_node;
12338 else if (template_parm_flag && storage_class != sc_none)
12340 error_at (min_location (declspecs->locations[ds_thread],
12341 declspecs->locations[ds_storage_class]),
12342 "storage class specified for template parameter %qs",
12343 name);
12344 return error_mark_node;
12346 else if (storage_class == sc_static
12347 || storage_class == sc_extern
12348 || thread_p)
12350 error_at (min_location (declspecs->locations[ds_thread],
12351 declspecs->locations[ds_storage_class]),
12352 "storage class specified for parameter %qs", name);
12353 return error_mark_node;
12356 /* Function parameters cannot be concept. */
12357 if (concept_p)
12359 error_at (declspecs->locations[ds_concept],
12360 "a parameter cannot be declared %qs", "concept");
12361 concept_p = 0;
12362 constexpr_p = 0;
12364 /* Function parameters cannot be constexpr. If we saw one, moan
12365 and pretend it wasn't there. */
12366 else if (constexpr_p)
12368 error_at (declspecs->locations[ds_constexpr],
12369 "a parameter cannot be declared %qs", "constexpr");
12370 constexpr_p = 0;
12372 if (constinit_p)
12374 error_at (declspecs->locations[ds_constinit],
12375 "a parameter cannot be declared %qs", "constinit");
12376 constinit_p = 0;
12378 if (consteval_p)
12380 error_at (declspecs->locations[ds_consteval],
12381 "a parameter cannot be declared %qs", "consteval");
12382 consteval_p = 0;
12386 /* Give error if `virtual' is used outside of class declaration. */
12387 if (virtualp
12388 && (current_class_name == NULL_TREE || decl_context != FIELD))
12390 error_at (declspecs->locations[ds_virtual],
12391 "%<virtual%> outside class declaration");
12392 virtualp = 0;
12395 if (innermost_code == cdk_decomp)
12397 location_t loc = (declarator->kind == cdk_reference
12398 ? declarator->declarator->id_loc : declarator->id_loc);
12399 if (inlinep)
12400 error_at (declspecs->locations[ds_inline],
12401 "structured binding declaration cannot be %qs", "inline");
12402 if (typedef_p)
12403 error_at (declspecs->locations[ds_typedef],
12404 "structured binding declaration cannot be %qs", "typedef");
12405 if (constexpr_p && !concept_p)
12406 error_at (declspecs->locations[ds_constexpr], "structured "
12407 "binding declaration cannot be %qs", "constexpr");
12408 if (consteval_p)
12409 error_at (declspecs->locations[ds_consteval], "structured "
12410 "binding declaration cannot be %qs", "consteval");
12411 if (thread_p && cxx_dialect < cxx20)
12412 pedwarn (declspecs->locations[ds_thread], OPT_Wc__20_extensions,
12413 "structured binding declaration can be %qs only in "
12414 "%<-std=c++20%> or %<-std=gnu++20%>",
12415 declspecs->gnu_thread_keyword_p
12416 ? "__thread" : "thread_local");
12417 if (concept_p)
12418 error_at (declspecs->locations[ds_concept],
12419 "structured binding declaration cannot be %qs", "concept");
12420 /* [dcl.struct.bind] "A cv that includes volatile is deprecated." */
12421 if (type_quals & TYPE_QUAL_VOLATILE)
12422 warning_at (declspecs->locations[ds_volatile], OPT_Wvolatile,
12423 "%<volatile%>-qualified structured binding is deprecated");
12424 switch (storage_class)
12426 case sc_none:
12427 break;
12428 case sc_register:
12429 error_at (loc, "structured binding declaration cannot be %qs",
12430 "register");
12431 break;
12432 case sc_static:
12433 if (cxx_dialect < cxx20)
12434 pedwarn (loc, OPT_Wc__20_extensions,
12435 "structured binding declaration can be %qs only in "
12436 "%<-std=c++20%> or %<-std=gnu++20%>", "static");
12437 break;
12438 case sc_extern:
12439 error_at (loc, "structured binding declaration cannot be %qs",
12440 "extern");
12441 break;
12442 case sc_mutable:
12443 error_at (loc, "structured binding declaration cannot be %qs",
12444 "mutable");
12445 break;
12446 case sc_auto:
12447 error_at (loc, "structured binding declaration cannot be "
12448 "C++98 %<auto%>");
12449 break;
12450 default:
12451 gcc_unreachable ();
12453 if (TREE_CODE (type) != TEMPLATE_TYPE_PARM
12454 || TYPE_IDENTIFIER (type) != auto_identifier)
12456 if (type != error_mark_node)
12458 error_at (loc, "structured binding declaration cannot have "
12459 "type %qT", type);
12460 inform (loc,
12461 "type must be cv-qualified %<auto%> or reference to "
12462 "cv-qualified %<auto%>");
12464 type = build_qualified_type (make_auto (), type_quals);
12465 declspecs->type = type;
12467 inlinep = 0;
12468 typedef_p = 0;
12469 constexpr_p = 0;
12470 consteval_p = 0;
12471 concept_p = 0;
12472 if (storage_class != sc_static)
12474 storage_class = sc_none;
12475 declspecs->storage_class = sc_none;
12479 /* Static anonymous unions are dealt with here. */
12480 if (staticp && decl_context == TYPENAME
12481 && declspecs->type
12482 && ANON_AGGR_TYPE_P (declspecs->type))
12483 decl_context = FIELD;
12485 /* Warn about storage classes that are invalid for certain
12486 kinds of declarations (parameters, typenames, etc.). */
12487 if (thread_p
12488 && ((storage_class
12489 && storage_class != sc_extern
12490 && storage_class != sc_static)
12491 || typedef_p))
12493 location_t loc
12494 = min_location (declspecs->locations[ds_thread],
12495 declspecs->locations[ds_storage_class]);
12496 error_at (loc, "multiple storage classes in declaration of %qs", name);
12497 thread_p = false;
12499 if (decl_context != NORMAL
12500 && ((storage_class != sc_none
12501 && storage_class != sc_mutable)
12502 || thread_p))
12504 if ((decl_context == PARM || decl_context == CATCHPARM)
12505 && (storage_class == sc_register
12506 || storage_class == sc_auto))
12508 else if (typedef_p)
12510 else if (decl_context == FIELD
12511 /* C++ allows static class elements. */
12512 && storage_class == sc_static)
12513 /* C++ also allows inlines and signed and unsigned elements,
12514 but in those cases we don't come in here. */
12516 else
12518 location_t loc
12519 = min_location (declspecs->locations[ds_thread],
12520 declspecs->locations[ds_storage_class]);
12521 if (decl_context == FIELD)
12522 error_at (loc, "storage class specified for %qs", name);
12523 else if (decl_context == PARM || decl_context == CATCHPARM)
12524 error_at (loc, "storage class specified for parameter %qs", name);
12525 else
12526 error_at (loc, "storage class specified for typename");
12527 if (storage_class == sc_register
12528 || storage_class == sc_auto
12529 || storage_class == sc_extern
12530 || thread_p)
12531 storage_class = sc_none;
12534 else if (storage_class == sc_extern && funcdef_flag
12535 && ! toplevel_bindings_p ())
12536 error ("nested function %qs declared %<extern%>", name);
12537 else if (toplevel_bindings_p ())
12539 if (storage_class == sc_auto)
12540 error_at (declspecs->locations[ds_storage_class],
12541 "top-level declaration of %qs specifies %<auto%>", name);
12543 else if (thread_p
12544 && storage_class != sc_extern
12545 && storage_class != sc_static)
12547 if (declspecs->gnu_thread_keyword_p)
12548 pedwarn (declspecs->locations[ds_thread],
12549 0, "function-scope %qs implicitly auto and "
12550 "declared %<__thread%>", name);
12552 /* When thread_local is applied to a variable of block scope the
12553 storage-class-specifier static is implied if it does not appear
12554 explicitly. */
12555 storage_class = declspecs->storage_class = sc_static;
12556 staticp = 1;
12559 if (storage_class && friendp)
12561 error_at (min_location (declspecs->locations[ds_thread],
12562 declspecs->locations[ds_storage_class]),
12563 "storage class specifiers invalid in friend function "
12564 "declarations");
12565 storage_class = sc_none;
12566 staticp = 0;
12569 if (!id_declarator)
12570 unqualified_id = NULL_TREE;
12571 else
12573 unqualified_id = id_declarator->u.id.unqualified_name;
12574 switch (TREE_CODE (unqualified_id))
12576 case BIT_NOT_EXPR:
12577 unqualified_id = TREE_OPERAND (unqualified_id, 0);
12578 if (TYPE_P (unqualified_id))
12579 unqualified_id = constructor_name (unqualified_id);
12580 break;
12582 case IDENTIFIER_NODE:
12583 case TEMPLATE_ID_EXPR:
12584 break;
12586 default:
12587 gcc_unreachable ();
12591 if (declspecs->std_attributes)
12593 location_t attr_loc = declspecs->locations[ds_std_attribute];
12594 if (warning_at (attr_loc, OPT_Wattributes, "attribute ignored"))
12595 inform (attr_loc, "an attribute that appertains to a type-specifier "
12596 "is ignored");
12599 /* Determine the type of the entity declared by recurring on the
12600 declarator. */
12601 for (; declarator; declarator = declarator->declarator)
12603 const cp_declarator *inner_declarator;
12604 tree attrs;
12606 if (type == error_mark_node)
12607 return error_mark_node;
12609 attrs = declarator->attributes;
12610 if (attrs)
12612 int attr_flags;
12614 attr_flags = 0;
12615 if (declarator->kind == cdk_id)
12616 attr_flags |= (int) ATTR_FLAG_DECL_NEXT;
12617 if (declarator->kind == cdk_function)
12618 attr_flags |= (int) ATTR_FLAG_FUNCTION_NEXT;
12619 if (declarator->kind == cdk_array)
12620 attr_flags |= (int) ATTR_FLAG_ARRAY_NEXT;
12621 tree late_attrs = NULL_TREE;
12622 if (decl_context != PARM && decl_context != TYPENAME)
12623 /* Assume that any attributes that get applied late to
12624 templates will DTRT when applied to the declaration
12625 as a whole. */
12626 late_attrs = splice_template_attributes (&attrs, type);
12627 returned_attrs = decl_attributes (&type,
12628 chainon (returned_attrs, attrs),
12629 attr_flags);
12630 returned_attrs = chainon (late_attrs, returned_attrs);
12633 inner_declarator = declarator->declarator;
12635 /* We don't want to warn in parameter context because we don't
12636 yet know if the parse will succeed, and this might turn out
12637 to be a constructor call. */
12638 if (decl_context != PARM
12639 && decl_context != TYPENAME
12640 && !typedef_p
12641 && declarator->parenthesized != UNKNOWN_LOCATION
12642 /* If the type is class-like and the inner name used a
12643 global namespace qualifier, we need the parens.
12644 Unfortunately all we can tell is whether a qualified name
12645 was used or not. */
12646 && !(inner_declarator
12647 && inner_declarator->kind == cdk_id
12648 && inner_declarator->u.id.qualifying_scope
12649 && (MAYBE_CLASS_TYPE_P (type)
12650 || TREE_CODE (type) == ENUMERAL_TYPE)))
12652 if (warning_at (declarator->parenthesized, OPT_Wparentheses,
12653 "unnecessary parentheses in declaration of %qs",
12654 name))
12656 gcc_rich_location iloc (declarator->parenthesized);
12657 iloc.add_fixit_remove (get_start (declarator->parenthesized));
12658 iloc.add_fixit_remove (get_finish (declarator->parenthesized));
12659 inform (&iloc, "remove parentheses");
12662 if (declarator->kind == cdk_id || declarator->kind == cdk_decomp)
12663 break;
12665 switch (declarator->kind)
12667 case cdk_array:
12668 type = create_array_type_for_decl (dname, type,
12669 declarator->u.array.bounds,
12670 declarator->id_loc);
12671 if (!valid_array_size_p (dname
12672 ? declarator->id_loc : input_location,
12673 type, dname))
12674 type = error_mark_node;
12676 if (declarator->std_attributes)
12677 /* [dcl.array]/1:
12679 The optional attribute-specifier-seq appertains to the
12680 array. */
12681 returned_attrs = chainon (returned_attrs,
12682 declarator->std_attributes);
12683 break;
12685 case cdk_function:
12687 tree arg_types;
12688 int funcdecl_p;
12690 /* Declaring a function type. */
12692 /* Pick up type qualifiers which should be applied to `this'. */
12693 memfn_quals = declarator->u.function.qualifiers;
12694 /* Pick up virt-specifiers. */
12695 virt_specifiers = declarator->u.function.virt_specifiers;
12696 /* And ref-qualifier, too */
12697 rqual = declarator->u.function.ref_qualifier;
12698 /* And tx-qualifier. */
12699 tree tx_qual = declarator->u.function.tx_qualifier;
12700 /* Pick up the exception specifications. */
12701 raises = declarator->u.function.exception_specification;
12702 /* If the exception-specification is ill-formed, let's pretend
12703 there wasn't one. */
12704 if (raises == error_mark_node)
12705 raises = NULL_TREE;
12707 if (reqs)
12708 error_at (location_of (reqs), "requires-clause on return type");
12709 reqs = declarator->u.function.requires_clause;
12711 /* Say it's a definition only for the CALL_EXPR
12712 closest to the identifier. */
12713 funcdecl_p = inner_declarator && inner_declarator->kind == cdk_id;
12715 /* Handle a late-specified return type. */
12716 tree late_return_type = declarator->u.function.late_return_type;
12717 if (tree auto_node = type_uses_auto (type))
12719 if (!late_return_type)
12721 if (!funcdecl_p)
12722 /* auto (*fp)() = f; is OK. */;
12723 else if (current_class_type
12724 && LAMBDA_TYPE_P (current_class_type))
12725 /* OK for C++11 lambdas. */;
12726 else if (cxx_dialect < cxx14)
12728 error_at (typespec_loc, "%qs function uses "
12729 "%<auto%> type specifier without "
12730 "trailing return type", name);
12731 inform (typespec_loc,
12732 "deduced return type only available "
12733 "with %<-std=c++14%> or %<-std=gnu++14%>");
12735 else if (virtualp)
12737 error_at (typespec_loc, "virtual function "
12738 "cannot have deduced return type");
12739 virtualp = false;
12742 else if (!is_auto (type) && sfk != sfk_conversion)
12744 error_at (typespec_loc, "%qs function with trailing "
12745 "return type has %qT as its type rather "
12746 "than plain %<auto%>", name, type);
12747 return error_mark_node;
12749 else if (is_auto (type) && AUTO_IS_DECLTYPE (type))
12751 if (funcdecl_p)
12752 error_at (typespec_loc,
12753 "%qs function with trailing return type "
12754 "has %<decltype(auto)%> as its type "
12755 "rather than plain %<auto%>", name);
12756 else
12757 error_at (typespec_loc,
12758 "invalid use of %<decltype(auto)%>");
12759 return error_mark_node;
12761 tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node);
12762 if (!tmpl)
12763 if (tree late_auto = type_uses_auto (late_return_type))
12764 tmpl = CLASS_PLACEHOLDER_TEMPLATE (late_auto);
12765 if (tmpl)
12767 if (!funcdecl_p || !dguide_name_p (unqualified_id))
12769 error_at (typespec_loc, "deduced class "
12770 "type %qD in function return type",
12771 DECL_NAME (tmpl));
12772 inform (DECL_SOURCE_LOCATION (tmpl),
12773 "%qD declared here", tmpl);
12774 return error_mark_node;
12776 else if (!late_return_type)
12778 error_at (declarator->id_loc, "deduction guide "
12779 "for %qT must have trailing return "
12780 "type", TREE_TYPE (tmpl));
12781 inform (DECL_SOURCE_LOCATION (tmpl),
12782 "%qD declared here", tmpl);
12783 return error_mark_node;
12785 else if (CLASS_TYPE_P (late_return_type)
12786 && CLASSTYPE_TEMPLATE_INFO (late_return_type)
12787 && (CLASSTYPE_TI_TEMPLATE (late_return_type)
12788 == tmpl))
12789 /* OK */;
12790 else
12791 error ("trailing return type %qT of deduction guide "
12792 "is not a specialization of %qT",
12793 late_return_type, TREE_TYPE (tmpl));
12796 else if (late_return_type
12797 && sfk != sfk_conversion)
12799 if (late_return_type == error_mark_node)
12800 return error_mark_node;
12801 if (cxx_dialect < cxx11)
12802 /* Not using maybe_warn_cpp0x because this should
12803 always be an error. */
12804 error_at (typespec_loc,
12805 "trailing return type only available "
12806 "with %<-std=c++11%> or %<-std=gnu++11%>");
12807 else
12808 error_at (typespec_loc, "%qs function with trailing "
12809 "return type not declared with %<auto%> "
12810 "type specifier", name);
12811 return error_mark_node;
12813 type = splice_late_return_type (type, late_return_type);
12814 if (type == error_mark_node)
12815 return error_mark_node;
12817 if (late_return_type)
12819 late_return_type_p = true;
12820 type_quals = cp_type_quals (type);
12823 if (type_quals != TYPE_UNQUALIFIED)
12825 if (SCALAR_TYPE_P (type) || VOID_TYPE_P (type))
12826 warning_at (typespec_loc, OPT_Wignored_qualifiers, "type "
12827 "qualifiers ignored on function return type");
12828 /* [dcl.fct] "A volatile-qualified return type is
12829 deprecated." */
12830 if (type_quals & TYPE_QUAL_VOLATILE)
12831 warning_at (typespec_loc, OPT_Wvolatile,
12832 "%<volatile%>-qualified return type is "
12833 "deprecated");
12835 /* We now know that the TYPE_QUALS don't apply to the
12836 decl, but to its return type. */
12837 type_quals = TYPE_UNQUALIFIED;
12840 /* Error about some types functions can't return. */
12842 if (TREE_CODE (type) == FUNCTION_TYPE)
12844 error_at (typespec_loc, "%qs declared as function returning "
12845 "a function", name);
12846 return error_mark_node;
12848 if (TREE_CODE (type) == ARRAY_TYPE)
12850 error_at (typespec_loc, "%qs declared as function returning "
12851 "an array", name);
12852 return error_mark_node;
12854 if (constinit_p)
12856 error_at (declspecs->locations[ds_constinit],
12857 "%<constinit%> on function return type is not "
12858 "allowed");
12859 return error_mark_node;
12862 if (check_decltype_auto (typespec_loc, type))
12863 return error_mark_node;
12865 if (ctype == NULL_TREE
12866 && decl_context == FIELD
12867 && funcdecl_p
12868 && friendp == 0)
12869 ctype = current_class_type;
12871 if (ctype && (sfk == sfk_constructor
12872 || sfk == sfk_destructor))
12874 /* We are within a class's scope. If our declarator name
12875 is the same as the class name, and we are defining
12876 a function, then it is a constructor/destructor, and
12877 therefore returns a void type. */
12879 /* ISO C++ 12.4/2. A destructor may not be declared
12880 const or volatile. A destructor may not be static.
12881 A destructor may not be declared with ref-qualifier.
12883 ISO C++ 12.1. A constructor may not be declared
12884 const or volatile. A constructor may not be
12885 virtual. A constructor may not be static.
12886 A constructor may not be declared with ref-qualifier. */
12887 if (staticp == 2)
12888 error_at (declspecs->locations[ds_storage_class],
12889 (flags == DTOR_FLAG)
12890 ? G_("destructor cannot be static member "
12891 "function")
12892 : G_("constructor cannot be static member "
12893 "function"));
12894 if (memfn_quals)
12896 error ((flags == DTOR_FLAG)
12897 ? G_("destructors may not be cv-qualified")
12898 : G_("constructors may not be cv-qualified"));
12899 memfn_quals = TYPE_UNQUALIFIED;
12902 if (rqual)
12904 maybe_warn_cpp0x (CPP0X_REF_QUALIFIER);
12905 error ((flags == DTOR_FLAG)
12906 ? G_("destructors may not be ref-qualified")
12907 : G_("constructors may not be ref-qualified"));
12908 rqual = REF_QUAL_NONE;
12911 if (decl_context == FIELD
12912 && !member_function_or_else (ctype,
12913 current_class_type,
12914 flags))
12915 return error_mark_node;
12917 if (flags != DTOR_FLAG)
12919 /* It's a constructor. */
12920 if (explicitp == 1)
12921 explicitp = 2;
12922 if (virtualp)
12924 permerror (declspecs->locations[ds_virtual],
12925 "constructors cannot be declared %<virtual%>");
12926 virtualp = 0;
12928 if (decl_context == FIELD
12929 && sfk != sfk_constructor)
12930 return error_mark_node;
12932 if (decl_context == FIELD)
12933 staticp = 0;
12935 else if (friendp)
12937 if (virtualp)
12939 /* Cannot be both friend and virtual. */
12940 gcc_rich_location richloc (declspecs->locations[ds_virtual]);
12941 richloc.add_range (declspecs->locations[ds_friend]);
12942 error_at (&richloc, "virtual functions cannot be friends");
12943 friendp = 0;
12945 if (decl_context == NORMAL)
12946 error_at (declarator->id_loc,
12947 "friend declaration not in class definition");
12948 if (current_function_decl && funcdef_flag)
12950 error_at (declarator->id_loc,
12951 "cannot define friend function %qs in a local "
12952 "class definition", name);
12953 friendp = 0;
12955 /* [class.friend]/6: A function can be defined in a friend
12956 declaration if the function name is unqualified. */
12957 if (funcdef_flag && in_namespace)
12959 if (in_namespace == global_namespace)
12960 error_at (declarator->id_loc,
12961 "friend function definition %qs cannot have "
12962 "a name qualified with %<::%>", name);
12963 else
12964 error_at (declarator->id_loc,
12965 "friend function definition %qs cannot have "
12966 "a name qualified with %<%D::%>", name,
12967 in_namespace);
12970 else if (ctype && sfk == sfk_conversion)
12972 if (explicitp == 1)
12974 maybe_warn_cpp0x (CPP0X_EXPLICIT_CONVERSION);
12975 explicitp = 2;
12977 if (late_return_type_p)
12978 error ("a conversion function cannot have a trailing return type");
12980 else if (sfk == sfk_deduction_guide)
12982 if (explicitp == 1)
12983 explicitp = 2;
12986 tree pushed_scope = NULL_TREE;
12987 if (funcdecl_p
12988 && decl_context != FIELD
12989 && inner_declarator->u.id.qualifying_scope
12990 && CLASS_TYPE_P (inner_declarator->u.id.qualifying_scope))
12991 pushed_scope
12992 = push_scope (inner_declarator->u.id.qualifying_scope);
12994 arg_types = grokparms (declarator->u.function.parameters, &parms);
12996 if (pushed_scope)
12997 pop_scope (pushed_scope);
12999 if (inner_declarator
13000 && inner_declarator->kind == cdk_id
13001 && inner_declarator->u.id.sfk == sfk_destructor
13002 && arg_types != void_list_node)
13004 error_at (declarator->id_loc,
13005 "destructors may not have parameters");
13006 arg_types = void_list_node;
13007 parms = NULL_TREE;
13010 type = build_function_type (type, arg_types);
13012 tree attrs = declarator->std_attributes;
13013 if (tx_qual)
13015 tree att = build_tree_list (tx_qual, NULL_TREE);
13016 /* transaction_safe applies to the type, but
13017 transaction_safe_dynamic applies to the function. */
13018 if (is_attribute_p ("transaction_safe", tx_qual))
13019 attrs = chainon (attrs, att);
13020 else
13021 returned_attrs = chainon (returned_attrs, att);
13023 if (attrs)
13024 /* [dcl.fct]/2:
13026 The optional attribute-specifier-seq appertains to
13027 the function type. */
13028 cplus_decl_attributes (&type, attrs, 0);
13030 if (raises)
13031 type = build_exception_variant (type, raises);
13033 break;
13035 case cdk_pointer:
13036 case cdk_reference:
13037 case cdk_ptrmem:
13038 /* Filter out pointers-to-references and references-to-references.
13039 We can get these if a TYPE_DECL is used. */
13041 if (TYPE_REF_P (type))
13043 if (declarator->kind != cdk_reference)
13045 error ("cannot declare pointer to %q#T", type);
13046 type = TREE_TYPE (type);
13049 /* In C++0x, we allow reference to reference declarations
13050 that occur indirectly through typedefs [7.1.3/8 dcl.typedef]
13051 and template type arguments [14.3.1/4 temp.arg.type]. The
13052 check for direct reference to reference declarations, which
13053 are still forbidden, occurs below. Reasoning behind the change
13054 can be found in DR106, DR540, and the rvalue reference
13055 proposals. */
13056 else if (cxx_dialect == cxx98)
13058 error ("cannot declare reference to %q#T", type);
13059 type = TREE_TYPE (type);
13062 else if (VOID_TYPE_P (type))
13064 if (declarator->kind == cdk_reference)
13065 error ("cannot declare reference to %q#T", type);
13066 else if (declarator->kind == cdk_ptrmem)
13067 error ("cannot declare pointer to %q#T member", type);
13070 /* We now know that the TYPE_QUALS don't apply to the decl,
13071 but to the target of the pointer. */
13072 type_quals = TYPE_UNQUALIFIED;
13074 /* This code used to handle METHOD_TYPE, but I don't think it's
13075 possible to get it here anymore. */
13076 gcc_assert (TREE_CODE (type) != METHOD_TYPE);
13077 if (declarator->kind == cdk_ptrmem
13078 && TREE_CODE (type) == FUNCTION_TYPE)
13080 memfn_quals |= type_memfn_quals (type);
13081 type = build_memfn_type (type,
13082 declarator->u.pointer.class_type,
13083 memfn_quals,
13084 rqual);
13085 if (type == error_mark_node)
13086 return error_mark_node;
13088 rqual = REF_QUAL_NONE;
13089 memfn_quals = TYPE_UNQUALIFIED;
13092 if (TREE_CODE (type) == FUNCTION_TYPE
13093 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
13094 || type_memfn_rqual (type) != REF_QUAL_NONE))
13095 error (declarator->kind == cdk_reference
13096 ? G_("cannot declare reference to qualified function type %qT")
13097 : G_("cannot declare pointer to qualified function type %qT"),
13098 type);
13100 /* When the pointed-to type involves components of variable size,
13101 care must be taken to ensure that the size evaluation code is
13102 emitted early enough to dominate all the possible later uses
13103 and late enough for the variables on which it depends to have
13104 been assigned.
13106 This is expected to happen automatically when the pointed-to
13107 type has a name/declaration of it's own, but special attention
13108 is required if the type is anonymous.
13110 We handle the NORMAL and FIELD contexts here by inserting a
13111 dummy statement that just evaluates the size at a safe point
13112 and ensures it is not deferred until e.g. within a deeper
13113 conditional context (c++/43555).
13115 We expect nothing to be needed here for PARM or TYPENAME.
13116 Evaluating the size at this point for TYPENAME would
13117 actually be incorrect, as we might be in the middle of an
13118 expression with side effects on the pointed-to type size
13119 "arguments" prior to the pointer declaration point and the
13120 size evaluation could end up prior to the side effects. */
13122 if (!TYPE_NAME (type)
13123 && (decl_context == NORMAL || decl_context == FIELD)
13124 && at_function_scope_p ()
13125 && variably_modified_type_p (type, NULL_TREE))
13127 TYPE_NAME (type) = build_decl (UNKNOWN_LOCATION, TYPE_DECL,
13128 NULL_TREE, type);
13129 add_decl_expr (TYPE_NAME (type));
13132 if (declarator->kind == cdk_reference)
13134 /* In C++0x, the type we are creating a reference to might be
13135 a typedef which is itself a reference type. In that case,
13136 we follow the reference collapsing rules in
13137 [7.1.3/8 dcl.typedef] to create the final reference type:
13139 "If a typedef TD names a type that is a reference to a type
13140 T, an attempt to create the type 'lvalue reference to cv TD'
13141 creates the type 'lvalue reference to T,' while an attempt
13142 to create the type "rvalue reference to cv TD' creates the
13143 type TD."
13145 if (VOID_TYPE_P (type))
13146 /* We already gave an error. */;
13147 else if (TYPE_REF_P (type))
13149 if (declarator->u.reference.rvalue_ref)
13150 /* Leave type alone. */;
13151 else
13152 type = cp_build_reference_type (TREE_TYPE (type), false);
13154 else
13155 type = cp_build_reference_type
13156 (type, declarator->u.reference.rvalue_ref);
13158 /* In C++0x, we need this check for direct reference to
13159 reference declarations, which are forbidden by
13160 [8.3.2/5 dcl.ref]. Reference to reference declarations
13161 are only allowed indirectly through typedefs and template
13162 type arguments. Example:
13164 void foo(int & &); // invalid ref-to-ref decl
13166 typedef int & int_ref;
13167 void foo(int_ref &); // valid ref-to-ref decl
13169 if (inner_declarator && inner_declarator->kind == cdk_reference)
13170 error ("cannot declare reference to %q#T, which is not "
13171 "a typedef or a template type argument", type);
13173 else if (TREE_CODE (type) == METHOD_TYPE)
13174 type = build_ptrmemfunc_type (build_pointer_type (type));
13175 else if (declarator->kind == cdk_ptrmem)
13177 gcc_assert (TREE_CODE (declarator->u.pointer.class_type)
13178 != NAMESPACE_DECL);
13179 if (declarator->u.pointer.class_type == error_mark_node)
13180 /* We will already have complained. */
13181 type = error_mark_node;
13182 else
13183 type = build_ptrmem_type (declarator->u.pointer.class_type,
13184 type);
13186 else
13187 type = build_pointer_type (type);
13189 /* Process a list of type modifier keywords (such as
13190 const or volatile) that were given inside the `*' or `&'. */
13192 if (declarator->u.pointer.qualifiers)
13194 type
13195 = cp_build_qualified_type (type,
13196 declarator->u.pointer.qualifiers);
13197 type_quals = cp_type_quals (type);
13200 /* Apply C++11 attributes to the pointer, and not to the
13201 type pointed to. This is unlike what is done for GNU
13202 attributes above. It is to comply with [dcl.ptr]/1:
13204 [the optional attribute-specifier-seq (7.6.1) appertains
13205 to the pointer and not to the object pointed to]. */
13206 if (declarator->std_attributes)
13207 decl_attributes (&type, declarator->std_attributes,
13210 ctype = NULL_TREE;
13211 break;
13213 case cdk_error:
13214 break;
13216 default:
13217 gcc_unreachable ();
13221 id_loc = declarator ? declarator->id_loc : input_location;
13223 if (innermost_code != cdk_function
13224 /* Don't check this if it can be the artifical decltype(auto)
13225 we created when building a constraint in a compound-requirement:
13226 that the type-constraint is plain is going to be checked in
13227 cp_parser_compound_requirement. */
13228 && decl_context != TYPENAME
13229 && check_decltype_auto (id_loc, type))
13230 return error_mark_node;
13232 /* A `constexpr' specifier used in an object declaration declares
13233 the object as `const'. */
13234 if (constexpr_p && innermost_code != cdk_function)
13236 /* DR1688 says that a `constexpr' specifier in combination with
13237 `volatile' is valid. */
13239 if (!TYPE_REF_P (type))
13241 type_quals |= TYPE_QUAL_CONST;
13242 type = cp_build_qualified_type (type, type_quals);
13246 if (unqualified_id && TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR
13247 && !FUNC_OR_METHOD_TYPE_P (type)
13248 && !variable_template_p (TREE_OPERAND (unqualified_id, 0)))
13250 error ("template-id %qD used as a declarator",
13251 unqualified_id);
13252 unqualified_id = dname;
13255 /* If TYPE is a FUNCTION_TYPE, but the function name was explicitly
13256 qualified with a class-name, turn it into a METHOD_TYPE, unless
13257 we know that the function is static. We take advantage of this
13258 opportunity to do other processing that pertains to entities
13259 explicitly declared to be class members. Note that if DECLARATOR
13260 is non-NULL, we know it is a cdk_id declarator; otherwise, we
13261 would not have exited the loop above. */
13262 if (declarator
13263 && declarator->kind == cdk_id
13264 && declarator->u.id.qualifying_scope
13265 && MAYBE_CLASS_TYPE_P (declarator->u.id.qualifying_scope))
13267 ctype = declarator->u.id.qualifying_scope;
13268 ctype = TYPE_MAIN_VARIANT (ctype);
13269 template_count = num_template_headers_for_class (ctype);
13271 if (ctype == current_class_type)
13273 if (friendp)
13275 permerror (declspecs->locations[ds_friend],
13276 "member functions are implicitly "
13277 "friends of their class");
13278 friendp = 0;
13280 else
13281 permerror (id_loc, "extra qualification %<%T::%> on member %qs",
13282 ctype, name);
13284 else if (/* If the qualifying type is already complete, then we
13285 can skip the following checks. */
13286 !COMPLETE_TYPE_P (ctype)
13287 && (/* If the function is being defined, then
13288 qualifying type must certainly be complete. */
13289 funcdef_flag
13290 /* A friend declaration of "T::f" is OK, even if
13291 "T" is a template parameter. But, if this
13292 function is not a friend, the qualifying type
13293 must be a class. */
13294 || (!friendp && !CLASS_TYPE_P (ctype))
13295 /* For a declaration, the type need not be
13296 complete, if either it is dependent (since there
13297 is no meaningful definition of complete in that
13298 case) or the qualifying class is currently being
13299 defined. */
13300 || !(dependent_type_p (ctype)
13301 || currently_open_class (ctype)))
13302 /* Check that the qualifying type is complete. */
13303 && !complete_type_or_else (ctype, NULL_TREE))
13304 return error_mark_node;
13305 else if (TREE_CODE (type) == FUNCTION_TYPE)
13307 if (current_class_type
13308 && (!friendp || funcdef_flag || initialized))
13310 error_at (id_loc, funcdef_flag || initialized
13311 ? G_("cannot define member function %<%T::%s%> "
13312 "within %qT")
13313 : G_("cannot declare member function %<%T::%s%> "
13314 "within %qT"),
13315 ctype, name, current_class_type);
13316 return error_mark_node;
13319 else if (typedef_p && current_class_type)
13321 error_at (id_loc, "cannot declare member %<%T::%s%> within %qT",
13322 ctype, name, current_class_type);
13323 return error_mark_node;
13327 if (ctype == NULL_TREE && decl_context == FIELD && friendp == 0)
13328 ctype = current_class_type;
13330 /* Now TYPE has the actual type. */
13332 if (returned_attrs)
13334 if (attrlist)
13335 *attrlist = chainon (returned_attrs, *attrlist);
13336 else
13337 attrlist = &returned_attrs;
13340 if (declarator
13341 && declarator->kind == cdk_id
13342 && declarator->std_attributes
13343 && attrlist != NULL)
13345 /* [dcl.meaning]/1: The optional attribute-specifier-seq following
13346 a declarator-id appertains to the entity that is declared. */
13347 if (declarator->std_attributes != error_mark_node)
13348 *attrlist = chainon (*attrlist, declarator->std_attributes);
13349 else
13350 /* We should have already diagnosed the issue (c++/78344). */
13351 gcc_assert (seen_error ());
13354 /* Handle parameter packs. */
13355 if (parameter_pack_p)
13357 if (decl_context == PARM)
13358 /* Turn the type into a pack expansion.*/
13359 type = make_pack_expansion (type);
13360 else
13361 error ("non-parameter %qs cannot be a parameter pack", name);
13364 if ((decl_context == FIELD || decl_context == PARM)
13365 && !processing_template_decl
13366 && variably_modified_type_p (type, NULL_TREE))
13368 if (decl_context == FIELD)
13369 error_at (id_loc,
13370 "data member may not have variably modified type %qT", type);
13371 else
13372 error_at (id_loc,
13373 "parameter may not have variably modified type %qT", type);
13374 type = error_mark_node;
13377 if (explicitp == 1 || (explicitp && friendp))
13379 /* [dcl.fct.spec] (C++11) The explicit specifier shall be used only
13380 in the declaration of a constructor or conversion function within
13381 a class definition. */
13382 if (!current_class_type)
13383 error_at (declspecs->locations[ds_explicit],
13384 "%<explicit%> outside class declaration");
13385 else if (friendp)
13386 error_at (declspecs->locations[ds_explicit],
13387 "%<explicit%> in friend declaration");
13388 else
13389 error_at (declspecs->locations[ds_explicit],
13390 "only declarations of constructors and conversion operators "
13391 "can be %<explicit%>");
13392 explicitp = 0;
13395 if (storage_class == sc_mutable)
13397 location_t sloc = declspecs->locations[ds_storage_class];
13398 if (decl_context != FIELD || friendp)
13400 error_at (sloc, "non-member %qs cannot be declared %<mutable%>",
13401 name);
13402 storage_class = sc_none;
13404 else if (decl_context == TYPENAME || typedef_p)
13406 error_at (sloc,
13407 "non-object member %qs cannot be declared %<mutable%>",
13408 name);
13409 storage_class = sc_none;
13411 else if (FUNC_OR_METHOD_TYPE_P (type))
13413 error_at (sloc, "function %qs cannot be declared %<mutable%>",
13414 name);
13415 storage_class = sc_none;
13417 else if (staticp)
13419 error_at (sloc, "%<static%> %qs cannot be declared %<mutable%>",
13420 name);
13421 storage_class = sc_none;
13423 else if (type_quals & TYPE_QUAL_CONST)
13425 error_at (sloc, "%<const%> %qs cannot be declared %<mutable%>",
13426 name);
13427 storage_class = sc_none;
13429 else if (TYPE_REF_P (type))
13431 permerror (sloc, "reference %qs cannot be declared %<mutable%>",
13432 name);
13433 storage_class = sc_none;
13437 /* If this is declaring a typedef name, return a TYPE_DECL. */
13438 if (typedef_p && decl_context != TYPENAME)
13440 bool alias_p = decl_spec_seq_has_spec_p (declspecs, ds_alias);
13441 tree decl;
13443 if (funcdef_flag)
13445 if (decl_context == NORMAL)
13446 error_at (id_loc,
13447 "typedef may not be a function definition");
13448 else
13449 error_at (id_loc,
13450 "typedef may not be a member function definition");
13451 return error_mark_node;
13454 /* This declaration:
13456 typedef void f(int) const;
13458 declares a function type which is not a member of any
13459 particular class, but which is cv-qualified; for
13460 example "f S::*" declares a pointer to a const-qualified
13461 member function of S. We record the cv-qualification in the
13462 function type. */
13463 if ((rqual || memfn_quals) && TREE_CODE (type) == FUNCTION_TYPE)
13465 type = apply_memfn_quals (type, memfn_quals, rqual);
13467 /* We have now dealt with these qualifiers. */
13468 memfn_quals = TYPE_UNQUALIFIED;
13469 rqual = REF_QUAL_NONE;
13472 if (type_uses_auto (type))
13474 if (alias_p)
13475 error_at (declspecs->locations[ds_type_spec],
13476 "%<auto%> not allowed in alias declaration");
13477 else
13478 error_at (declspecs->locations[ds_type_spec],
13479 "typedef declared %<auto%>");
13480 type = error_mark_node;
13483 if (reqs)
13484 error_at (location_of (reqs), "requires-clause on typedef");
13486 if (id_declarator && declarator->u.id.qualifying_scope)
13488 error_at (id_loc, "typedef name may not be a nested-name-specifier");
13489 type = error_mark_node;
13492 if (decl_context == FIELD)
13493 decl = build_lang_decl_loc (id_loc, TYPE_DECL, unqualified_id, type);
13494 else
13495 decl = build_decl (id_loc, TYPE_DECL, unqualified_id, type);
13497 if (decl_context != FIELD)
13499 if (!current_function_decl)
13500 DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
13501 else if (DECL_MAYBE_IN_CHARGE_CDTOR_P (current_function_decl))
13502 /* The TYPE_DECL is "abstract" because there will be
13503 clones of this constructor/destructor, and there will
13504 be copies of this TYPE_DECL generated in those
13505 clones. The decloning optimization (for space) may
13506 revert this subsequently if it determines that
13507 the clones should share a common implementation. */
13508 DECL_ABSTRACT_P (decl) = true;
13510 set_originating_module (decl);
13512 else if (current_class_type
13513 && constructor_name_p (unqualified_id, current_class_type))
13514 permerror (id_loc, "ISO C++ forbids nested type %qD with same name "
13515 "as enclosing class",
13516 unqualified_id);
13518 /* If the user declares "typedef struct {...} foo" then the
13519 struct will have an anonymous name. Fill that name in now.
13520 Nothing can refer to it, so nothing needs know about the name
13521 change. */
13522 if (type != error_mark_node
13523 && unqualified_id
13524 && TYPE_NAME (type)
13525 && TREE_CODE (TYPE_NAME (type)) == TYPE_DECL
13526 && TYPE_UNNAMED_P (type)
13527 && declspecs->type_definition_p
13528 && attributes_naming_typedef_ok (*attrlist)
13529 && cp_type_quals (type) == TYPE_UNQUALIFIED)
13530 name_unnamed_type (type, decl);
13532 if (signed_p
13533 || (typedef_decl && C_TYPEDEF_EXPLICITLY_SIGNED (typedef_decl)))
13534 C_TYPEDEF_EXPLICITLY_SIGNED (decl) = 1;
13536 bad_specifiers (decl, BSP_TYPE, virtualp,
13537 memfn_quals != TYPE_UNQUALIFIED,
13538 inlinep, friendp, raises != NULL_TREE,
13539 declspecs->locations);
13541 if (alias_p)
13542 /* Acknowledge that this was written:
13543 `using analias = atype;'. */
13544 TYPE_DECL_ALIAS_P (decl) = 1;
13546 return decl;
13549 /* Detect the case of an array type of unspecified size
13550 which came, as such, direct from a typedef name.
13551 We must copy the type, so that the array's domain can be
13552 individually set by the object's initializer. */
13554 if (type && typedef_type
13555 && TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type)
13556 && TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (typedef_type))
13557 type = build_cplus_array_type (TREE_TYPE (type), NULL_TREE);
13559 /* Detect where we're using a typedef of function type to declare a
13560 function. PARMS will not be set, so we must create it now. */
13562 if (type == typedef_type && TREE_CODE (type) == FUNCTION_TYPE)
13564 tree decls = NULL_TREE;
13565 tree args;
13567 for (args = TYPE_ARG_TYPES (type);
13568 args && args != void_list_node;
13569 args = TREE_CHAIN (args))
13571 tree decl = cp_build_parm_decl (NULL_TREE, NULL_TREE,
13572 TREE_VALUE (args));
13574 DECL_CHAIN (decl) = decls;
13575 decls = decl;
13578 parms = nreverse (decls);
13580 if (decl_context != TYPENAME)
13582 /* The qualifiers on the function type become the qualifiers on
13583 the non-static member function. */
13584 memfn_quals |= type_memfn_quals (type);
13585 rqual = type_memfn_rqual (type);
13586 type_quals = TYPE_UNQUALIFIED;
13587 raises = TYPE_RAISES_EXCEPTIONS (type);
13591 /* If this is a type name (such as, in a cast or sizeof),
13592 compute the type and return it now. */
13594 if (decl_context == TYPENAME)
13596 /* Note that here we don't care about type_quals. */
13598 /* Special case: "friend class foo" looks like a TYPENAME context. */
13599 if (friendp)
13601 if (inlinep)
13603 error ("%<inline%> specified for friend class declaration");
13604 inlinep = 0;
13607 if (!current_aggr)
13609 /* Don't allow friend declaration without a class-key. */
13610 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
13611 permerror (input_location, "template parameters cannot be friends");
13612 else if (TREE_CODE (type) == TYPENAME_TYPE)
13613 permerror (input_location, "friend declaration requires class-key, "
13614 "i.e. %<friend class %T::%D%>",
13615 TYPE_CONTEXT (type), TYPENAME_TYPE_FULLNAME (type));
13616 else
13617 permerror (input_location, "friend declaration requires class-key, "
13618 "i.e. %<friend %#T%>",
13619 type);
13622 /* Only try to do this stuff if we didn't already give up. */
13623 if (type != integer_type_node)
13625 /* A friendly class? */
13626 if (current_class_type)
13627 make_friend_class (current_class_type, TYPE_MAIN_VARIANT (type),
13628 /*complain=*/true);
13629 else
13630 error ("trying to make class %qT a friend of global scope",
13631 type);
13633 type = void_type_node;
13636 else if (memfn_quals || rqual)
13638 if (ctype == NULL_TREE
13639 && TREE_CODE (type) == METHOD_TYPE)
13640 ctype = TYPE_METHOD_BASETYPE (type);
13642 if (ctype)
13643 type = build_memfn_type (type, ctype, memfn_quals, rqual);
13644 /* Core issue #547: need to allow this in template type args.
13645 Allow it in general in C++11 for alias-declarations. */
13646 else if ((template_type_arg || cxx_dialect >= cxx11)
13647 && TREE_CODE (type) == FUNCTION_TYPE)
13648 type = apply_memfn_quals (type, memfn_quals, rqual);
13649 else
13650 error ("invalid qualifiers on non-member function type");
13653 if (reqs)
13654 error_at (location_of (reqs), "requires-clause on type-id");
13656 return type;
13658 else if (unqualified_id == NULL_TREE && decl_context != PARM
13659 && decl_context != CATCHPARM
13660 && TREE_CODE (type) != UNION_TYPE
13661 && ! bitfield
13662 && innermost_code != cdk_decomp)
13664 error ("abstract declarator %qT used as declaration", type);
13665 return error_mark_node;
13668 if (!FUNC_OR_METHOD_TYPE_P (type))
13670 /* Only functions may be declared using an operator-function-id. */
13671 if (dname && IDENTIFIER_ANY_OP_P (dname))
13673 error_at (id_loc, "declaration of %qD as non-function", dname);
13674 return error_mark_node;
13677 if (reqs)
13678 error_at (location_of (reqs),
13679 "requires-clause on declaration of non-function type %qT",
13680 type);
13683 /* We don't check parameter types here because we can emit a better
13684 error message later. */
13685 if (decl_context != PARM)
13687 type = check_var_type (unqualified_id, type, id_loc);
13688 if (type == error_mark_node)
13689 return error_mark_node;
13692 /* Now create the decl, which may be a VAR_DECL, a PARM_DECL
13693 or a FUNCTION_DECL, depending on DECL_CONTEXT and TYPE. */
13695 if (decl_context == PARM || decl_context == CATCHPARM)
13697 if (ctype || in_namespace)
13698 error ("cannot use %<::%> in parameter declaration");
13700 tree auto_node = type_uses_auto (type);
13701 if (auto_node && !(cxx_dialect >= cxx17 && template_parm_flag))
13703 if (cxx_dialect >= cxx14)
13705 if (decl_context == PARM && AUTO_IS_DECLTYPE (auto_node))
13706 error_at (typespec_loc,
13707 "cannot declare a parameter with %<decltype(auto)%>");
13708 else if (tree c = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
13710 auto_diagnostic_group g;
13711 error_at (typespec_loc,
13712 "class template placeholder %qE not permitted "
13713 "in this context", c);
13714 if (decl_context == PARM && cxx_dialect >= cxx20)
13715 inform (typespec_loc, "use %<auto%> for an "
13716 "abbreviated function template");
13718 else
13719 error_at (typespec_loc,
13720 "%<auto%> parameter not permitted in this context");
13722 else
13723 error_at (typespec_loc, "parameter declared %<auto%>");
13724 type = error_mark_node;
13727 /* A parameter declared as an array of T is really a pointer to T.
13728 One declared as a function is really a pointer to a function.
13729 One declared as a member is really a pointer to member. */
13731 if (TREE_CODE (type) == ARRAY_TYPE)
13733 /* Transfer const-ness of array into that of type pointed to. */
13734 type = build_pointer_type (TREE_TYPE (type));
13735 type_quals = TYPE_UNQUALIFIED;
13736 array_parameter_p = true;
13738 else if (TREE_CODE (type) == FUNCTION_TYPE)
13739 type = build_pointer_type (type);
13742 if (ctype && TREE_CODE (type) == FUNCTION_TYPE && staticp < 2
13743 && !(unqualified_id
13744 && identifier_p (unqualified_id)
13745 && IDENTIFIER_NEWDEL_OP_P (unqualified_id)))
13747 cp_cv_quals real_quals = memfn_quals;
13748 if (cxx_dialect < cxx14 && constexpr_p
13749 && sfk != sfk_constructor && sfk != sfk_destructor)
13750 real_quals |= TYPE_QUAL_CONST;
13751 type = build_memfn_type (type, ctype, real_quals, rqual);
13755 tree decl = NULL_TREE;
13757 if (decl_context == PARM)
13759 decl = cp_build_parm_decl (NULL_TREE, unqualified_id, type);
13760 DECL_ARRAY_PARAMETER_P (decl) = array_parameter_p;
13762 bad_specifiers (decl, BSP_PARM, virtualp,
13763 memfn_quals != TYPE_UNQUALIFIED,
13764 inlinep, friendp, raises != NULL_TREE,
13765 declspecs->locations);
13767 else if (decl_context == FIELD)
13769 if (!staticp && !friendp && !FUNC_OR_METHOD_TYPE_P (type))
13770 if (tree auto_node = type_uses_auto (type))
13772 location_t tloc = declspecs->locations[ds_type_spec];
13773 if (CLASS_PLACEHOLDER_TEMPLATE (auto_node))
13774 error_at (tloc, "invalid use of template-name %qE without an "
13775 "argument list",
13776 CLASS_PLACEHOLDER_TEMPLATE (auto_node));
13777 else
13778 error_at (tloc, "non-static data member declared with "
13779 "placeholder %qT", auto_node);
13780 type = error_mark_node;
13783 /* The C99 flexible array extension. */
13784 if (!staticp && TREE_CODE (type) == ARRAY_TYPE
13785 && TYPE_DOMAIN (type) == NULL_TREE)
13787 if (ctype
13788 && (TREE_CODE (ctype) == UNION_TYPE
13789 || TREE_CODE (ctype) == QUAL_UNION_TYPE))
13791 error_at (id_loc, "flexible array member in union");
13792 type = error_mark_node;
13794 else
13796 /* Array is a flexible member. */
13797 if (name)
13798 pedwarn (id_loc, OPT_Wpedantic,
13799 "ISO C++ forbids flexible array member %qs", name);
13800 else
13801 pedwarn (input_location, OPT_Wpedantic,
13802 "ISO C++ forbids flexible array members");
13804 /* Flexible array member has a null domain. */
13805 type = build_cplus_array_type (TREE_TYPE (type), NULL_TREE);
13809 if (type == error_mark_node)
13811 /* Happens when declaring arrays of sizes which
13812 are error_mark_node, for example. */
13813 decl = NULL_TREE;
13815 else if (in_namespace && !friendp)
13817 /* Something like struct S { int N::j; }; */
13818 error_at (id_loc, "invalid use of %<::%>");
13819 return error_mark_node;
13821 else if (FUNC_OR_METHOD_TYPE_P (type) && unqualified_id)
13823 int publicp = 0;
13824 tree function_context;
13826 if (friendp == 0)
13828 /* This should never happen in pure C++ (the check
13829 could be an assert). It could happen in
13830 Objective-C++ if someone writes invalid code that
13831 uses a function declaration for an instance
13832 variable or property (instance variables and
13833 properties are parsed as FIELD_DECLs, but they are
13834 part of an Objective-C class, not a C++ class).
13835 That code is invalid and is caught by this
13836 check. */
13837 if (!ctype)
13839 error ("declaration of function %qD in invalid context",
13840 unqualified_id);
13841 return error_mark_node;
13844 /* ``A union may [ ... ] not [ have ] virtual functions.''
13845 ARM 9.5 */
13846 if (virtualp && TREE_CODE (ctype) == UNION_TYPE)
13848 error_at (declspecs->locations[ds_virtual],
13849 "function %qD declared %<virtual%> inside a union",
13850 unqualified_id);
13851 return error_mark_node;
13854 if (virtualp
13855 && identifier_p (unqualified_id)
13856 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
13858 error_at (declspecs->locations[ds_virtual],
13859 "%qD cannot be declared %<virtual%>, since it "
13860 "is always static", unqualified_id);
13861 virtualp = 0;
13865 /* Check that the name used for a destructor makes sense. */
13866 if (sfk == sfk_destructor)
13868 tree uqname = id_declarator->u.id.unqualified_name;
13870 if (!ctype)
13872 gcc_assert (friendp);
13873 error_at (id_loc, "expected qualified name in friend "
13874 "declaration for destructor %qD", uqname);
13875 return error_mark_node;
13878 if (!check_dtor_name (ctype, TREE_OPERAND (uqname, 0)))
13880 error_at (id_loc, "declaration of %qD as member of %qT",
13881 uqname, ctype);
13882 return error_mark_node;
13884 if (concept_p)
13886 error_at (declspecs->locations[ds_concept],
13887 "a destructor cannot be %qs", "concept");
13888 return error_mark_node;
13890 if (constexpr_p && cxx_dialect < cxx20)
13892 error_at (declspecs->locations[ds_constexpr],
13893 "%<constexpr%> destructors only available"
13894 " with %<-std=c++20%> or %<-std=gnu++20%>");
13895 return error_mark_node;
13897 if (consteval_p)
13899 error_at (declspecs->locations[ds_consteval],
13900 "a destructor cannot be %qs", "consteval");
13901 return error_mark_node;
13904 else if (sfk == sfk_constructor && friendp && !ctype)
13906 error ("expected qualified name in friend declaration "
13907 "for constructor %qD",
13908 id_declarator->u.id.unqualified_name);
13909 return error_mark_node;
13911 if (sfk == sfk_constructor)
13912 if (concept_p)
13914 error_at (declspecs->locations[ds_concept],
13915 "a constructor cannot be %<concept%>");
13916 return error_mark_node;
13918 if (concept_p)
13920 error_at (declspecs->locations[ds_concept],
13921 "a concept cannot be a member function");
13922 concept_p = false;
13924 else if (consteval_p
13925 && identifier_p (unqualified_id)
13926 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
13928 error_at (declspecs->locations[ds_consteval],
13929 "%qD cannot be %qs", unqualified_id, "consteval");
13930 consteval_p = false;
13933 if (TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
13935 tree tmpl = TREE_OPERAND (unqualified_id, 0);
13936 if (variable_template_p (tmpl))
13938 error_at (id_loc, "specialization of variable template "
13939 "%qD declared as function", tmpl);
13940 inform (DECL_SOURCE_LOCATION (tmpl),
13941 "variable template declared here");
13942 return error_mark_node;
13946 /* Tell grokfndecl if it needs to set TREE_PUBLIC on the node. */
13947 function_context
13948 = (ctype != NULL_TREE
13949 ? decl_function_context (TYPE_MAIN_DECL (ctype)) : NULL_TREE);
13950 publicp = ((! friendp || ! staticp)
13951 && function_context == NULL_TREE);
13953 decl = grokfndecl (ctype, type,
13954 TREE_CODE (unqualified_id) != TEMPLATE_ID_EXPR
13955 ? unqualified_id : dname,
13956 parms,
13957 unqualified_id,
13958 declspecs,
13959 reqs,
13960 virtualp, flags, memfn_quals, rqual, raises,
13961 friendp ? -1 : 0, friendp, publicp,
13962 inlinep | (2 * constexpr_p) | (4 * concept_p)
13963 | (8 * consteval_p),
13964 initialized == SD_DELETED, sfk,
13965 funcdef_flag, late_return_type_p,
13966 template_count, in_namespace,
13967 attrlist, id_loc);
13968 decl = set_virt_specifiers (decl, virt_specifiers);
13969 if (decl == NULL_TREE)
13970 return error_mark_node;
13971 #if 0
13972 /* This clobbers the attrs stored in `decl' from `attrlist'. */
13973 /* The decl and setting of decl_attr is also turned off. */
13974 decl = build_decl_attribute_variant (decl, decl_attr);
13975 #endif
13977 /* [class.conv.ctor]
13979 A constructor declared without the function-specifier
13980 explicit that can be called with a single parameter
13981 specifies a conversion from the type of its first
13982 parameter to the type of its class. Such a constructor
13983 is called a converting constructor. */
13984 if (explicitp == 2)
13985 DECL_NONCONVERTING_P (decl) = 1;
13987 if (declspecs->explicit_specifier)
13988 store_explicit_specifier (decl, declspecs->explicit_specifier);
13990 else if (!staticp
13991 && ((current_class_type
13992 && same_type_p (type, current_class_type))
13993 || (!dependent_type_p (type)
13994 && !COMPLETE_TYPE_P (complete_type (type))
13995 && (!complete_or_array_type_p (type)
13996 || initialized == SD_UNINITIALIZED))))
13998 if (TREE_CODE (type) != ARRAY_TYPE
13999 || !COMPLETE_TYPE_P (TREE_TYPE (type)))
14001 if (unqualified_id)
14003 error_at (id_loc, "field %qD has incomplete type %qT",
14004 unqualified_id, type);
14005 cxx_incomplete_type_inform (strip_array_types (type));
14007 else
14008 error ("name %qT has incomplete type", type);
14010 type = error_mark_node;
14011 decl = NULL_TREE;
14014 else if (!verify_type_context (input_location,
14015 staticp
14016 ? TCTX_STATIC_STORAGE
14017 : TCTX_FIELD, type))
14019 type = error_mark_node;
14020 decl = NULL_TREE;
14022 else
14024 if (friendp)
14026 if (unqualified_id)
14027 error_at (id_loc,
14028 "%qE is neither function nor member function; "
14029 "cannot be declared friend", unqualified_id);
14030 else
14031 error ("unnamed field is neither function nor member "
14032 "function; cannot be declared friend");
14033 return error_mark_node;
14035 decl = NULL_TREE;
14038 if (friendp)
14040 /* Packages tend to use GNU attributes on friends, so we only
14041 warn for standard attributes. */
14042 if (attrlist && !funcdef_flag && cxx11_attribute_p (*attrlist))
14044 *attrlist = NULL_TREE;
14045 if (warning_at (id_loc, OPT_Wattributes, "attribute ignored"))
14046 inform (id_loc, "an attribute that appertains to a friend "
14047 "declaration that is not a definition is ignored");
14049 /* Friends are treated specially. */
14050 if (ctype == current_class_type)
14051 ; /* We already issued a permerror. */
14052 else if (decl && DECL_NAME (decl))
14054 set_originating_module (decl, true);
14056 if (initialized)
14057 /* Kludge: We need funcdef_flag to be true in do_friend for
14058 in-class defaulted functions, but that breaks grokfndecl.
14059 So set it here. */
14060 funcdef_flag = true;
14062 if (template_class_depth (current_class_type) == 0)
14064 decl = check_explicit_specialization
14065 (unqualified_id, decl, template_count,
14066 2 * funcdef_flag + 4);
14067 if (decl == error_mark_node)
14068 return error_mark_node;
14071 decl = do_friend (ctype, unqualified_id, decl,
14072 flags, funcdef_flag);
14073 return decl;
14075 else
14076 return error_mark_node;
14079 /* Structure field. It may not be a function, except for C++. */
14081 if (decl == NULL_TREE)
14083 if (staticp)
14085 /* C++ allows static class members. All other work
14086 for this is done by grokfield. */
14087 decl = build_lang_decl_loc (id_loc, VAR_DECL,
14088 unqualified_id, type);
14089 set_linkage_for_static_data_member (decl);
14090 if (concept_p)
14091 error_at (declspecs->locations[ds_concept],
14092 "static data member %qE declared %qs",
14093 unqualified_id, "concept");
14094 else if (constexpr_p && !initialized)
14096 error_at (DECL_SOURCE_LOCATION (decl),
14097 "%<constexpr%> static data member %qD must "
14098 "have an initializer", decl);
14099 constexpr_p = false;
14101 if (consteval_p)
14102 error_at (declspecs->locations[ds_consteval],
14103 "static data member %qE declared %qs",
14104 unqualified_id, "consteval");
14106 if (inlinep)
14107 mark_inline_variable (decl, declspecs->locations[ds_inline]);
14109 if (!DECL_VAR_DECLARED_INLINE_P (decl)
14110 && !(cxx_dialect >= cxx17 && constexpr_p))
14111 /* Even if there is an in-class initialization, DECL
14112 is considered undefined until an out-of-class
14113 definition is provided, unless this is an inline
14114 variable. */
14115 DECL_EXTERNAL (decl) = 1;
14117 if (thread_p)
14119 CP_DECL_THREAD_LOCAL_P (decl) = true;
14120 if (!processing_template_decl)
14121 set_decl_tls_model (decl, decl_default_tls_model (decl));
14122 if (declspecs->gnu_thread_keyword_p)
14123 SET_DECL_GNU_TLS_P (decl);
14126 /* Set the constraints on the declaration. */
14127 bool memtmpl = (current_template_depth
14128 > template_class_depth (current_class_type));
14129 if (memtmpl)
14131 tree tmpl_reqs
14132 = TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
14133 tree ci = build_constraints (tmpl_reqs, NULL_TREE);
14134 set_constraints (decl, ci);
14137 else
14139 if (concept_p)
14141 error_at (declspecs->locations[ds_concept],
14142 "non-static data member %qE declared %qs",
14143 unqualified_id, "concept");
14144 concept_p = false;
14145 constexpr_p = false;
14147 else if (constexpr_p)
14149 error_at (declspecs->locations[ds_constexpr],
14150 "non-static data member %qE declared %qs",
14151 unqualified_id, "constexpr");
14152 constexpr_p = false;
14154 if (constinit_p)
14156 error_at (declspecs->locations[ds_constinit],
14157 "non-static data member %qE declared %qs",
14158 unqualified_id, "constinit");
14159 constinit_p = false;
14161 if (consteval_p)
14163 error_at (declspecs->locations[ds_consteval],
14164 "non-static data member %qE declared %qs",
14165 unqualified_id, "consteval");
14166 consteval_p = false;
14168 decl = build_decl (id_loc, FIELD_DECL, unqualified_id, type);
14169 DECL_NONADDRESSABLE_P (decl) = bitfield;
14170 if (bitfield && !unqualified_id)
14171 DECL_PADDING_P (decl) = 1;
14173 if (storage_class == sc_mutable)
14175 DECL_MUTABLE_P (decl) = 1;
14176 storage_class = sc_none;
14179 if (initialized)
14181 /* An attempt is being made to initialize a non-static
14182 member. This is new in C++11. */
14183 maybe_warn_cpp0x (CPP0X_NSDMI, init_loc);
14185 /* If this has been parsed with static storage class, but
14186 errors forced staticp to be cleared, ensure NSDMI is
14187 not present. */
14188 if (declspecs->storage_class == sc_static)
14189 DECL_INITIAL (decl) = error_mark_node;
14193 bad_specifiers (decl, BSP_FIELD, virtualp,
14194 memfn_quals != TYPE_UNQUALIFIED,
14195 staticp ? false : inlinep, friendp,
14196 raises != NULL_TREE,
14197 declspecs->locations);
14200 else if (FUNC_OR_METHOD_TYPE_P (type))
14202 tree original_name;
14203 int publicp = 0;
14205 if (!unqualified_id)
14206 return error_mark_node;
14208 if (TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
14209 original_name = dname;
14210 else
14211 original_name = unqualified_id;
14212 // FIXME:gcc_assert (original_name == dname);
14214 if (storage_class == sc_auto)
14215 error_at (declspecs->locations[ds_storage_class],
14216 "storage class %<auto%> invalid for function %qs", name);
14217 else if (storage_class == sc_register)
14218 error_at (declspecs->locations[ds_storage_class],
14219 "storage class %<register%> invalid for function %qs",
14220 name);
14221 else if (thread_p)
14223 if (declspecs->gnu_thread_keyword_p)
14224 error_at (declspecs->locations[ds_thread],
14225 "storage class %<__thread%> invalid for function %qs",
14226 name);
14227 else
14228 error_at (declspecs->locations[ds_thread],
14229 "storage class %<thread_local%> invalid for "
14230 "function %qs", name);
14233 if (virt_specifiers)
14234 error ("virt-specifiers in %qs not allowed outside a class "
14235 "definition", name);
14236 /* Function declaration not at top level.
14237 Storage classes other than `extern' are not allowed
14238 and `extern' makes no difference. */
14239 if (! toplevel_bindings_p ()
14240 && (storage_class == sc_static
14241 || decl_spec_seq_has_spec_p (declspecs, ds_inline))
14242 && pedantic)
14244 if (storage_class == sc_static)
14245 pedwarn (declspecs->locations[ds_storage_class], OPT_Wpedantic,
14246 "%<static%> specifier invalid for function %qs "
14247 "declared out of global scope", name);
14248 else
14249 pedwarn (declspecs->locations[ds_inline], OPT_Wpedantic,
14250 "%<inline%> specifier invalid for function %qs "
14251 "declared out of global scope", name);
14254 if (ctype == NULL_TREE)
14256 if (virtualp)
14258 error ("virtual non-class function %qs", name);
14259 virtualp = 0;
14261 else if (sfk == sfk_constructor
14262 || sfk == sfk_destructor)
14264 error (funcdef_flag
14265 ? G_("%qs defined in a non-class scope")
14266 : G_("%qs declared in a non-class scope"), name);
14267 sfk = sfk_none;
14270 if (consteval_p
14271 && identifier_p (unqualified_id)
14272 && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
14274 error_at (declspecs->locations[ds_consteval],
14275 "%qD cannot be %qs", unqualified_id, "consteval");
14276 consteval_p = false;
14279 /* Record whether the function is public. */
14280 publicp = (ctype != NULL_TREE
14281 || storage_class != sc_static);
14283 decl = grokfndecl (ctype, type, original_name, parms, unqualified_id,
14284 declspecs,
14285 reqs, virtualp, flags, memfn_quals, rqual, raises,
14286 1, friendp,
14287 publicp,
14288 inlinep | (2 * constexpr_p) | (4 * concept_p)
14289 | (8 * consteval_p),
14290 initialized == SD_DELETED,
14291 sfk,
14292 funcdef_flag,
14293 late_return_type_p,
14294 template_count, in_namespace, attrlist,
14295 id_loc);
14296 if (decl == NULL_TREE)
14297 return error_mark_node;
14299 if (explicitp == 2)
14300 DECL_NONCONVERTING_P (decl) = 1;
14301 if (staticp == 1)
14303 int invalid_static = 0;
14305 /* Don't allow a static member function in a class, and forbid
14306 declaring main to be static. */
14307 if (TREE_CODE (type) == METHOD_TYPE)
14309 permerror (input_location, "cannot declare member function %qD to have "
14310 "static linkage", decl);
14311 invalid_static = 1;
14313 else if (current_function_decl)
14315 /* 7.1.1: There can be no static function declarations within a
14316 block. */
14317 error_at (declspecs->locations[ds_storage_class],
14318 "cannot declare static function inside another function");
14319 invalid_static = 1;
14322 if (invalid_static)
14324 staticp = 0;
14325 storage_class = sc_none;
14328 if (declspecs->explicit_specifier)
14329 store_explicit_specifier (decl, declspecs->explicit_specifier);
14331 else
14333 /* It's a variable. */
14335 /* An uninitialized decl with `extern' is a reference. */
14336 decl = grokvardecl (type, dname, unqualified_id,
14337 declspecs,
14338 initialized,
14339 type_quals,
14340 inlinep,
14341 concept_p,
14342 template_count,
14343 ctype ? ctype : in_namespace,
14344 id_loc);
14345 if (decl == NULL_TREE)
14346 return error_mark_node;
14348 bad_specifiers (decl, BSP_VAR, virtualp,
14349 memfn_quals != TYPE_UNQUALIFIED,
14350 inlinep, friendp, raises != NULL_TREE,
14351 declspecs->locations);
14353 if (ctype)
14355 DECL_CONTEXT (decl) = ctype;
14356 if (staticp == 1)
14358 permerror (declspecs->locations[ds_storage_class],
14359 "%<static%> may not be used when defining "
14360 "(as opposed to declaring) a static data member");
14361 staticp = 0;
14362 storage_class = sc_none;
14364 if (storage_class == sc_register && TREE_STATIC (decl))
14366 error ("static member %qD declared %<register%>", decl);
14367 storage_class = sc_none;
14369 if (storage_class == sc_extern && pedantic)
14371 pedwarn (input_location, OPT_Wpedantic,
14372 "cannot explicitly declare member %q#D to have "
14373 "extern linkage", decl);
14374 storage_class = sc_none;
14377 else if (constexpr_p && DECL_EXTERNAL (decl))
14379 error_at (DECL_SOURCE_LOCATION (decl),
14380 "declaration of %<constexpr%> variable %qD "
14381 "is not a definition", decl);
14382 constexpr_p = false;
14384 if (consteval_p)
14386 error_at (DECL_SOURCE_LOCATION (decl),
14387 "a variable cannot be declared %<consteval%>");
14388 consteval_p = false;
14391 if (inlinep)
14392 mark_inline_variable (decl, declspecs->locations[ds_inline]);
14393 if (innermost_code == cdk_decomp)
14395 gcc_assert (declarator && declarator->kind == cdk_decomp);
14396 DECL_SOURCE_LOCATION (decl) = id_loc;
14397 DECL_ARTIFICIAL (decl) = 1;
14398 fit_decomposition_lang_decl (decl, NULL_TREE);
14402 if (VAR_P (decl) && !initialized)
14403 if (tree auto_node = type_uses_auto (type))
14404 if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
14406 location_t loc = declspecs->locations[ds_type_spec];
14407 error_at (loc, "declaration of %q#D has no initializer", decl);
14408 TREE_TYPE (decl) = error_mark_node;
14411 if (storage_class == sc_extern && initialized && !funcdef_flag)
14413 if (toplevel_bindings_p ())
14415 /* It's common practice (and completely valid) to have a const
14416 be initialized and declared extern. */
14417 if (!(type_quals & TYPE_QUAL_CONST))
14418 warning_at (DECL_SOURCE_LOCATION (decl), 0,
14419 "%qs initialized and declared %<extern%>", name);
14421 else
14423 error_at (DECL_SOURCE_LOCATION (decl),
14424 "%qs has both %<extern%> and initializer", name);
14425 return error_mark_node;
14429 /* Record `register' declaration for warnings on &
14430 and in case doing stupid register allocation. */
14432 if (storage_class == sc_register)
14434 DECL_REGISTER (decl) = 1;
14435 /* Warn about register storage specifiers on PARM_DECLs. */
14436 if (TREE_CODE (decl) == PARM_DECL)
14438 if (cxx_dialect >= cxx17)
14439 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
14440 "ISO C++17 does not allow %<register%> storage "
14441 "class specifier");
14442 else
14443 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
14444 "%<register%> storage class specifier used");
14447 else if (storage_class == sc_extern)
14448 DECL_THIS_EXTERN (decl) = 1;
14449 else if (storage_class == sc_static)
14450 DECL_THIS_STATIC (decl) = 1;
14452 if (VAR_P (decl))
14454 /* Set constexpr flag on vars (functions got it in grokfndecl). */
14455 if (constexpr_p)
14456 DECL_DECLARED_CONSTEXPR_P (decl) = true;
14457 /* And the constinit flag (which only applies to variables). */
14458 else if (constinit_p)
14459 DECL_DECLARED_CONSTINIT_P (decl) = true;
14462 /* Record constancy and volatility on the DECL itself . There's
14463 no need to do this when processing a template; we'll do this
14464 for the instantiated declaration based on the type of DECL. */
14465 if (!processing_template_decl)
14466 cp_apply_type_quals_to_decl (type_quals, decl);
14468 return decl;
14472 /* Subroutine of start_function. Ensure that each of the parameter
14473 types (as listed in PARMS) is complete, as is required for a
14474 function definition. */
14476 static void
14477 require_complete_types_for_parms (tree parms)
14479 for (; parms; parms = DECL_CHAIN (parms))
14481 if (dependent_type_p (TREE_TYPE (parms)))
14482 continue;
14483 if (!VOID_TYPE_P (TREE_TYPE (parms))
14484 && complete_type_or_else (TREE_TYPE (parms), parms))
14486 relayout_decl (parms);
14487 DECL_ARG_TYPE (parms) = type_passed_as (TREE_TYPE (parms));
14489 abstract_virtuals_error (parms, TREE_TYPE (parms));
14490 maybe_warn_parm_abi (TREE_TYPE (parms),
14491 DECL_SOURCE_LOCATION (parms));
14493 else
14494 /* grokparms or complete_type_or_else will have already issued
14495 an error. */
14496 TREE_TYPE (parms) = error_mark_node;
14500 /* Returns nonzero if T is a local variable. */
14503 local_variable_p (const_tree t)
14505 if ((VAR_P (t)
14506 && (DECL_LOCAL_DECL_P (t)
14507 || !DECL_CONTEXT (t)
14508 || TREE_CODE (DECL_CONTEXT (t)) == FUNCTION_DECL))
14509 || (TREE_CODE (t) == PARM_DECL))
14510 return 1;
14512 return 0;
14515 /* Like local_variable_p, but suitable for use as a tree-walking
14516 function. */
14518 static tree
14519 local_variable_p_walkfn (tree *tp, int *walk_subtrees,
14520 void * /*data*/)
14522 if (unevaluated_p (TREE_CODE (*tp)))
14524 /* DR 2082 permits local variables in unevaluated contexts
14525 within a default argument. */
14526 *walk_subtrees = 0;
14527 return NULL_TREE;
14530 if (local_variable_p (*tp)
14531 && (!DECL_ARTIFICIAL (*tp) || DECL_NAME (*tp) == this_identifier))
14532 return *tp;
14533 else if (TYPE_P (*tp))
14534 *walk_subtrees = 0;
14536 return NULL_TREE;
14539 /* Check that ARG, which is a default-argument expression for a
14540 parameter DECL, is valid. Returns ARG, or ERROR_MARK_NODE, if
14541 something goes wrong. DECL may also be a _TYPE node, rather than a
14542 DECL, if there is no DECL available. */
14544 tree
14545 check_default_argument (tree decl, tree arg, tsubst_flags_t complain)
14547 tree var;
14548 tree decl_type;
14550 if (TREE_CODE (arg) == DEFERRED_PARSE)
14551 /* We get a DEFERRED_PARSE when looking at an in-class declaration
14552 with a default argument. Ignore the argument for now; we'll
14553 deal with it after the class is complete. */
14554 return arg;
14556 if (TYPE_P (decl))
14558 decl_type = decl;
14559 decl = NULL_TREE;
14561 else
14562 decl_type = TREE_TYPE (decl);
14564 if (arg == error_mark_node
14565 || decl == error_mark_node
14566 || TREE_TYPE (arg) == error_mark_node
14567 || decl_type == error_mark_node)
14568 /* Something already went wrong. There's no need to check
14569 further. */
14570 return error_mark_node;
14572 /* [dcl.fct.default]
14574 A default argument expression is implicitly converted to the
14575 parameter type. */
14576 ++cp_unevaluated_operand;
14577 /* Avoid digest_init clobbering the initializer. */
14578 tree carg = BRACE_ENCLOSED_INITIALIZER_P (arg) ? unshare_expr (arg): arg;
14579 perform_implicit_conversion_flags (decl_type, carg, complain,
14580 LOOKUP_IMPLICIT);
14581 --cp_unevaluated_operand;
14583 /* Avoid redundant -Wzero-as-null-pointer-constant warnings at
14584 the call sites. */
14585 if (TYPE_PTR_OR_PTRMEM_P (decl_type)
14586 && null_ptr_cst_p (arg)
14587 /* Don't lose side-effects as in PR90473. */
14588 && !TREE_SIDE_EFFECTS (arg))
14589 return nullptr_node;
14591 /* [dcl.fct.default]
14593 Local variables shall not be used in default argument
14594 expressions.
14596 The keyword `this' shall not be used in a default argument of a
14597 member function. */
14598 var = cp_walk_tree_without_duplicates (&arg, local_variable_p_walkfn, NULL);
14599 if (var)
14601 if (complain & tf_warning_or_error)
14603 if (DECL_NAME (var) == this_identifier)
14604 permerror (input_location, "default argument %qE uses %qD",
14605 arg, var);
14606 else
14607 error ("default argument %qE uses local variable %qD", arg, var);
14609 return error_mark_node;
14612 /* All is well. */
14613 return arg;
14616 /* Returns a deprecated type used within TYPE, or NULL_TREE if none. */
14618 static tree
14619 type_is_deprecated (tree type)
14621 enum tree_code code;
14622 if (TREE_DEPRECATED (type))
14623 return type;
14624 if (TYPE_NAME (type))
14626 if (TREE_DEPRECATED (TYPE_NAME (type)))
14627 return type;
14628 else
14630 cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (TYPE_NAME (type)));
14631 return NULL_TREE;
14635 /* Do warn about using typedefs to a deprecated class. */
14636 if (OVERLOAD_TYPE_P (type) && type != TYPE_MAIN_VARIANT (type))
14637 return type_is_deprecated (TYPE_MAIN_VARIANT (type));
14639 code = TREE_CODE (type);
14641 if (code == POINTER_TYPE || code == REFERENCE_TYPE
14642 || code == OFFSET_TYPE || code == FUNCTION_TYPE
14643 || code == METHOD_TYPE || code == ARRAY_TYPE)
14644 return type_is_deprecated (TREE_TYPE (type));
14646 if (TYPE_PTRMEMFUNC_P (type))
14647 return type_is_deprecated
14648 (TREE_TYPE (TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (type))));
14650 return NULL_TREE;
14653 /* Returns an unavailable type used within TYPE, or NULL_TREE if none. */
14655 static tree
14656 type_is_unavailable (tree type)
14658 enum tree_code code;
14659 if (TREE_UNAVAILABLE (type))
14660 return type;
14661 if (TYPE_NAME (type))
14663 if (TREE_UNAVAILABLE (TYPE_NAME (type)))
14664 return type;
14665 else
14667 cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (TYPE_NAME (type)));
14668 return NULL_TREE;
14672 /* Do warn about using typedefs to a deprecated class. */
14673 if (OVERLOAD_TYPE_P (type) && type != TYPE_MAIN_VARIANT (type))
14674 return type_is_deprecated (TYPE_MAIN_VARIANT (type));
14676 code = TREE_CODE (type);
14678 if (code == POINTER_TYPE || code == REFERENCE_TYPE
14679 || code == OFFSET_TYPE || code == FUNCTION_TYPE
14680 || code == METHOD_TYPE || code == ARRAY_TYPE)
14681 return type_is_unavailable (TREE_TYPE (type));
14683 if (TYPE_PTRMEMFUNC_P (type))
14684 return type_is_unavailable
14685 (TREE_TYPE (TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (type))));
14687 return NULL_TREE;
14690 /* Decode the list of parameter types for a function type.
14691 Given the list of things declared inside the parens,
14692 return a list of types.
14694 If this parameter does not end with an ellipsis, we append
14695 void_list_node.
14697 *PARMS is set to the chain of PARM_DECLs created. */
14699 tree
14700 grokparms (tree parmlist, tree *parms)
14702 tree result = NULL_TREE;
14703 tree decls = NULL_TREE;
14704 tree parm;
14705 int any_error = 0;
14707 for (parm = parmlist; parm != NULL_TREE; parm = TREE_CHAIN (parm))
14709 tree type = NULL_TREE;
14710 tree init = TREE_PURPOSE (parm);
14711 tree decl = TREE_VALUE (parm);
14713 if (parm == void_list_node || parm == explicit_void_list_node)
14714 break;
14716 if (! decl || TREE_TYPE (decl) == error_mark_node)
14718 any_error = 1;
14719 continue;
14722 type = TREE_TYPE (decl);
14723 if (VOID_TYPE_P (type))
14725 if (same_type_p (type, void_type_node)
14726 && !init
14727 && !DECL_NAME (decl) && !result
14728 && TREE_CHAIN (parm) == void_list_node)
14729 /* DR 577: A parameter list consisting of a single
14730 unnamed parameter of non-dependent type 'void'. */
14731 break;
14732 else if (cv_qualified_p (type))
14733 error_at (DECL_SOURCE_LOCATION (decl),
14734 "invalid use of cv-qualified type %qT in "
14735 "parameter declaration", type);
14736 else
14737 error_at (DECL_SOURCE_LOCATION (decl),
14738 "invalid use of type %<void%> in parameter "
14739 "declaration");
14740 /* It's not a good idea to actually create parameters of
14741 type `void'; other parts of the compiler assume that a
14742 void type terminates the parameter list. */
14743 type = error_mark_node;
14744 TREE_TYPE (decl) = error_mark_node;
14747 if (type != error_mark_node)
14749 if (deprecated_state != UNAVAILABLE_DEPRECATED_SUPPRESS)
14751 tree unavailtype = type_is_unavailable (type);
14752 if (unavailtype)
14753 cp_handle_deprecated_or_unavailable (unavailtype);
14755 if (deprecated_state != DEPRECATED_SUPPRESS
14756 && deprecated_state != UNAVAILABLE_DEPRECATED_SUPPRESS)
14758 tree deptype = type_is_deprecated (type);
14759 if (deptype)
14760 cp_handle_deprecated_or_unavailable (deptype);
14763 /* [dcl.fct] "A parameter with volatile-qualified type is
14764 deprecated." */
14765 if (CP_TYPE_VOLATILE_P (type))
14766 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wvolatile,
14767 "%<volatile%>-qualified parameter is "
14768 "deprecated");
14770 /* Top-level qualifiers on the parameters are
14771 ignored for function types. */
14772 type = cp_build_qualified_type (type, 0);
14773 if (TREE_CODE (type) == METHOD_TYPE)
14775 error ("parameter %qD invalidly declared method type", decl);
14776 type = build_pointer_type (type);
14777 TREE_TYPE (decl) = type;
14779 else if (cxx_dialect < cxx17 && INDIRECT_TYPE_P (type))
14781 /* Before C++17 DR 393:
14782 [dcl.fct]/6, parameter types cannot contain pointers
14783 (references) to arrays of unknown bound. */
14784 tree t = TREE_TYPE (type);
14785 int ptr = TYPE_PTR_P (type);
14787 while (1)
14789 if (TYPE_PTR_P (t))
14790 ptr = 1;
14791 else if (TREE_CODE (t) != ARRAY_TYPE)
14792 break;
14793 else if (!TYPE_DOMAIN (t))
14794 break;
14795 t = TREE_TYPE (t);
14797 if (TREE_CODE (t) == ARRAY_TYPE)
14798 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wpedantic,
14800 ? G_("parameter %qD includes pointer to array of "
14801 "unknown bound %qT")
14802 : G_("parameter %qD includes reference to array of "
14803 "unknown bound %qT"),
14804 decl, t);
14807 if (init && !processing_template_decl)
14808 init = check_default_argument (decl, init, tf_warning_or_error);
14811 DECL_CHAIN (decl) = decls;
14812 decls = decl;
14813 result = tree_cons (init, type, result);
14815 decls = nreverse (decls);
14816 result = nreverse (result);
14817 if (parm)
14818 result = chainon (result, void_list_node);
14819 *parms = decls;
14820 if (any_error)
14821 result = NULL_TREE;
14823 if (any_error)
14824 /* We had parm errors, recover by giving the function (...) type. */
14825 result = NULL_TREE;
14827 return result;
14831 /* D is a constructor or overloaded `operator='.
14833 Let T be the class in which D is declared. Then, this function
14834 returns:
14836 -1 if D's is an ill-formed constructor or copy assignment operator
14837 whose first parameter is of type `T'.
14838 0 if D is not a copy constructor or copy assignment
14839 operator.
14840 1 if D is a copy constructor or copy assignment operator whose
14841 first parameter is a reference to non-const qualified T.
14842 2 if D is a copy constructor or copy assignment operator whose
14843 first parameter is a reference to const qualified T.
14845 This function can be used as a predicate. Positive values indicate
14846 a copy constructor and nonzero values indicate a copy assignment
14847 operator. */
14850 copy_fn_p (const_tree d)
14852 tree args;
14853 tree arg_type;
14854 int result = 1;
14856 gcc_assert (DECL_FUNCTION_MEMBER_P (d));
14858 if (TREE_CODE (d) == TEMPLATE_DECL
14859 || (DECL_TEMPLATE_INFO (d)
14860 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (d))))
14861 /* Instantiations of template member functions are never copy
14862 functions. Note that member functions of templated classes are
14863 represented as template functions internally, and we must
14864 accept those as copy functions. */
14865 return 0;
14867 if (!DECL_CONSTRUCTOR_P (d)
14868 && DECL_NAME (d) != assign_op_identifier)
14869 return 0;
14871 args = FUNCTION_FIRST_USER_PARMTYPE (d);
14872 if (!args)
14873 return 0;
14875 arg_type = TREE_VALUE (args);
14876 if (arg_type == error_mark_node)
14877 return 0;
14879 if (TYPE_MAIN_VARIANT (arg_type) == DECL_CONTEXT (d))
14881 /* Pass by value copy assignment operator. */
14882 result = -1;
14884 else if (TYPE_REF_P (arg_type)
14885 && !TYPE_REF_IS_RVALUE (arg_type)
14886 && TYPE_MAIN_VARIANT (TREE_TYPE (arg_type)) == DECL_CONTEXT (d))
14888 if (CP_TYPE_CONST_P (TREE_TYPE (arg_type)))
14889 result = 2;
14891 else
14892 return 0;
14894 args = TREE_CHAIN (args);
14896 if (args && args != void_list_node && !TREE_PURPOSE (args))
14897 /* There are more non-optional args. */
14898 return 0;
14900 return result;
14903 /* D is a constructor or overloaded `operator='.
14905 Let T be the class in which D is declared. Then, this function
14906 returns true when D is a move constructor or move assignment
14907 operator, false otherwise. */
14909 bool
14910 move_fn_p (const_tree d)
14912 gcc_assert (DECL_FUNCTION_MEMBER_P (d));
14914 if (cxx_dialect == cxx98)
14915 /* There are no move constructors if we are in C++98 mode. */
14916 return false;
14918 if (TREE_CODE (d) == TEMPLATE_DECL
14919 || (DECL_TEMPLATE_INFO (d)
14920 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (d))))
14921 /* Instantiations of template member functions are never move
14922 functions. Note that member functions of templated classes are
14923 represented as template functions internally, and we must
14924 accept those as move functions. */
14925 return 0;
14927 return move_signature_fn_p (d);
14930 /* D is a constructor or overloaded `operator='.
14932 Then, this function returns true when D has the same signature as a move
14933 constructor or move assignment operator (because either it is such a
14934 ctor/op= or it is a template specialization with the same signature),
14935 false otherwise. */
14937 bool
14938 move_signature_fn_p (const_tree d)
14940 tree args;
14941 tree arg_type;
14942 bool result = false;
14944 if (!DECL_CONSTRUCTOR_P (d)
14945 && DECL_NAME (d) != assign_op_identifier)
14946 return 0;
14948 args = FUNCTION_FIRST_USER_PARMTYPE (d);
14949 if (!args)
14950 return 0;
14952 arg_type = TREE_VALUE (args);
14953 if (arg_type == error_mark_node)
14954 return 0;
14956 if (TYPE_REF_P (arg_type)
14957 && TYPE_REF_IS_RVALUE (arg_type)
14958 && same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (arg_type)),
14959 DECL_CONTEXT (d)))
14960 result = true;
14962 args = TREE_CHAIN (args);
14964 if (args && args != void_list_node && !TREE_PURPOSE (args))
14965 /* There are more non-optional args. */
14966 return false;
14968 return result;
14971 /* Remember any special properties of member function DECL. */
14973 void
14974 grok_special_member_properties (tree decl)
14976 tree class_type;
14978 if (TREE_CODE (decl) == USING_DECL
14979 || !DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
14980 return;
14982 class_type = DECL_CONTEXT (decl);
14983 if (IDENTIFIER_CTOR_P (DECL_NAME (decl)))
14985 int ctor = copy_fn_p (decl);
14987 if (!DECL_ARTIFICIAL (decl))
14988 TYPE_HAS_USER_CONSTRUCTOR (class_type) = 1;
14990 if (ctor > 0)
14992 /* [class.copy]
14994 A non-template constructor for class X is a copy
14995 constructor if its first parameter is of type X&, const
14996 X&, volatile X& or const volatile X&, and either there
14997 are no other parameters or else all other parameters have
14998 default arguments. */
14999 TYPE_HAS_COPY_CTOR (class_type) = 1;
15000 if (ctor > 1)
15001 TYPE_HAS_CONST_COPY_CTOR (class_type) = 1;
15004 if (sufficient_parms_p (FUNCTION_FIRST_USER_PARMTYPE (decl)))
15005 TYPE_HAS_DEFAULT_CONSTRUCTOR (class_type) = 1;
15007 if (is_list_ctor (decl))
15008 TYPE_HAS_LIST_CTOR (class_type) = 1;
15010 if (maybe_constexpr_fn (decl)
15011 && !ctor && !move_fn_p (decl))
15012 TYPE_HAS_CONSTEXPR_CTOR (class_type) = 1;
15014 else if (DECL_NAME (decl) == assign_op_identifier)
15016 /* [class.copy]
15018 A non-template assignment operator for class X is a copy
15019 assignment operator if its parameter is of type X, X&, const
15020 X&, volatile X& or const volatile X&. */
15022 int assop = copy_fn_p (decl);
15024 if (assop)
15026 TYPE_HAS_COPY_ASSIGN (class_type) = 1;
15027 if (assop != 1)
15028 TYPE_HAS_CONST_COPY_ASSIGN (class_type) = 1;
15031 else if (IDENTIFIER_CONV_OP_P (DECL_NAME (decl)))
15032 TYPE_HAS_CONVERSION (class_type) = true;
15034 /* Destructors are handled in check_methods. */
15037 /* Check a constructor DECL has the correct form. Complains
15038 if the class has a constructor of the form X(X). */
15040 bool
15041 grok_ctor_properties (const_tree ctype, const_tree decl)
15043 int ctor_parm = copy_fn_p (decl);
15045 if (ctor_parm < 0)
15047 /* [class.copy]
15049 A declaration of a constructor for a class X is ill-formed if
15050 its first parameter is of type (optionally cv-qualified) X
15051 and either there are no other parameters or else all other
15052 parameters have default arguments.
15054 We *don't* complain about member template instantiations that
15055 have this form, though; they can occur as we try to decide
15056 what constructor to use during overload resolution. Since
15057 overload resolution will never prefer such a constructor to
15058 the non-template copy constructor (which is either explicitly
15059 or implicitly defined), there's no need to worry about their
15060 existence. Theoretically, they should never even be
15061 instantiated, but that's hard to forestall. */
15062 error_at (DECL_SOURCE_LOCATION (decl),
15063 "invalid constructor; you probably meant %<%T (const %T&)%>",
15064 ctype, ctype);
15065 return false;
15068 return true;
15071 /* DECL is a declaration for an overloaded or conversion operator. If
15072 COMPLAIN is true, errors are issued for invalid declarations. */
15074 bool
15075 grok_op_properties (tree decl, bool complain)
15077 tree argtypes = TYPE_ARG_TYPES (TREE_TYPE (decl));
15078 bool methodp = TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE;
15079 tree name = DECL_NAME (decl);
15080 location_t loc = DECL_SOURCE_LOCATION (decl);
15082 tree class_type = DECL_CONTEXT (decl);
15083 if (class_type && !CLASS_TYPE_P (class_type))
15084 class_type = NULL_TREE;
15086 tree_code operator_code;
15087 unsigned op_flags;
15088 if (IDENTIFIER_CONV_OP_P (name))
15090 /* Conversion operators are TYPE_EXPR for the purposes of this
15091 function. */
15092 operator_code = TYPE_EXPR;
15093 op_flags = OVL_OP_FLAG_UNARY;
15095 else
15097 const ovl_op_info_t *ovl_op = IDENTIFIER_OVL_OP_INFO (name);
15099 operator_code = ovl_op->tree_code;
15100 op_flags = ovl_op->flags;
15101 gcc_checking_assert (operator_code != ERROR_MARK);
15102 DECL_OVERLOADED_OPERATOR_CODE_RAW (decl) = ovl_op->ovl_op_code;
15105 if (op_flags & OVL_OP_FLAG_ALLOC)
15107 /* operator new and operator delete are quite special. */
15108 if (class_type)
15109 switch (op_flags)
15111 case OVL_OP_FLAG_ALLOC:
15112 TYPE_HAS_NEW_OPERATOR (class_type) = 1;
15113 break;
15115 case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_DELETE:
15116 TYPE_GETS_DELETE (class_type) |= 1;
15117 break;
15119 case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_VEC:
15120 TYPE_HAS_ARRAY_NEW_OPERATOR (class_type) = 1;
15121 break;
15123 case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_DELETE | OVL_OP_FLAG_VEC:
15124 TYPE_GETS_DELETE (class_type) |= 2;
15125 break;
15127 default:
15128 gcc_unreachable ();
15131 /* [basic.std.dynamic.allocation]/1:
15133 A program is ill-formed if an allocation function is declared
15134 in a namespace scope other than global scope or declared
15135 static in global scope.
15137 The same also holds true for deallocation functions. */
15138 if (DECL_NAMESPACE_SCOPE_P (decl))
15140 if (CP_DECL_CONTEXT (decl) != global_namespace)
15142 error_at (loc, "%qD may not be declared within a namespace",
15143 decl);
15144 return false;
15147 if (!TREE_PUBLIC (decl))
15149 error_at (loc, "%qD may not be declared as static", decl);
15150 return false;
15154 if (op_flags & OVL_OP_FLAG_DELETE)
15156 DECL_SET_IS_OPERATOR_DELETE (decl, true);
15157 coerce_delete_type (decl, loc);
15159 else
15161 DECL_SET_IS_OPERATOR_NEW (decl, true);
15162 TREE_TYPE (decl) = coerce_new_type (TREE_TYPE (decl), loc);
15165 return true;
15168 /* An operator function must either be a non-static member function
15169 or have at least one parameter of a class, a reference to a class,
15170 an enumeration, or a reference to an enumeration. 13.4.0.6 */
15171 if (! methodp || DECL_STATIC_FUNCTION_P (decl))
15173 if (operator_code == TYPE_EXPR
15174 || operator_code == CALL_EXPR
15175 || operator_code == COMPONENT_REF
15176 || operator_code == ARRAY_REF
15177 || operator_code == NOP_EXPR)
15179 error_at (loc, "%qD must be a non-static member function", decl);
15180 return false;
15183 if (DECL_STATIC_FUNCTION_P (decl))
15185 error_at (loc, "%qD must be either a non-static member "
15186 "function or a non-member function", decl);
15187 return false;
15190 for (tree arg = argtypes; ; arg = TREE_CHAIN (arg))
15192 if (!arg || arg == void_list_node)
15194 if (complain)
15195 error_at(loc, "%qD must have an argument of class or "
15196 "enumerated type", decl);
15197 return false;
15200 tree type = non_reference (TREE_VALUE (arg));
15201 if (type == error_mark_node)
15202 return false;
15204 /* MAYBE_CLASS_TYPE_P, rather than CLASS_TYPE_P, is used
15205 because these checks are performed even on template
15206 functions. */
15207 if (MAYBE_CLASS_TYPE_P (type)
15208 || TREE_CODE (type) == ENUMERAL_TYPE)
15209 break;
15213 if (operator_code == CALL_EXPR)
15214 /* There are no further restrictions on the arguments to an overloaded
15215 "operator ()". */
15216 return true;
15218 if (operator_code == COND_EXPR)
15220 /* 13.4.0.3 */
15221 error_at (loc, "ISO C++ prohibits overloading %<operator ?:%>");
15222 return false;
15225 /* Count the number of arguments and check for ellipsis. */
15226 int arity = 0;
15227 for (tree arg = argtypes; arg != void_list_node; arg = TREE_CHAIN (arg))
15229 if (!arg)
15231 /* Variadic. */
15232 if (operator_code == ARRAY_REF && cxx_dialect >= cxx23)
15233 break;
15235 error_at (loc, "%qD must not have variable number of arguments",
15236 decl);
15237 return false;
15239 ++arity;
15242 /* Verify correct number of arguments. */
15243 switch (op_flags)
15245 case OVL_OP_FLAG_AMBIARY:
15246 if (arity == 1)
15248 /* We have a unary instance of an ambi-ary op. Remap to the
15249 unary one. */
15250 unsigned alt = ovl_op_alternate[ovl_op_mapping [operator_code]];
15251 const ovl_op_info_t *ovl_op = &ovl_op_info[false][alt];
15252 gcc_checking_assert (ovl_op->flags == OVL_OP_FLAG_UNARY);
15253 operator_code = ovl_op->tree_code;
15254 DECL_OVERLOADED_OPERATOR_CODE_RAW (decl) = ovl_op->ovl_op_code;
15256 else if (arity != 2)
15258 /* This was an ambiguous operator but is invalid. */
15259 error_at (loc,
15260 methodp
15261 ? G_("%qD must have either zero or one argument")
15262 : G_("%qD must have either one or two arguments"), decl);
15263 return false;
15265 else if ((operator_code == POSTINCREMENT_EXPR
15266 || operator_code == POSTDECREMENT_EXPR)
15267 && ! processing_template_decl
15268 /* x++ and x--'s second argument must be an int. */
15269 && ! same_type_p (TREE_VALUE (TREE_CHAIN (argtypes)),
15270 integer_type_node))
15272 error_at (loc,
15273 methodp
15274 ? G_("postfix %qD must have %<int%> as its argument")
15275 : G_("postfix %qD must have %<int%> as its second argument"),
15276 decl);
15277 return false;
15279 break;
15281 case OVL_OP_FLAG_UNARY:
15282 if (arity != 1)
15284 error_at (loc,
15285 methodp
15286 ? G_("%qD must have no arguments")
15287 : G_("%qD must have exactly one argument"), decl);
15288 return false;
15290 break;
15292 case OVL_OP_FLAG_BINARY:
15293 if (arity != 2)
15295 if (operator_code == ARRAY_REF && cxx_dialect >= cxx23)
15296 break;
15297 error_at (loc,
15298 methodp
15299 ? G_("%qD must have exactly one argument")
15300 : G_("%qD must have exactly two arguments"), decl);
15301 return false;
15303 break;
15305 default:
15306 gcc_unreachable ();
15309 /* There can be no default arguments. */
15310 for (tree arg = argtypes; arg && arg != void_list_node;
15311 arg = TREE_CHAIN (arg))
15312 if (TREE_PURPOSE (arg))
15314 TREE_PURPOSE (arg) = NULL_TREE;
15315 error_at (loc, "%qD cannot have default arguments", decl);
15316 return false;
15319 /* At this point the declaration is well-formed. It may not be
15320 sensible though. */
15322 /* Check member function warnings only on the in-class declaration.
15323 There's no point warning on an out-of-class definition. */
15324 if (class_type && class_type != current_class_type)
15325 return true;
15327 /* Warn about conversion operators that will never be used. */
15328 if (IDENTIFIER_CONV_OP_P (name)
15329 && ! DECL_TEMPLATE_INFO (decl)
15330 && warn_class_conversion)
15332 tree t = TREE_TYPE (name);
15333 int ref = TYPE_REF_P (t);
15335 if (ref)
15336 t = TYPE_MAIN_VARIANT (TREE_TYPE (t));
15338 if (VOID_TYPE_P (t))
15339 warning_at (loc, OPT_Wclass_conversion, "converting %qT to %<void%> "
15340 "will never use a type conversion operator", class_type);
15341 else if (class_type)
15343 if (same_type_ignoring_top_level_qualifiers_p (t, class_type))
15344 warning_at (loc, OPT_Wclass_conversion,
15346 ? G_("converting %qT to a reference to the same type "
15347 "will never use a type conversion operator")
15348 : G_("converting %qT to the same type "
15349 "will never use a type conversion operator"),
15350 class_type);
15351 /* Don't force t to be complete here. */
15352 else if (MAYBE_CLASS_TYPE_P (t)
15353 && COMPLETE_TYPE_P (t)
15354 && DERIVED_FROM_P (t, class_type))
15355 warning_at (loc, OPT_Wclass_conversion,
15357 ? G_("converting %qT to a reference to a base class "
15358 "%qT will never use a type conversion operator")
15359 : G_("converting %qT to a base class %qT "
15360 "will never use a type conversion operator"),
15361 class_type, t);
15365 if (!warn_ecpp)
15366 return true;
15368 /* Effective C++ rules below. */
15370 /* More Effective C++ rule 7. */
15371 if (operator_code == TRUTH_ANDIF_EXPR
15372 || operator_code == TRUTH_ORIF_EXPR
15373 || operator_code == COMPOUND_EXPR)
15374 warning_at (loc, OPT_Weffc__,
15375 "user-defined %qD always evaluates both arguments", decl);
15377 /* More Effective C++ rule 6. */
15378 if (operator_code == POSTINCREMENT_EXPR
15379 || operator_code == POSTDECREMENT_EXPR
15380 || operator_code == PREINCREMENT_EXPR
15381 || operator_code == PREDECREMENT_EXPR)
15383 tree arg = TREE_VALUE (argtypes);
15384 tree ret = TREE_TYPE (TREE_TYPE (decl));
15385 if (methodp || TYPE_REF_P (arg))
15386 arg = TREE_TYPE (arg);
15387 arg = TYPE_MAIN_VARIANT (arg);
15389 if (operator_code == PREINCREMENT_EXPR
15390 || operator_code == PREDECREMENT_EXPR)
15392 if (!TYPE_REF_P (ret)
15393 || !same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (ret)), arg))
15394 warning_at (loc, OPT_Weffc__, "prefix %qD should return %qT", decl,
15395 build_reference_type (arg));
15397 else
15399 if (!same_type_p (TYPE_MAIN_VARIANT (ret), arg))
15400 warning_at (loc, OPT_Weffc__,
15401 "postfix %qD should return %qT", decl, arg);
15405 /* Effective C++ rule 23. */
15406 if (!DECL_ASSIGNMENT_OPERATOR_P (decl)
15407 && (operator_code == PLUS_EXPR
15408 || operator_code == MINUS_EXPR
15409 || operator_code == TRUNC_DIV_EXPR
15410 || operator_code == MULT_EXPR
15411 || operator_code == TRUNC_MOD_EXPR)
15412 && TYPE_REF_P (TREE_TYPE (TREE_TYPE (decl))))
15413 warning_at (loc, OPT_Weffc__, "%qD should return by value", decl);
15415 return true;
15418 /* Return a string giving the keyword associate with CODE. */
15420 static const char *
15421 tag_name (enum tag_types code)
15423 switch (code)
15425 case record_type:
15426 return "struct";
15427 case class_type:
15428 return "class";
15429 case union_type:
15430 return "union";
15431 case enum_type:
15432 return "enum";
15433 case typename_type:
15434 return "typename";
15435 default:
15436 gcc_unreachable ();
15440 /* Name lookup in an elaborated-type-specifier (after the keyword
15441 indicated by TAG_CODE) has found the TYPE_DECL DECL. If the
15442 elaborated-type-specifier is invalid, issue a diagnostic and return
15443 error_mark_node; otherwise, return the *_TYPE to which it referred.
15444 If ALLOW_TEMPLATE_P is true, TYPE may be a class template. */
15446 tree
15447 check_elaborated_type_specifier (enum tag_types tag_code,
15448 tree decl,
15449 bool allow_template_p)
15451 tree type;
15453 /* In the case of:
15455 struct S { struct S *p; };
15457 name lookup will find the TYPE_DECL for the implicit "S::S"
15458 typedef. Adjust for that here. */
15459 if (DECL_SELF_REFERENCE_P (decl))
15460 decl = TYPE_NAME (TREE_TYPE (decl));
15462 type = TREE_TYPE (decl);
15464 /* Check TEMPLATE_TYPE_PARM first because DECL_IMPLICIT_TYPEDEF_P
15465 is false for this case as well. */
15466 if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
15468 error ("using template type parameter %qT after %qs",
15469 type, tag_name (tag_code));
15470 return error_mark_node;
15472 /* Accept template template parameters. */
15473 else if (allow_template_p
15474 && (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM
15475 || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM))
15477 /* [dcl.type.elab]
15479 If the identifier resolves to a typedef-name or the
15480 simple-template-id resolves to an alias template
15481 specialization, the elaborated-type-specifier is ill-formed.
15483 In other words, the only legitimate declaration to use in the
15484 elaborated type specifier is the implicit typedef created when
15485 the type is declared. */
15486 else if (!DECL_IMPLICIT_TYPEDEF_P (decl)
15487 && !DECL_SELF_REFERENCE_P (decl)
15488 && tag_code != typename_type)
15490 if (alias_template_specialization_p (type, nt_opaque))
15491 error ("using alias template specialization %qT after %qs",
15492 type, tag_name (tag_code));
15493 else
15494 error ("using typedef-name %qD after %qs", decl, tag_name (tag_code));
15495 inform (DECL_SOURCE_LOCATION (decl),
15496 "%qD has a previous declaration here", decl);
15497 return error_mark_node;
15499 else if (TREE_CODE (type) != RECORD_TYPE
15500 && TREE_CODE (type) != UNION_TYPE
15501 && tag_code != enum_type
15502 && tag_code != typename_type)
15504 error ("%qT referred to as %qs", type, tag_name (tag_code));
15505 inform (location_of (type), "%qT has a previous declaration here", type);
15506 return error_mark_node;
15508 else if (TREE_CODE (type) != ENUMERAL_TYPE
15509 && tag_code == enum_type)
15511 error ("%qT referred to as enum", type);
15512 inform (location_of (type), "%qT has a previous declaration here", type);
15513 return error_mark_node;
15515 else if (!allow_template_p
15516 && TREE_CODE (type) == RECORD_TYPE
15517 && CLASSTYPE_IS_TEMPLATE (type))
15519 /* If a class template appears as elaborated type specifier
15520 without a template header such as:
15522 template <class T> class C {};
15523 void f(class C); // No template header here
15525 then the required template argument is missing. */
15526 error ("template argument required for %<%s %T%>",
15527 tag_name (tag_code),
15528 DECL_NAME (CLASSTYPE_TI_TEMPLATE (type)));
15529 return error_mark_node;
15532 return type;
15535 /* Lookup NAME of an elaborated type specifier according to SCOPE and
15536 issue diagnostics if necessary. Return *_TYPE node upon success,
15537 NULL_TREE when the NAME is not found, and ERROR_MARK_NODE for type
15538 error. */
15540 static tree
15541 lookup_and_check_tag (enum tag_types tag_code, tree name,
15542 TAG_how how, bool template_header_p)
15544 tree decl;
15545 if (how == TAG_how::GLOBAL)
15547 /* First try ordinary name lookup, ignoring hidden class name
15548 injected via friend declaration. */
15549 decl = lookup_name (name, LOOK_want::TYPE);
15550 decl = strip_using_decl (decl);
15551 /* If that fails, the name will be placed in the smallest
15552 non-class, non-function-prototype scope according to 3.3.1/5.
15553 We may already have a hidden name declared as friend in this
15554 scope. So lookup again but not ignoring hidden names.
15555 If we find one, that name will be made visible rather than
15556 creating a new tag. */
15557 if (!decl)
15558 decl = lookup_elaborated_type (name, TAG_how::INNERMOST_NON_CLASS);
15560 else
15561 decl = lookup_elaborated_type (name, how);
15563 if (!decl)
15564 /* We found nothing. */
15565 return NULL_TREE;
15567 if (TREE_CODE (decl) == TREE_LIST)
15569 error ("reference to %qD is ambiguous", name);
15570 print_candidates (decl);
15571 return error_mark_node;
15574 if (DECL_CLASS_TEMPLATE_P (decl)
15575 && !template_header_p
15576 && how == TAG_how::CURRENT_ONLY)
15578 error ("class template %qD redeclared as non-template", name);
15579 inform (location_of (decl), "previous declaration here");
15580 CLASSTYPE_ERRONEOUS (TREE_TYPE (decl)) = true;
15581 return error_mark_node;
15584 if (DECL_CLASS_TEMPLATE_P (decl)
15585 /* If scope is TAG_how::CURRENT_ONLY we're defining a class,
15586 so ignore a template template parameter. */
15587 || (how != TAG_how::CURRENT_ONLY && DECL_TEMPLATE_TEMPLATE_PARM_P (decl)))
15588 decl = DECL_TEMPLATE_RESULT (decl);
15590 if (TREE_CODE (decl) != TYPE_DECL)
15591 /* Found not-a-type. */
15592 return NULL_TREE;
15594 /* Look for invalid nested type:
15595 class C {
15596 class C {};
15597 }; */
15598 if (how == TAG_how::CURRENT_ONLY && DECL_SELF_REFERENCE_P (decl))
15600 error ("%qD has the same name as the class in which it is "
15601 "declared", decl);
15602 return error_mark_node;
15605 /* Two cases we need to consider when deciding if a class
15606 template is allowed as an elaborated type specifier:
15607 1. It is a self reference to its own class.
15608 2. It comes with a template header.
15610 For example:
15612 template <class T> class C {
15613 class C *c1; // DECL_SELF_REFERENCE_P is true
15614 class D;
15616 template <class U> class C; // template_header_p is true
15617 template <class T> class C<T>::D {
15618 class C *c2; // DECL_SELF_REFERENCE_P is true
15619 }; */
15621 tree t = check_elaborated_type_specifier (tag_code, decl,
15622 template_header_p
15623 | DECL_SELF_REFERENCE_P (decl));
15624 if (template_header_p && t && CLASS_TYPE_P (t)
15625 && (!CLASSTYPE_TEMPLATE_INFO (t)
15626 || (!PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)))))
15628 error ("%qT is not a template", t);
15629 inform (location_of (t), "previous declaration here");
15630 if (TYPE_CLASS_SCOPE_P (t)
15631 && CLASSTYPE_TEMPLATE_INFO (TYPE_CONTEXT (t)))
15632 inform (input_location,
15633 "perhaps you want to explicitly add %<%T::%>",
15634 TYPE_CONTEXT (t));
15635 return error_mark_node;
15638 return t;
15641 /* Get the struct, enum or union (TAG_CODE says which) with tag NAME.
15642 Define the tag as a forward-reference if it is not defined.
15644 If a declaration is given, process it here, and report an error if
15645 multiple declarations are not identical.
15647 SCOPE is TS_CURRENT when this is also a definition. Only look in
15648 the current frame for the name (since C++ allows new names in any
15649 scope.) It is TS_WITHIN_ENCLOSING_NON_CLASS if this is a friend
15650 declaration. Only look beginning from the current scope outward up
15651 till the nearest non-class scope. Otherwise it is TS_GLOBAL.
15653 TEMPLATE_HEADER_P is true when this declaration is preceded by
15654 a set of template parameters. */
15656 tree
15657 xref_tag (enum tag_types tag_code, tree name,
15658 TAG_how how, bool template_header_p)
15660 enum tree_code code;
15661 tree context = NULL_TREE;
15663 auto_cond_timevar tv (TV_NAME_LOOKUP);
15665 gcc_assert (identifier_p (name));
15667 switch (tag_code)
15669 case record_type:
15670 case class_type:
15671 code = RECORD_TYPE;
15672 break;
15673 case union_type:
15674 code = UNION_TYPE;
15675 break;
15676 case enum_type:
15677 code = ENUMERAL_TYPE;
15678 break;
15679 default:
15680 gcc_unreachable ();
15683 /* In case of anonymous name, xref_tag is only called to
15684 make type node and push name. Name lookup is not required. */
15685 tree t = NULL_TREE;
15686 if (!IDENTIFIER_ANON_P (name))
15687 t = lookup_and_check_tag (tag_code, name, how, template_header_p);
15689 if (t == error_mark_node)
15690 return error_mark_node;
15692 if (how != TAG_how::CURRENT_ONLY && t && current_class_type
15693 && template_class_depth (current_class_type)
15694 && template_header_p)
15696 if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
15697 return t;
15699 /* Since HOW is not TAG_how::CURRENT_ONLY, we are not looking at
15700 a definition of this tag. Since, in addition, we are
15701 currently processing a (member) template declaration of a
15702 template class, we must be very careful; consider:
15704 template <class X> struct S1
15706 template <class U> struct S2
15708 template <class V> friend struct S1;
15711 Here, the S2::S1 declaration should not be confused with the
15712 outer declaration. In particular, the inner version should
15713 have a template parameter of level 2, not level 1.
15715 On the other hand, when presented with:
15717 template <class T> struct S1
15719 template <class U> struct S2 {};
15720 template <class U> friend struct S2;
15723 the friend must find S1::S2 eventually. We accomplish this
15724 by making sure that the new type we create to represent this
15725 declaration has the right TYPE_CONTEXT. */
15726 context = TYPE_CONTEXT (t);
15727 t = NULL_TREE;
15730 if (! t)
15732 /* If no such tag is yet defined, create a forward-reference node
15733 and record it as the "definition".
15734 When a real declaration of this type is found,
15735 the forward-reference will be altered into a real type. */
15736 if (code == ENUMERAL_TYPE)
15738 error ("use of enum %q#D without previous declaration", name);
15739 return error_mark_node;
15742 t = make_class_type (code);
15743 TYPE_CONTEXT (t) = context;
15744 if (IDENTIFIER_LAMBDA_P (name))
15745 /* Mark it as a lambda type right now. Our caller will
15746 correct the value. */
15747 CLASSTYPE_LAMBDA_EXPR (t) = error_mark_node;
15748 t = pushtag (name, t, how);
15750 else
15752 if (template_header_p && MAYBE_CLASS_TYPE_P (t))
15754 /* Check that we aren't trying to overload a class with different
15755 constraints. */
15756 tree constr = NULL_TREE;
15757 if (current_template_parms)
15759 tree reqs = TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
15760 constr = build_constraints (reqs, NULL_TREE);
15762 if (!redeclare_class_template (t, current_template_parms, constr))
15763 return error_mark_node;
15765 else if (!processing_template_decl
15766 && CLASS_TYPE_P (t)
15767 && CLASSTYPE_IS_TEMPLATE (t))
15769 error ("redeclaration of %qT as a non-template", t);
15770 inform (location_of (t), "previous declaration %qD", t);
15771 return error_mark_node;
15774 if (modules_p ()
15775 && how == TAG_how::CURRENT_ONLY)
15777 tree decl = TYPE_NAME (t);
15778 if (!module_may_redeclare (decl))
15780 error ("cannot declare %qD in a different module", decl);
15781 inform (DECL_SOURCE_LOCATION (decl), "declared here");
15782 return error_mark_node;
15785 tree maybe_tmpl = decl;
15786 if (CLASS_TYPE_P (t) && CLASSTYPE_IS_TEMPLATE (t))
15787 maybe_tmpl = CLASSTYPE_TI_TEMPLATE (t);
15789 if (DECL_LANG_SPECIFIC (decl)
15790 && DECL_MODULE_IMPORT_P (decl)
15791 && TREE_CODE (CP_DECL_CONTEXT (decl)) == NAMESPACE_DECL)
15793 /* Push it into this TU's symbol slot. */
15794 gcc_checking_assert (current_namespace == CP_DECL_CONTEXT (decl));
15795 if (maybe_tmpl != decl)
15796 /* We're in the template parm binding level.
15797 Pushtag has logic to slide under that, but we're
15798 not pushing a *new* type. */
15799 push_nested_namespace (CP_DECL_CONTEXT (decl));
15801 pushdecl (maybe_tmpl);
15802 if (maybe_tmpl != decl)
15803 pop_nested_namespace (CP_DECL_CONTEXT (decl));
15806 set_instantiating_module (maybe_tmpl);
15810 return t;
15813 /* Create the binfo hierarchy for REF with (possibly NULL) base list
15814 BASE_LIST. For each element on BASE_LIST the TREE_PURPOSE is an
15815 access_* node, and the TREE_VALUE is the type of the base-class.
15816 Non-NULL TREE_TYPE indicates virtual inheritance. */
15818 void
15819 xref_basetypes (tree ref, tree base_list)
15821 tree *basep;
15822 tree binfo, base_binfo;
15823 unsigned max_vbases = 0; /* Maximum direct & indirect virtual bases. */
15824 unsigned max_bases = 0; /* Maximum direct bases. */
15825 unsigned max_dvbases = 0; /* Maximum direct virtual bases. */
15826 int i;
15827 tree default_access;
15828 tree igo_prev; /* Track Inheritance Graph Order. */
15830 if (ref == error_mark_node)
15831 return;
15833 /* The base of a derived class is private by default, all others are
15834 public. */
15835 default_access = (TREE_CODE (ref) == RECORD_TYPE
15836 && CLASSTYPE_DECLARED_CLASS (ref)
15837 ? access_private_node : access_public_node);
15839 /* First, make sure that any templates in base-classes are
15840 instantiated. This ensures that if we call ourselves recursively
15841 we do not get confused about which classes are marked and which
15842 are not. */
15843 basep = &base_list;
15844 while (*basep)
15846 tree basetype = TREE_VALUE (*basep);
15848 /* The dependent_type_p call below should really be dependent_scope_p
15849 so that we give a hard error about using an incomplete type as a
15850 base, but we allow it with a pedwarn for backward
15851 compatibility. */
15852 if (processing_template_decl
15853 && CLASS_TYPE_P (basetype) && TYPE_BEING_DEFINED (basetype))
15854 cxx_incomplete_type_diagnostic (NULL_TREE, basetype, DK_PEDWARN);
15855 if (!dependent_type_p (basetype)
15856 && !complete_type_or_else (basetype, NULL))
15857 /* An incomplete type. Remove it from the list. */
15858 *basep = TREE_CHAIN (*basep);
15859 else
15861 max_bases++;
15862 if (TREE_TYPE (*basep))
15863 max_dvbases++;
15864 if (CLASS_TYPE_P (basetype))
15865 max_vbases += vec_safe_length (CLASSTYPE_VBASECLASSES (basetype));
15866 basep = &TREE_CHAIN (*basep);
15869 max_vbases += max_dvbases;
15871 TYPE_MARKED_P (ref) = 1;
15873 /* The binfo slot should be empty, unless this is an (ill-formed)
15874 redefinition. */
15875 gcc_assert (!TYPE_BINFO (ref) || TYPE_SIZE (ref));
15877 gcc_assert (TYPE_MAIN_VARIANT (ref) == ref);
15879 binfo = make_tree_binfo (max_bases);
15881 TYPE_BINFO (ref) = binfo;
15882 BINFO_OFFSET (binfo) = size_zero_node;
15883 BINFO_TYPE (binfo) = ref;
15885 /* Apply base-class info set up to the variants of this type. */
15886 fixup_type_variants (ref);
15888 if (max_bases)
15890 vec_alloc (BINFO_BASE_ACCESSES (binfo), max_bases);
15891 /* A C++98 POD cannot have base classes. */
15892 CLASSTYPE_NON_LAYOUT_POD_P (ref) = true;
15894 if (TREE_CODE (ref) == UNION_TYPE)
15896 error ("derived union %qT invalid", ref);
15897 return;
15901 if (max_bases > 1)
15902 warning (OPT_Wmultiple_inheritance,
15903 "%qT defined with multiple direct bases", ref);
15905 if (max_vbases)
15907 /* An aggregate can't have virtual base classes. */
15908 CLASSTYPE_NON_AGGREGATE (ref) = true;
15910 vec_alloc (CLASSTYPE_VBASECLASSES (ref), max_vbases);
15912 if (max_dvbases)
15913 warning (OPT_Wvirtual_inheritance,
15914 "%qT defined with direct virtual base", ref);
15917 for (igo_prev = binfo; base_list; base_list = TREE_CHAIN (base_list))
15919 tree access = TREE_PURPOSE (base_list);
15920 int via_virtual = TREE_TYPE (base_list) != NULL_TREE;
15921 tree basetype = TREE_VALUE (base_list);
15923 if (access == access_default_node)
15924 access = default_access;
15926 /* Before C++17, an aggregate cannot have base classes. In C++17, an
15927 aggregate can't have virtual, private, or protected base classes. */
15928 if (cxx_dialect < cxx17
15929 || access != access_public_node
15930 || via_virtual)
15931 CLASSTYPE_NON_AGGREGATE (ref) = true;
15933 if (PACK_EXPANSION_P (basetype))
15934 basetype = PACK_EXPANSION_PATTERN (basetype);
15935 if (TREE_CODE (basetype) == TYPE_DECL)
15936 basetype = TREE_TYPE (basetype);
15937 if (!MAYBE_CLASS_TYPE_P (basetype) || TREE_CODE (basetype) == UNION_TYPE)
15939 error ("base type %qT fails to be a struct or class type",
15940 basetype);
15941 goto dropped_base;
15944 base_binfo = NULL_TREE;
15945 if (CLASS_TYPE_P (basetype) && !dependent_scope_p (basetype))
15947 base_binfo = TYPE_BINFO (basetype);
15948 /* The original basetype could have been a typedef'd type. */
15949 basetype = BINFO_TYPE (base_binfo);
15951 /* Inherit flags from the base. */
15952 TYPE_HAS_NEW_OPERATOR (ref)
15953 |= TYPE_HAS_NEW_OPERATOR (basetype);
15954 TYPE_HAS_ARRAY_NEW_OPERATOR (ref)
15955 |= TYPE_HAS_ARRAY_NEW_OPERATOR (basetype);
15956 TYPE_GETS_DELETE (ref) |= TYPE_GETS_DELETE (basetype);
15957 TYPE_HAS_CONVERSION (ref) |= TYPE_HAS_CONVERSION (basetype);
15958 CLASSTYPE_DIAMOND_SHAPED_P (ref)
15959 |= CLASSTYPE_DIAMOND_SHAPED_P (basetype);
15960 CLASSTYPE_REPEATED_BASE_P (ref)
15961 |= CLASSTYPE_REPEATED_BASE_P (basetype);
15964 /* We must do this test after we've seen through a typedef
15965 type. */
15966 if (TYPE_MARKED_P (basetype))
15968 if (basetype == ref)
15969 error ("recursive type %qT undefined", basetype);
15970 else
15971 error ("duplicate base type %qT invalid", basetype);
15972 goto dropped_base;
15975 if (PACK_EXPANSION_P (TREE_VALUE (base_list)))
15976 /* Regenerate the pack expansion for the bases. */
15977 basetype = make_pack_expansion (basetype);
15979 TYPE_MARKED_P (basetype) = 1;
15981 base_binfo = copy_binfo (base_binfo, basetype, ref,
15982 &igo_prev, via_virtual);
15983 if (!BINFO_INHERITANCE_CHAIN (base_binfo))
15984 BINFO_INHERITANCE_CHAIN (base_binfo) = binfo;
15986 BINFO_BASE_APPEND (binfo, base_binfo);
15987 BINFO_BASE_ACCESS_APPEND (binfo, access);
15988 continue;
15990 dropped_base:
15991 /* Update max_vbases to reflect the reality that we are dropping
15992 this base: if it reaches zero we want to undo the vec_alloc
15993 above to avoid inconsistencies during error-recovery: eg, in
15994 build_special_member_call, CLASSTYPE_VBASECLASSES non null
15995 and vtt null (c++/27952). */
15996 if (via_virtual)
15997 max_vbases--;
15998 if (CLASS_TYPE_P (basetype))
15999 max_vbases
16000 -= vec_safe_length (CLASSTYPE_VBASECLASSES (basetype));
16003 if (CLASSTYPE_VBASECLASSES (ref)
16004 && max_vbases == 0)
16005 vec_free (CLASSTYPE_VBASECLASSES (ref));
16007 if (vec_safe_length (CLASSTYPE_VBASECLASSES (ref)) < max_vbases)
16008 /* If we didn't get max_vbases vbases, we must have shared at
16009 least one of them, and are therefore diamond shaped. */
16010 CLASSTYPE_DIAMOND_SHAPED_P (ref) = 1;
16012 /* Unmark all the types. */
16013 for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
16014 TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 0;
16015 TYPE_MARKED_P (ref) = 0;
16017 /* Now see if we have a repeated base type. */
16018 if (!CLASSTYPE_REPEATED_BASE_P (ref))
16020 for (base_binfo = binfo; base_binfo;
16021 base_binfo = TREE_CHAIN (base_binfo))
16023 if (TYPE_MARKED_P (BINFO_TYPE (base_binfo)))
16025 CLASSTYPE_REPEATED_BASE_P (ref) = 1;
16026 break;
16028 TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 1;
16030 for (base_binfo = binfo; base_binfo;
16031 base_binfo = TREE_CHAIN (base_binfo))
16032 if (TYPE_MARKED_P (BINFO_TYPE (base_binfo)))
16033 TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 0;
16034 else
16035 break;
16040 /* Copies the enum-related properties from type SRC to type DST.
16041 Used with the underlying type of an enum and the enum itself. */
16042 static void
16043 copy_type_enum (tree dst, tree src)
16045 tree t;
16046 for (t = dst; t; t = TYPE_NEXT_VARIANT (t))
16048 TYPE_MIN_VALUE (t) = TYPE_MIN_VALUE (src);
16049 TYPE_MAX_VALUE (t) = TYPE_MAX_VALUE (src);
16050 TYPE_SIZE (t) = TYPE_SIZE (src);
16051 TYPE_SIZE_UNIT (t) = TYPE_SIZE_UNIT (src);
16052 SET_TYPE_MODE (dst, TYPE_MODE (src));
16053 TYPE_PRECISION (t) = TYPE_PRECISION (src);
16054 unsigned valign = TYPE_ALIGN (src);
16055 if (TYPE_USER_ALIGN (t))
16056 valign = MAX (valign, TYPE_ALIGN (t));
16057 else
16058 TYPE_USER_ALIGN (t) = TYPE_USER_ALIGN (src);
16059 SET_TYPE_ALIGN (t, valign);
16060 TYPE_UNSIGNED (t) = TYPE_UNSIGNED (src);
16064 /* Begin compiling the definition of an enumeration type.
16065 NAME is its name,
16067 if ENUMTYPE is not NULL_TREE then the type has alredy been found.
16069 UNDERLYING_TYPE is the type that will be used as the storage for
16070 the enumeration type. This should be NULL_TREE if no storage type
16071 was specified.
16073 ATTRIBUTES are any attributes specified after the enum-key.
16075 SCOPED_ENUM_P is true if this is a scoped enumeration type.
16077 if IS_NEW is not NULL, gets TRUE iff a new type is created.
16079 Returns the type object, as yet incomplete.
16080 Also records info about it so that build_enumerator
16081 may be used to declare the individual values as they are read. */
16083 tree
16084 start_enum (tree name, tree enumtype, tree underlying_type,
16085 tree attributes, bool scoped_enum_p, bool *is_new)
16087 tree prevtype = NULL_TREE;
16088 gcc_assert (identifier_p (name));
16090 if (is_new)
16091 *is_new = false;
16092 /* [C++0x dcl.enum]p5:
16094 If not explicitly specified, the underlying type of a scoped
16095 enumeration type is int. */
16096 if (!underlying_type && scoped_enum_p)
16097 underlying_type = integer_type_node;
16099 if (underlying_type)
16100 underlying_type = cv_unqualified (underlying_type);
16102 /* If this is the real definition for a previous forward reference,
16103 fill in the contents in the same object that used to be the
16104 forward reference. */
16105 if (!enumtype)
16106 enumtype = lookup_and_check_tag (enum_type, name,
16107 /*tag_scope=*/TAG_how::CURRENT_ONLY,
16108 /*template_header_p=*/false);
16110 /* In case of a template_decl, the only check that should be deferred
16111 to instantiation time is the comparison of underlying types. */
16112 if (enumtype && TREE_CODE (enumtype) == ENUMERAL_TYPE)
16114 if (scoped_enum_p != SCOPED_ENUM_P (enumtype))
16116 error_at (input_location, "scoped/unscoped mismatch "
16117 "in enum %q#T", enumtype);
16118 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
16119 "previous definition here");
16120 enumtype = error_mark_node;
16122 else if (ENUM_FIXED_UNDERLYING_TYPE_P (enumtype) != !! underlying_type)
16124 error_at (input_location, "underlying type mismatch "
16125 "in enum %q#T", enumtype);
16126 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
16127 "previous definition here");
16128 enumtype = error_mark_node;
16130 else if (underlying_type && ENUM_UNDERLYING_TYPE (enumtype)
16131 && !same_type_p (underlying_type,
16132 ENUM_UNDERLYING_TYPE (enumtype)))
16134 error_at (input_location, "different underlying type "
16135 "in enum %q#T", enumtype);
16136 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
16137 "previous definition here");
16138 underlying_type = NULL_TREE;
16141 if (modules_p ())
16143 if (!module_may_redeclare (TYPE_NAME (enumtype)))
16145 error ("cannot define %qD in different module",
16146 TYPE_NAME (enumtype));
16147 inform (DECL_SOURCE_LOCATION (TYPE_NAME (enumtype)),
16148 "declared here");
16149 enumtype = error_mark_node;
16151 set_instantiating_module (TYPE_NAME (enumtype));
16155 if (!enumtype || TREE_CODE (enumtype) != ENUMERAL_TYPE
16156 || processing_template_decl)
16158 /* In case of error, make a dummy enum to allow parsing to
16159 continue. */
16160 if (enumtype == error_mark_node)
16162 name = make_anon_name ();
16163 enumtype = NULL_TREE;
16166 /* enumtype may be an ENUMERAL_TYPE if this is a redefinition
16167 of an opaque enum, or an opaque enum of an already defined
16168 enumeration (C++11).
16169 In any other case, it'll be NULL_TREE. */
16170 if (!enumtype)
16172 if (is_new)
16173 *is_new = true;
16175 prevtype = enumtype;
16177 /* Do not push the decl more than once. */
16178 if (!enumtype
16179 || TREE_CODE (enumtype) != ENUMERAL_TYPE)
16181 enumtype = cxx_make_type (ENUMERAL_TYPE);
16182 enumtype = pushtag (name, enumtype);
16184 /* std::byte aliases anything. */
16185 if (enumtype != error_mark_node
16186 && TYPE_CONTEXT (enumtype) == std_node
16187 && !strcmp ("byte", TYPE_NAME_STRING (enumtype)))
16188 TYPE_ALIAS_SET (enumtype) = 0;
16190 else
16191 enumtype = xref_tag (enum_type, name);
16193 if (enumtype == error_mark_node)
16194 return error_mark_node;
16196 /* The enum is considered opaque until the opening '{' of the
16197 enumerator list. */
16198 SET_OPAQUE_ENUM_P (enumtype, true);
16199 ENUM_FIXED_UNDERLYING_TYPE_P (enumtype) = !! underlying_type;
16202 SET_SCOPED_ENUM_P (enumtype, scoped_enum_p);
16204 cplus_decl_attributes (&enumtype, attributes, (int)ATTR_FLAG_TYPE_IN_PLACE);
16206 if (underlying_type)
16208 if (ENUM_UNDERLYING_TYPE (enumtype))
16209 /* We already checked that it matches, don't change it to a different
16210 typedef variant. */;
16211 else if (CP_INTEGRAL_TYPE_P (underlying_type))
16213 copy_type_enum (enumtype, underlying_type);
16214 ENUM_UNDERLYING_TYPE (enumtype) = underlying_type;
16216 else if (dependent_type_p (underlying_type))
16217 ENUM_UNDERLYING_TYPE (enumtype) = underlying_type;
16218 else
16219 error ("underlying type %qT of %qT must be an integral type",
16220 underlying_type, enumtype);
16223 /* If into a template class, the returned enum is always the first
16224 declaration (opaque or not) seen. This way all the references to
16225 this type will be to the same declaration. The following ones are used
16226 only to check for definition errors. */
16227 if (prevtype && processing_template_decl)
16228 return prevtype;
16229 else
16230 return enumtype;
16233 /* After processing and defining all the values of an enumeration type,
16234 install their decls in the enumeration type.
16235 ENUMTYPE is the type object. */
16237 void
16238 finish_enum_value_list (tree enumtype)
16240 tree values;
16241 tree underlying_type;
16242 tree decl;
16243 tree value;
16244 tree minnode, maxnode;
16245 tree t;
16247 bool fixed_underlying_type_p
16248 = ENUM_UNDERLYING_TYPE (enumtype) != NULL_TREE;
16250 /* We built up the VALUES in reverse order. */
16251 TYPE_VALUES (enumtype) = nreverse (TYPE_VALUES (enumtype));
16253 /* For an enum defined in a template, just set the type of the values;
16254 all further processing is postponed until the template is
16255 instantiated. We need to set the type so that tsubst of a CONST_DECL
16256 works. */
16257 if (processing_template_decl)
16259 for (values = TYPE_VALUES (enumtype);
16260 values;
16261 values = TREE_CHAIN (values))
16262 TREE_TYPE (TREE_VALUE (values)) = enumtype;
16263 return;
16266 /* Determine the minimum and maximum values of the enumerators. */
16267 if (TYPE_VALUES (enumtype))
16269 minnode = maxnode = NULL_TREE;
16271 for (values = TYPE_VALUES (enumtype);
16272 values;
16273 values = TREE_CHAIN (values))
16275 decl = TREE_VALUE (values);
16277 /* [dcl.enum]: Following the closing brace of an enum-specifier,
16278 each enumerator has the type of its enumeration. Prior to the
16279 closing brace, the type of each enumerator is the type of its
16280 initializing value. */
16281 TREE_TYPE (decl) = enumtype;
16283 /* Update the minimum and maximum values, if appropriate. */
16284 value = DECL_INITIAL (decl);
16285 if (TREE_CODE (value) != INTEGER_CST)
16286 value = integer_zero_node;
16287 /* Figure out what the minimum and maximum values of the
16288 enumerators are. */
16289 if (!minnode)
16290 minnode = maxnode = value;
16291 else if (tree_int_cst_lt (maxnode, value))
16292 maxnode = value;
16293 else if (tree_int_cst_lt (value, minnode))
16294 minnode = value;
16297 else
16298 /* [dcl.enum]
16300 If the enumerator-list is empty, the underlying type is as if
16301 the enumeration had a single enumerator with value 0. */
16302 minnode = maxnode = integer_zero_node;
16304 if (!fixed_underlying_type_p)
16306 /* Compute the number of bits require to represent all values of the
16307 enumeration. We must do this before the type of MINNODE and
16308 MAXNODE are transformed, since tree_int_cst_min_precision relies
16309 on the TREE_TYPE of the value it is passed. */
16310 signop sgn = tree_int_cst_sgn (minnode) >= 0 ? UNSIGNED : SIGNED;
16311 int lowprec = tree_int_cst_min_precision (minnode, sgn);
16312 int highprec = tree_int_cst_min_precision (maxnode, sgn);
16313 int precision = MAX (lowprec, highprec);
16314 unsigned int itk;
16315 bool use_short_enum;
16317 /* Determine the underlying type of the enumeration.
16319 [dcl.enum]
16321 The underlying type of an enumeration is an integral type that
16322 can represent all the enumerator values defined in the
16323 enumeration. It is implementation-defined which integral type is
16324 used as the underlying type for an enumeration except that the
16325 underlying type shall not be larger than int unless the value of
16326 an enumerator cannot fit in an int or unsigned int.
16328 We use "int" or an "unsigned int" as the underlying type, even if
16329 a smaller integral type would work, unless the user has
16330 explicitly requested that we use the smallest possible type. The
16331 user can request that for all enumerations with a command line
16332 flag, or for just one enumeration with an attribute. */
16334 use_short_enum = flag_short_enums
16335 || lookup_attribute ("packed", TYPE_ATTRIBUTES (enumtype));
16337 /* If the precision of the type was specified with an attribute and it
16338 was too small, give an error. Otherwise, use it. */
16339 if (TYPE_PRECISION (enumtype))
16341 if (precision > TYPE_PRECISION (enumtype))
16342 error ("specified mode too small for enumerated values");
16343 else
16345 use_short_enum = true;
16346 precision = TYPE_PRECISION (enumtype);
16350 for (itk = (use_short_enum ? itk_char : itk_int);
16351 itk != itk_none;
16352 itk++)
16354 underlying_type = integer_types[itk];
16355 if (underlying_type != NULL_TREE
16356 && TYPE_PRECISION (underlying_type) >= precision
16357 && TYPE_SIGN (underlying_type) == sgn)
16358 break;
16360 if (itk == itk_none)
16362 /* DR 377
16364 IF no integral type can represent all the enumerator values, the
16365 enumeration is ill-formed. */
16366 error ("no integral type can represent all of the enumerator values "
16367 "for %qT", enumtype);
16368 precision = TYPE_PRECISION (long_long_integer_type_node);
16369 underlying_type = integer_types[itk_unsigned_long_long];
16372 /* [dcl.enum]
16374 The value of sizeof() applied to an enumeration type, an object
16375 of an enumeration type, or an enumerator, is the value of sizeof()
16376 applied to the underlying type. */
16377 copy_type_enum (enumtype, underlying_type);
16379 /* Compute the minimum and maximum values for the type.
16381 [dcl.enum]
16383 For an enumeration where emin is the smallest enumerator and emax
16384 is the largest, the values of the enumeration are the values of the
16385 underlying type in the range bmin to bmax, where bmin and bmax are,
16386 respectively, the smallest and largest values of the smallest bit-
16387 field that can store emin and emax. */
16389 /* The middle-end currently assumes that types with TYPE_PRECISION
16390 narrower than their underlying type are suitably zero or sign
16391 extended to fill their mode. Similarly, it assumes that the front
16392 end assures that a value of a particular type must be within
16393 TYPE_MIN_VALUE and TYPE_MAX_VALUE.
16395 We used to set these fields based on bmin and bmax, but that led
16396 to invalid assumptions like optimizing away bounds checking. So
16397 now we just set the TYPE_PRECISION, TYPE_MIN_VALUE, and
16398 TYPE_MAX_VALUE to the values for the mode above and only restrict
16399 the ENUM_UNDERLYING_TYPE for the benefit of diagnostics. */
16400 ENUM_UNDERLYING_TYPE (enumtype)
16401 = build_distinct_type_copy (underlying_type);
16402 TYPE_PRECISION (ENUM_UNDERLYING_TYPE (enumtype)) = precision;
16403 set_min_and_max_values_for_integral_type
16404 (ENUM_UNDERLYING_TYPE (enumtype), precision, sgn);
16406 /* If -fstrict-enums, still constrain TYPE_MIN/MAX_VALUE. */
16407 if (flag_strict_enums)
16408 set_min_and_max_values_for_integral_type (enumtype, precision, sgn);
16410 else
16411 underlying_type = ENUM_UNDERLYING_TYPE (enumtype);
16413 /* If the enum is exported, mark the consts too. */
16414 bool export_p = (UNSCOPED_ENUM_P (enumtype)
16415 && DECL_MODULE_EXPORT_P (TYPE_STUB_DECL (enumtype))
16416 && at_namespace_scope_p ());
16418 /* Convert each of the enumerators to the type of the underlying
16419 type of the enumeration. */
16420 for (values = TYPE_VALUES (enumtype); values; values = TREE_CHAIN (values))
16422 decl = TREE_VALUE (values);
16423 iloc_sentinel ils (DECL_SOURCE_LOCATION (decl));
16424 if (fixed_underlying_type_p)
16425 /* If the enumeration type has a fixed underlying type, we
16426 already checked all of the enumerator values. */
16427 value = DECL_INITIAL (decl);
16428 else
16429 value = perform_implicit_conversion (underlying_type,
16430 DECL_INITIAL (decl),
16431 tf_warning_or_error);
16432 /* Do not clobber shared ints. */
16433 if (value != error_mark_node)
16435 value = copy_node (value);
16437 TREE_TYPE (value) = enumtype;
16439 DECL_INITIAL (decl) = value;
16440 if (export_p)
16441 DECL_MODULE_EXPORT_P (decl) = true;
16444 /* Fix up all variant types of this enum type. */
16445 for (t = TYPE_MAIN_VARIANT (enumtype); t; t = TYPE_NEXT_VARIANT (t))
16446 TYPE_VALUES (t) = TYPE_VALUES (enumtype);
16448 if (at_class_scope_p ()
16449 && COMPLETE_TYPE_P (current_class_type)
16450 && UNSCOPED_ENUM_P (enumtype))
16452 insert_late_enum_def_bindings (current_class_type, enumtype);
16453 /* TYPE_FIELDS needs fixup. */
16454 fixup_type_variants (current_class_type);
16457 /* Finish debugging output for this type. */
16458 rest_of_type_compilation (enumtype, namespace_bindings_p ());
16460 /* Each enumerator now has the type of its enumeration. Clear the cache
16461 so that this change in types doesn't confuse us later on. */
16462 clear_cv_and_fold_caches ();
16465 /* Finishes the enum type. This is called only the first time an
16466 enumeration is seen, be it opaque or odinary.
16467 ENUMTYPE is the type object. */
16469 void
16470 finish_enum (tree enumtype)
16472 if (processing_template_decl)
16474 if (at_function_scope_p ())
16475 add_stmt (build_min (TAG_DEFN, enumtype));
16476 return;
16479 /* If this is a forward declaration, there should not be any variants,
16480 though we can get a variant in the middle of an enum-specifier with
16481 wacky code like 'enum E { e = sizeof(const E*) };' */
16482 gcc_assert (enumtype == TYPE_MAIN_VARIANT (enumtype)
16483 && (TYPE_VALUES (enumtype)
16484 || !TYPE_NEXT_VARIANT (enumtype)));
16487 /* Build and install a CONST_DECL for an enumeration constant of the
16488 enumeration type ENUMTYPE whose NAME and VALUE (if any) are provided.
16489 Apply ATTRIBUTES if available. LOC is the location of NAME.
16490 Assignment of sequential values by default is handled here. */
16492 tree
16493 build_enumerator (tree name, tree value, tree enumtype, tree attributes,
16494 location_t loc)
16496 tree decl;
16497 tree context;
16498 tree type;
16500 /* scalar_constant_value will pull out this expression, so make sure
16501 it's folded as appropriate. */
16502 if (processing_template_decl)
16503 value = fold_non_dependent_expr (value);
16505 /* If the VALUE was erroneous, pretend it wasn't there; that will
16506 result in the enum being assigned the next value in sequence. */
16507 if (value == error_mark_node)
16508 value = NULL_TREE;
16510 /* Remove no-op casts from the value. */
16511 if (value)
16512 STRIP_TYPE_NOPS (value);
16514 if (! processing_template_decl)
16516 /* Validate and default VALUE. */
16517 if (value != NULL_TREE)
16519 if (!ENUM_UNDERLYING_TYPE (enumtype))
16521 tree tmp_value = build_expr_type_conversion (WANT_INT | WANT_ENUM,
16522 value, true);
16523 if (tmp_value)
16524 value = tmp_value;
16526 else if (! INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P
16527 (TREE_TYPE (value)))
16528 value = perform_implicit_conversion_flags
16529 (ENUM_UNDERLYING_TYPE (enumtype), value, tf_warning_or_error,
16530 LOOKUP_IMPLICIT | LOOKUP_NO_NARROWING);
16532 if (value == error_mark_node)
16533 value = NULL_TREE;
16535 if (value != NULL_TREE)
16537 if (! INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P
16538 (TREE_TYPE (value)))
16540 error_at (cp_expr_loc_or_input_loc (value),
16541 "enumerator value for %qD must have integral or "
16542 "unscoped enumeration type", name);
16543 value = NULL_TREE;
16545 else
16547 value = cxx_constant_value (value);
16549 if (TREE_CODE (value) != INTEGER_CST)
16551 error ("enumerator value for %qD is not an integer "
16552 "constant", name);
16553 value = NULL_TREE;
16559 /* Default based on previous value. */
16560 if (value == NULL_TREE)
16562 if (TYPE_VALUES (enumtype))
16564 tree prev_value;
16566 /* C++03 7.2/4: If no initializer is specified for the first
16567 enumerator, the type is an unspecified integral
16568 type. Otherwise the type is the same as the type of the
16569 initializing value of the preceding enumerator unless the
16570 incremented value is not representable in that type, in
16571 which case the type is an unspecified integral type
16572 sufficient to contain the incremented value. */
16573 prev_value = DECL_INITIAL (TREE_VALUE (TYPE_VALUES (enumtype)));
16574 if (TREE_CODE (prev_value) != INTEGER_CST)
16575 value = error_mark_node;
16576 else
16578 wi::overflow_type overflowed;
16579 tree type = TREE_TYPE (prev_value);
16580 signop sgn = TYPE_SIGN (type);
16581 widest_int wi = wi::add (wi::to_widest (prev_value), 1, sgn,
16582 &overflowed);
16583 if (!overflowed)
16585 bool pos = !wi::neg_p (wi, sgn);
16586 if (!wi::fits_to_tree_p (wi, type))
16588 unsigned int itk;
16589 for (itk = itk_int; itk != itk_none; itk++)
16591 type = integer_types[itk];
16592 if (type != NULL_TREE
16593 && (pos || !TYPE_UNSIGNED (type))
16594 && wi::fits_to_tree_p (wi, type))
16595 break;
16597 if (type && cxx_dialect < cxx11
16598 && itk > itk_unsigned_long)
16599 pedwarn (input_location, OPT_Wlong_long,
16600 pos ? G_("\
16601 incremented enumerator value is too large for %<unsigned long%>") : G_("\
16602 incremented enumerator value is too large for %<long%>"));
16604 if (type == NULL_TREE)
16605 overflowed = wi::OVF_UNKNOWN;
16606 else
16607 value = wide_int_to_tree (type, wi);
16610 if (overflowed)
16612 error ("overflow in enumeration values at %qD", name);
16613 value = error_mark_node;
16617 else
16618 value = integer_zero_node;
16621 /* Remove no-op casts from the value. */
16622 STRIP_TYPE_NOPS (value);
16624 /* If the underlying type of the enum is fixed, check whether
16625 the enumerator values fits in the underlying type. If it
16626 does not fit, the program is ill-formed [C++0x dcl.enum]. */
16627 if (ENUM_UNDERLYING_TYPE (enumtype)
16628 && value
16629 && TREE_CODE (value) == INTEGER_CST)
16631 if (!int_fits_type_p (value, ENUM_UNDERLYING_TYPE (enumtype)))
16632 error ("enumerator value %qE is outside the range of underlying "
16633 "type %qT", value, ENUM_UNDERLYING_TYPE (enumtype));
16635 /* Convert the value to the appropriate type. */
16636 value = fold_convert (ENUM_UNDERLYING_TYPE (enumtype), value);
16640 /* C++ associates enums with global, function, or class declarations. */
16641 context = current_scope ();
16643 /* Build the actual enumeration constant. Note that the enumeration
16644 constants have the underlying type of the enum (if it is fixed)
16645 or the type of their initializer (if the underlying type of the
16646 enum is not fixed):
16648 [ C++0x dcl.enum ]
16650 If the underlying type is fixed, the type of each enumerator
16651 prior to the closing brace is the underlying type; if the
16652 initializing value of an enumerator cannot be represented by
16653 the underlying type, the program is ill-formed. If the
16654 underlying type is not fixed, the type of each enumerator is
16655 the type of its initializing value.
16657 If the underlying type is not fixed, it will be computed by
16658 finish_enum and we will reset the type of this enumerator. Of
16659 course, if we're processing a template, there may be no value. */
16660 type = value ? TREE_TYPE (value) : NULL_TREE;
16662 decl = build_decl (loc, CONST_DECL, name, type);
16664 DECL_CONTEXT (decl) = enumtype;
16665 TREE_CONSTANT (decl) = 1;
16666 TREE_READONLY (decl) = 1;
16667 DECL_INITIAL (decl) = value;
16669 if (attributes)
16670 cplus_decl_attributes (&decl, attributes, 0);
16672 if (context && context == current_class_type && !SCOPED_ENUM_P (enumtype))
16674 /* In something like `struct S { enum E { i = 7 }; };' we put `i'
16675 on the TYPE_FIELDS list for `S'. (That's so that you can say
16676 things like `S::i' later.) */
16678 /* The enumerator may be getting declared outside of its enclosing
16679 class, like so:
16681 class S { public: enum E : int; }; enum S::E : int { i = 7; };
16683 For which case we need to make sure that the access of `S::i'
16684 matches the access of `S::E'. */
16685 auto cas = make_temp_override (current_access_specifier);
16686 set_current_access_from_decl (TYPE_NAME (enumtype));
16687 finish_member_declaration (decl);
16689 else
16690 pushdecl (decl);
16692 /* Add this enumeration constant to the list for this type. */
16693 TYPE_VALUES (enumtype) = tree_cons (name, decl, TYPE_VALUES (enumtype));
16695 return decl;
16698 /* Look for an enumerator with the given NAME within the enumeration
16699 type ENUMTYPE. This routine is used primarily for qualified name
16700 lookup into an enumerator in C++0x, e.g.,
16702 enum class Color { Red, Green, Blue };
16704 Color color = Color::Red;
16706 Returns the value corresponding to the enumerator, or
16707 NULL_TREE if no such enumerator was found. */
16708 tree
16709 lookup_enumerator (tree enumtype, tree name)
16711 tree e;
16712 gcc_assert (enumtype && TREE_CODE (enumtype) == ENUMERAL_TYPE);
16714 e = purpose_member (name, TYPE_VALUES (enumtype));
16715 return e? TREE_VALUE (e) : NULL_TREE;
16718 /* Implement LANG_HOOKS_SIMULATE_ENUM_DECL. */
16720 tree
16721 cxx_simulate_enum_decl (location_t loc, const char *name,
16722 vec<string_int_pair> *values)
16724 location_t saved_loc = input_location;
16725 input_location = loc;
16727 tree enumtype = start_enum (get_identifier (name), NULL_TREE, NULL_TREE,
16728 NULL_TREE, false, NULL);
16729 if (!OPAQUE_ENUM_P (enumtype))
16731 error_at (loc, "multiple definition of %q#T", enumtype);
16732 inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
16733 "previous definition here");
16734 return enumtype;
16736 SET_OPAQUE_ENUM_P (enumtype, false);
16737 DECL_SOURCE_LOCATION (TYPE_NAME (enumtype)) = loc;
16739 for (const string_int_pair &value : values)
16740 build_enumerator (get_identifier (value.first),
16741 build_int_cst (integer_type_node, value.second),
16742 enumtype, NULL_TREE, loc);
16744 finish_enum_value_list (enumtype);
16745 finish_enum (enumtype);
16747 input_location = saved_loc;
16748 return enumtype;
16751 /* Implement LANG_HOOKS_SIMULATE_RECORD_DECL. */
16753 tree
16754 cxx_simulate_record_decl (location_t loc, const char *name,
16755 array_slice<const tree> fields)
16757 iloc_sentinel ils (loc);
16759 tree ident = get_identifier (name);
16760 tree type = xref_tag (/*tag_code=*/record_type, ident);
16761 if (type != error_mark_node
16762 && (TREE_CODE (type) != RECORD_TYPE || COMPLETE_TYPE_P (type)))
16764 error ("redefinition of %q#T", type);
16765 type = error_mark_node;
16767 if (type == error_mark_node)
16768 return lhd_simulate_record_decl (loc, name, fields);
16770 xref_basetypes (type, NULL_TREE);
16771 type = begin_class_definition (type);
16772 if (type == error_mark_node)
16773 return lhd_simulate_record_decl (loc, name, fields);
16775 for (tree field : fields)
16776 finish_member_declaration (field);
16778 type = finish_struct (type, NULL_TREE);
16780 tree decl = build_decl (loc, TYPE_DECL, ident, type);
16781 set_underlying_type (decl);
16782 lang_hooks.decls.pushdecl (decl);
16784 return type;
16787 /* We're defining DECL. Make sure that its type is OK. */
16789 static void
16790 check_function_type (tree decl, tree current_function_parms)
16792 tree fntype = TREE_TYPE (decl);
16793 tree return_type = complete_type (TREE_TYPE (fntype));
16795 /* In a function definition, arg types must be complete. */
16796 require_complete_types_for_parms (current_function_parms);
16798 if (dependent_type_p (return_type)
16799 || type_uses_auto (return_type))
16800 return;
16801 if (!COMPLETE_OR_VOID_TYPE_P (return_type))
16803 tree args = TYPE_ARG_TYPES (fntype);
16805 error ("return type %q#T is incomplete", return_type);
16807 /* Make it return void instead. */
16808 if (TREE_CODE (fntype) == METHOD_TYPE)
16809 fntype = build_method_type_directly (TREE_TYPE (TREE_VALUE (args)),
16810 void_type_node,
16811 TREE_CHAIN (args));
16812 else
16813 fntype = build_function_type (void_type_node, args);
16814 fntype = (cp_build_type_attribute_variant
16815 (fntype, TYPE_ATTRIBUTES (TREE_TYPE (decl))));
16816 fntype = cxx_copy_lang_qualifiers (fntype, TREE_TYPE (decl));
16817 TREE_TYPE (decl) = fntype;
16819 else
16821 abstract_virtuals_error (decl, TREE_TYPE (fntype));
16822 maybe_warn_parm_abi (TREE_TYPE (fntype),
16823 DECL_SOURCE_LOCATION (decl));
16827 /* True iff FN is an implicitly-defined default constructor. */
16829 static bool
16830 implicit_default_ctor_p (tree fn)
16832 return (DECL_CONSTRUCTOR_P (fn)
16833 && !user_provided_p (fn)
16834 && sufficient_parms_p (FUNCTION_FIRST_USER_PARMTYPE (fn)));
16837 /* Clobber the contents of *this to let the back end know that the object
16838 storage is dead when we enter the constructor or leave the destructor. */
16840 static tree
16841 build_clobber_this ()
16843 /* Clobbering an empty base is pointless, and harmful if its one byte
16844 TYPE_SIZE overlays real data. */
16845 if (is_empty_class (current_class_type))
16846 return void_node;
16848 /* If we have virtual bases, clobber the whole object, but only if we're in
16849 charge. If we don't have virtual bases, clobber the as-base type so we
16850 don't mess with tail padding. */
16851 bool vbases = CLASSTYPE_VBASECLASSES (current_class_type);
16853 tree ctype = current_class_type;
16854 if (!vbases)
16855 ctype = CLASSTYPE_AS_BASE (ctype);
16857 tree clobber = build_clobber (ctype);
16859 tree thisref = current_class_ref;
16860 if (ctype != current_class_type)
16862 thisref = build_nop (build_reference_type (ctype), current_class_ptr);
16863 thisref = convert_from_reference (thisref);
16866 tree exprstmt = build2 (MODIFY_EXPR, void_type_node, thisref, clobber);
16867 if (vbases)
16868 exprstmt = build_if_in_charge (exprstmt);
16870 return exprstmt;
16873 /* Create the FUNCTION_DECL for a function definition.
16874 DECLSPECS and DECLARATOR are the parts of the declaration;
16875 they describe the function's name and the type it returns,
16876 but twisted together in a fashion that parallels the syntax of C.
16878 FLAGS is a bitwise or of SF_PRE_PARSED (indicating that the
16879 DECLARATOR is really the DECL for the function we are about to
16880 process and that DECLSPECS should be ignored), SF_INCLASS_INLINE
16881 indicating that the function is an inline defined in-class.
16883 This function creates a binding context for the function body
16884 as well as setting up the FUNCTION_DECL in current_function_decl.
16886 For C++, we must first check whether that datum makes any sense.
16887 For example, "class A local_a(1,2);" means that variable local_a
16888 is an aggregate of type A, which should have a constructor
16889 applied to it with the argument list [1, 2].
16891 On entry, DECL_INITIAL (decl1) should be NULL_TREE or error_mark_node,
16892 or may be a BLOCK if the function has been defined previously
16893 in this translation unit. On exit, DECL_INITIAL (decl1) will be
16894 error_mark_node if the function has never been defined, or
16895 a BLOCK if the function has been defined somewhere. */
16897 bool
16898 start_preparsed_function (tree decl1, tree attrs, int flags)
16900 tree ctype = NULL_TREE;
16901 bool doing_friend = false;
16903 /* Sanity check. */
16904 gcc_assert (VOID_TYPE_P (TREE_VALUE (void_list_node)));
16905 gcc_assert (TREE_CHAIN (void_list_node) == NULL_TREE);
16907 tree fntype = TREE_TYPE (decl1);
16908 if (TREE_CODE (fntype) == METHOD_TYPE)
16909 ctype = TYPE_METHOD_BASETYPE (fntype);
16910 else
16912 ctype = DECL_FRIEND_CONTEXT (decl1);
16914 if (ctype)
16915 doing_friend = true;
16918 if (DECL_DECLARED_INLINE_P (decl1)
16919 && lookup_attribute ("noinline", attrs))
16920 warning_at (DECL_SOURCE_LOCATION (decl1), 0,
16921 "inline function %qD given attribute %qs", decl1, "noinline");
16923 /* Handle gnu_inline attribute. */
16924 if (GNU_INLINE_P (decl1))
16926 DECL_EXTERNAL (decl1) = 1;
16927 DECL_NOT_REALLY_EXTERN (decl1) = 0;
16928 DECL_INTERFACE_KNOWN (decl1) = 1;
16929 DECL_DISREGARD_INLINE_LIMITS (decl1) = 1;
16932 if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (decl1))
16933 /* This is a constructor, we must ensure that any default args
16934 introduced by this definition are propagated to the clones
16935 now. The clones are used directly in overload resolution. */
16936 adjust_clone_args (decl1);
16938 /* Sometimes we don't notice that a function is a static member, and
16939 build a METHOD_TYPE for it. Fix that up now. */
16940 gcc_assert (!(ctype != NULL_TREE && DECL_STATIC_FUNCTION_P (decl1)
16941 && TREE_CODE (TREE_TYPE (decl1)) == METHOD_TYPE));
16943 /* Set up current_class_type, and enter the scope of the class, if
16944 appropriate. */
16945 if (ctype)
16946 push_nested_class (ctype);
16947 else if (DECL_STATIC_FUNCTION_P (decl1))
16948 push_nested_class (DECL_CONTEXT (decl1));
16950 /* Now that we have entered the scope of the class, we must restore
16951 the bindings for any template parameters surrounding DECL1, if it
16952 is an inline member template. (Order is important; consider the
16953 case where a template parameter has the same name as a field of
16954 the class.) It is not until after this point that
16955 PROCESSING_TEMPLATE_DECL is guaranteed to be set up correctly. */
16956 if (flags & SF_INCLASS_INLINE)
16957 maybe_begin_member_template_processing (decl1);
16959 /* Effective C++ rule 15. */
16960 if (warn_ecpp
16961 && DECL_ASSIGNMENT_OPERATOR_P (decl1)
16962 && DECL_OVERLOADED_OPERATOR_IS (decl1, NOP_EXPR)
16963 && VOID_TYPE_P (TREE_TYPE (fntype)))
16964 warning (OPT_Weffc__,
16965 "%<operator=%> should return a reference to %<*this%>");
16967 /* Make the init_value nonzero so pushdecl knows this is not tentative.
16968 error_mark_node is replaced below (in poplevel) with the BLOCK. */
16969 if (!DECL_INITIAL (decl1))
16970 DECL_INITIAL (decl1) = error_mark_node;
16972 /* This function exists in static storage.
16973 (This does not mean `static' in the C sense!) */
16974 TREE_STATIC (decl1) = 1;
16976 /* We must call push_template_decl after current_class_type is set
16977 up. (If we are processing inline definitions after exiting a
16978 class scope, current_class_type will be NULL_TREE until set above
16979 by push_nested_class.) */
16980 if (processing_template_decl)
16982 tree newdecl1 = push_template_decl (decl1, doing_friend);
16983 if (newdecl1 == error_mark_node)
16985 if (ctype || DECL_STATIC_FUNCTION_P (decl1))
16986 pop_nested_class ();
16987 return false;
16989 decl1 = newdecl1;
16992 /* Make sure the parameter and return types are reasonable. When
16993 you declare a function, these types can be incomplete, but they
16994 must be complete when you define the function. */
16995 check_function_type (decl1, DECL_ARGUMENTS (decl1));
16997 /* Build the return declaration for the function. */
16998 tree restype = TREE_TYPE (fntype);
17000 if (DECL_RESULT (decl1) == NULL_TREE)
17002 tree resdecl;
17004 resdecl = build_decl (input_location, RESULT_DECL, 0, restype);
17005 DECL_ARTIFICIAL (resdecl) = 1;
17006 DECL_IGNORED_P (resdecl) = 1;
17007 DECL_RESULT (decl1) = resdecl;
17009 cp_apply_type_quals_to_decl (cp_type_quals (restype), resdecl);
17012 /* Record the decl so that the function name is defined.
17013 If we already have a decl for this name, and it is a FUNCTION_DECL,
17014 use the old decl. */
17015 if (!processing_template_decl && !(flags & SF_PRE_PARSED))
17017 /* A specialization is not used to guide overload resolution. */
17018 if (!DECL_FUNCTION_MEMBER_P (decl1)
17019 && !(DECL_USE_TEMPLATE (decl1) &&
17020 PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl1))))
17022 tree olddecl = pushdecl (decl1);
17024 if (olddecl == error_mark_node)
17025 /* If something went wrong when registering the declaration,
17026 use DECL1; we have to have a FUNCTION_DECL to use when
17027 parsing the body of the function. */
17029 else
17031 /* Otherwise, OLDDECL is either a previous declaration
17032 of the same function or DECL1 itself. */
17034 if (warn_missing_declarations
17035 && olddecl == decl1
17036 && !DECL_MAIN_P (decl1)
17037 && TREE_PUBLIC (decl1)
17038 && !DECL_DECLARED_INLINE_P (decl1))
17040 tree context;
17042 /* Check whether DECL1 is in an anonymous
17043 namespace. */
17044 for (context = DECL_CONTEXT (decl1);
17045 context;
17046 context = DECL_CONTEXT (context))
17048 if (TREE_CODE (context) == NAMESPACE_DECL
17049 && DECL_NAME (context) == NULL_TREE)
17050 break;
17053 if (context == NULL)
17054 warning_at (DECL_SOURCE_LOCATION (decl1),
17055 OPT_Wmissing_declarations,
17056 "no previous declaration for %qD", decl1);
17059 decl1 = olddecl;
17062 else
17064 /* We need to set the DECL_CONTEXT. */
17065 if (!DECL_CONTEXT (decl1) && DECL_TEMPLATE_INFO (decl1))
17066 DECL_CONTEXT (decl1) = DECL_CONTEXT (DECL_TI_TEMPLATE (decl1));
17068 fntype = TREE_TYPE (decl1);
17069 restype = TREE_TYPE (fntype);
17071 /* If #pragma weak applies, mark the decl appropriately now.
17072 The pragma only applies to global functions. Because
17073 determining whether or not the #pragma applies involves
17074 computing the mangled name for the declaration, we cannot
17075 apply the pragma until after we have merged this declaration
17076 with any previous declarations; if the original declaration
17077 has a linkage specification, that specification applies to
17078 the definition as well, and may affect the mangled name. */
17079 if (DECL_FILE_SCOPE_P (decl1))
17080 maybe_apply_pragma_weak (decl1);
17083 /* We are now in the scope of the function being defined. */
17084 current_function_decl = decl1;
17086 /* Save the parm names or decls from this function's declarator
17087 where store_parm_decls will find them. */
17088 tree current_function_parms = DECL_ARGUMENTS (decl1);
17090 /* Let the user know we're compiling this function. */
17091 announce_function (decl1);
17093 gcc_assert (DECL_INITIAL (decl1));
17095 /* This function may already have been parsed, in which case just
17096 return; our caller will skip over the body without parsing. */
17097 if (DECL_INITIAL (decl1) != error_mark_node)
17098 return true;
17100 /* Initialize RTL machinery. We cannot do this until
17101 CURRENT_FUNCTION_DECL and DECL_RESULT are set up. We do this
17102 even when processing a template; this is how we get
17103 CFUN set up, and our per-function variables initialized.
17104 FIXME factor out the non-RTL stuff. */
17105 cp_binding_level *bl = current_binding_level;
17106 allocate_struct_function (decl1, processing_template_decl);
17108 /* Initialize the language data structures. Whenever we start
17109 a new function, we destroy temporaries in the usual way. */
17110 cfun->language = ggc_cleared_alloc<language_function> ();
17111 current_stmt_tree ()->stmts_are_full_exprs_p = 1;
17112 current_binding_level = bl;
17114 /* If we are (erroneously) defining a function that we have already
17115 defined before, wipe out what we knew before. */
17116 gcc_checking_assert (!DECL_PENDING_INLINE_P (decl1));
17117 FNDECL_USED_AUTO (decl1) = false;
17118 DECL_SAVED_AUTO_RETURN_TYPE (decl1) = NULL;
17120 if (!processing_template_decl && type_uses_auto (restype))
17122 FNDECL_USED_AUTO (decl1) = true;
17123 DECL_SAVED_AUTO_RETURN_TYPE (decl1) = restype;
17126 /* Start the statement-tree, start the tree now. */
17127 DECL_SAVED_TREE (decl1) = push_stmt_list ();
17129 if (ctype && !doing_friend && !DECL_STATIC_FUNCTION_P (decl1))
17131 /* We know that this was set up by `grokclassfn'. We do not
17132 wait until `store_parm_decls', since evil parse errors may
17133 never get us to that point. Here we keep the consistency
17134 between `current_class_type' and `current_class_ptr'. */
17135 tree t = DECL_ARGUMENTS (decl1);
17137 gcc_assert (t != NULL_TREE && TREE_CODE (t) == PARM_DECL);
17138 gcc_assert (TYPE_PTR_P (TREE_TYPE (t)));
17140 cp_function_chain->x_current_class_ref
17141 = cp_build_fold_indirect_ref (t);
17142 /* Set this second to avoid shortcut in cp_build_indirect_ref. */
17143 cp_function_chain->x_current_class_ptr = t;
17145 /* Constructors and destructors need to know whether they're "in
17146 charge" of initializing virtual base classes. */
17147 t = DECL_CHAIN (t);
17148 if (DECL_HAS_IN_CHARGE_PARM_P (decl1))
17150 current_in_charge_parm = t;
17151 t = DECL_CHAIN (t);
17153 if (DECL_HAS_VTT_PARM_P (decl1))
17155 gcc_assert (DECL_NAME (t) == vtt_parm_identifier);
17156 current_vtt_parm = t;
17160 bool honor_interface = (!DECL_TEMPLATE_INSTANTIATION (decl1)
17161 /* Implicitly-defined methods (like the
17162 destructor for a class in which no destructor
17163 is explicitly declared) must not be defined
17164 until their definition is needed. So, we
17165 ignore interface specifications for
17166 compiler-generated functions. */
17167 && !DECL_ARTIFICIAL (decl1));
17168 struct c_fileinfo *finfo
17169 = get_fileinfo (LOCATION_FILE (DECL_SOURCE_LOCATION (decl1)));
17171 if (processing_template_decl)
17172 /* Don't mess with interface flags. */;
17173 else if (DECL_INTERFACE_KNOWN (decl1))
17175 tree ctx = decl_function_context (decl1);
17177 if (DECL_NOT_REALLY_EXTERN (decl1))
17178 DECL_EXTERNAL (decl1) = 0;
17180 if (ctx != NULL_TREE && vague_linkage_p (ctx))
17181 /* This is a function in a local class in an extern inline
17182 or template function. */
17183 comdat_linkage (decl1);
17185 /* If this function belongs to an interface, it is public.
17186 If it belongs to someone else's interface, it is also external.
17187 This only affects inlines and template instantiations. */
17188 else if (!finfo->interface_unknown && honor_interface)
17190 if (DECL_DECLARED_INLINE_P (decl1)
17191 || DECL_TEMPLATE_INSTANTIATION (decl1))
17193 DECL_EXTERNAL (decl1)
17194 = (finfo->interface_only
17195 || (DECL_DECLARED_INLINE_P (decl1)
17196 && ! flag_implement_inlines
17197 && !DECL_VINDEX (decl1)));
17199 /* For WIN32 we also want to put these in linkonce sections. */
17200 maybe_make_one_only (decl1);
17202 else
17203 DECL_EXTERNAL (decl1) = 0;
17204 DECL_INTERFACE_KNOWN (decl1) = 1;
17205 /* If this function is in an interface implemented in this file,
17206 make sure that the back end knows to emit this function
17207 here. */
17208 if (!DECL_EXTERNAL (decl1))
17209 mark_needed (decl1);
17211 else if (finfo->interface_unknown && finfo->interface_only
17212 && honor_interface)
17214 /* If MULTIPLE_SYMBOL_SPACES is defined and we saw a #pragma
17215 interface, we will have both finfo->interface_unknown and
17216 finfo->interface_only set. In that case, we don't want to
17217 use the normal heuristics because someone will supply a
17218 #pragma implementation elsewhere, and deducing it here would
17219 produce a conflict. */
17220 comdat_linkage (decl1);
17221 DECL_EXTERNAL (decl1) = 0;
17222 DECL_INTERFACE_KNOWN (decl1) = 1;
17223 DECL_DEFER_OUTPUT (decl1) = 1;
17225 else
17227 /* This is a definition, not a reference.
17228 So clear DECL_EXTERNAL, unless this is a GNU extern inline. */
17229 if (!GNU_INLINE_P (decl1))
17230 DECL_EXTERNAL (decl1) = 0;
17232 if ((DECL_DECLARED_INLINE_P (decl1)
17233 || DECL_TEMPLATE_INSTANTIATION (decl1))
17234 && ! DECL_INTERFACE_KNOWN (decl1))
17235 DECL_DEFER_OUTPUT (decl1) = 1;
17236 else
17237 DECL_INTERFACE_KNOWN (decl1) = 1;
17240 /* Determine the ELF visibility attribute for the function. We must not
17241 do this before calling "pushdecl", as we must allow "duplicate_decls"
17242 to merge any attributes appropriately. We also need to wait until
17243 linkage is set. */
17244 if (!DECL_CLONED_FUNCTION_P (decl1))
17245 determine_visibility (decl1);
17247 if (!processing_template_decl)
17248 maybe_instantiate_noexcept (decl1);
17250 begin_scope (sk_function_parms, decl1);
17252 ++function_depth;
17254 if (DECL_DESTRUCTOR_P (decl1)
17255 || (DECL_CONSTRUCTOR_P (decl1)
17256 && targetm.cxx.cdtor_returns_this ()))
17258 cdtor_label = create_artificial_label (input_location);
17259 LABEL_DECL_CDTOR (cdtor_label) = true;
17262 start_fname_decls ();
17264 store_parm_decls (current_function_parms);
17266 if (!processing_template_decl
17267 && (flag_lifetime_dse > 1)
17268 && DECL_CONSTRUCTOR_P (decl1)
17269 && !DECL_CLONED_FUNCTION_P (decl1)
17270 /* Clobbering an empty base is harmful if it overlays real data. */
17271 && !is_empty_class (current_class_type)
17272 /* We can't clobber safely for an implicitly-defined default constructor
17273 because part of the initialization might happen before we enter the
17274 constructor, via AGGR_INIT_ZERO_FIRST (c++/68006). */
17275 && !implicit_default_ctor_p (decl1))
17276 finish_expr_stmt (build_clobber_this ());
17278 if (!processing_template_decl
17279 && DECL_CONSTRUCTOR_P (decl1)
17280 && sanitize_flags_p (SANITIZE_VPTR)
17281 && !DECL_CLONED_FUNCTION_P (decl1)
17282 && !implicit_default_ctor_p (decl1))
17283 cp_ubsan_maybe_initialize_vtbl_ptrs (current_class_ptr);
17285 if (!DECL_OMP_DECLARE_REDUCTION_P (decl1))
17286 start_lambda_scope (decl1);
17288 return true;
17292 /* Like start_preparsed_function, except that instead of a
17293 FUNCTION_DECL, this function takes DECLSPECS and DECLARATOR.
17295 Returns true on success. If the DECLARATOR is not suitable
17296 for a function, we return false, which tells the parser to
17297 skip the entire function. */
17299 bool
17300 start_function (cp_decl_specifier_seq *declspecs,
17301 const cp_declarator *declarator,
17302 tree attrs)
17304 tree decl1;
17306 decl1 = grokdeclarator (declarator, declspecs, FUNCDEF, 1, &attrs);
17307 invoke_plugin_callbacks (PLUGIN_START_PARSE_FUNCTION, decl1);
17308 if (decl1 == error_mark_node)
17309 return false;
17311 if (DECL_MAIN_P (decl1))
17312 /* main must return int. grokfndecl should have corrected it
17313 (and issued a diagnostic) if the user got it wrong. */
17314 gcc_assert (same_type_p (TREE_TYPE (TREE_TYPE (decl1)),
17315 integer_type_node));
17317 return start_preparsed_function (decl1, attrs, /*flags=*/SF_DEFAULT);
17320 /* Returns true iff an EH_SPEC_BLOCK should be created in the body of
17321 FN. */
17323 static bool
17324 use_eh_spec_block (tree fn)
17326 return (flag_exceptions && flag_enforce_eh_specs
17327 && !processing_template_decl
17328 /* We insert the EH_SPEC_BLOCK only in the original
17329 function; then, it is copied automatically to the
17330 clones. */
17331 && !DECL_CLONED_FUNCTION_P (fn)
17332 /* Implicitly-generated constructors and destructors have
17333 exception specifications. However, those specifications
17334 are the union of the possible exceptions specified by the
17335 constructors/destructors for bases and members, so no
17336 unallowed exception will ever reach this function. By
17337 not creating the EH_SPEC_BLOCK we save a little memory,
17338 and we avoid spurious warnings about unreachable
17339 code. */
17340 && !DECL_DEFAULTED_FN (fn)
17341 && !type_throw_all_p (TREE_TYPE (fn)));
17344 /* Helper function to push ARGS into the current lexical scope. DECL
17345 is the function declaration. NONPARMS is used to handle enum
17346 constants. */
17348 void
17349 do_push_parm_decls (tree decl, tree args, tree *nonparms)
17351 /* If we're doing semantic analysis, then we'll call pushdecl
17352 for each of these. We must do them in reverse order so that
17353 they end in the correct forward order. */
17354 args = nreverse (args);
17356 tree next;
17357 for (tree parm = args; parm; parm = next)
17359 next = DECL_CHAIN (parm);
17360 if (TREE_CODE (parm) == PARM_DECL)
17361 pushdecl (parm);
17362 else if (nonparms)
17364 /* If we find an enum constant or a type tag, put it aside for
17365 the moment. */
17366 TREE_CHAIN (parm) = NULL_TREE;
17367 *nonparms = chainon (*nonparms, parm);
17371 /* Get the decls in their original chain order and record in the
17372 function. This is all and only the PARM_DECLs that were
17373 pushed into scope by the loop above. */
17374 DECL_ARGUMENTS (decl) = get_local_decls ();
17377 /* Store the parameter declarations into the current function declaration.
17378 This is called after parsing the parameter declarations, before
17379 digesting the body of the function.
17381 Also install to binding contour return value identifier, if any. */
17383 static void
17384 store_parm_decls (tree current_function_parms)
17386 tree fndecl = current_function_decl;
17388 /* This is a chain of any other decls that came in among the parm
17389 declarations. If a parm is declared with enum {foo, bar} x;
17390 then CONST_DECLs for foo and bar are put here. */
17391 tree nonparms = NULL_TREE;
17393 if (current_function_parms)
17395 /* This case is when the function was defined with an ANSI prototype.
17396 The parms already have decls, so we need not do anything here
17397 except record them as in effect
17398 and complain if any redundant old-style parm decls were written. */
17400 tree specparms = current_function_parms;
17402 /* Must clear this because it might contain TYPE_DECLs declared
17403 at class level. */
17404 current_binding_level->names = NULL;
17406 do_push_parm_decls (fndecl, specparms, &nonparms);
17408 else
17409 DECL_ARGUMENTS (fndecl) = NULL_TREE;
17411 /* Now store the final chain of decls for the arguments
17412 as the decl-chain of the current lexical scope.
17413 Put the enumerators in as well, at the front so that
17414 DECL_ARGUMENTS is not modified. */
17415 current_binding_level->names = chainon (nonparms, DECL_ARGUMENTS (fndecl));
17417 if (use_eh_spec_block (current_function_decl))
17418 current_eh_spec_block = begin_eh_spec_block ();
17422 /* Set the return value of the constructor (if present). */
17424 static void
17425 finish_constructor_body (void)
17427 tree val;
17428 tree exprstmt;
17430 if (targetm.cxx.cdtor_returns_this ())
17432 /* Any return from a constructor will end up here. */
17433 add_stmt (build_stmt (input_location, LABEL_EXPR, cdtor_label));
17435 val = DECL_ARGUMENTS (current_function_decl);
17436 suppress_warning (val, OPT_Wuse_after_free);
17437 val = build2 (MODIFY_EXPR, TREE_TYPE (val),
17438 DECL_RESULT (current_function_decl), val);
17439 /* Return the address of the object. */
17440 exprstmt = build_stmt (input_location, RETURN_EXPR, val);
17441 add_stmt (exprstmt);
17445 /* Do all the processing for the beginning of a destructor; set up the
17446 vtable pointers and cleanups for bases and members. */
17448 static void
17449 begin_destructor_body (void)
17451 tree compound_stmt;
17453 /* If the CURRENT_CLASS_TYPE is incomplete, we will have already
17454 issued an error message. We still want to try to process the
17455 body of the function, but initialize_vtbl_ptrs will crash if
17456 TYPE_BINFO is NULL. */
17457 if (COMPLETE_TYPE_P (current_class_type))
17459 compound_stmt = begin_compound_stmt (0);
17460 /* Make all virtual function table pointers in non-virtual base
17461 classes point to CURRENT_CLASS_TYPE's virtual function
17462 tables. */
17463 initialize_vtbl_ptrs (current_class_ptr);
17464 finish_compound_stmt (compound_stmt);
17466 if (flag_lifetime_dse
17467 /* Clobbering an empty base is harmful if it overlays real data. */
17468 && !is_empty_class (current_class_type))
17470 if (sanitize_flags_p (SANITIZE_VPTR)
17471 && (flag_sanitize_recover & SANITIZE_VPTR) == 0
17472 && TYPE_CONTAINS_VPTR_P (current_class_type))
17474 tree binfo = TYPE_BINFO (current_class_type);
17475 tree ref
17476 = cp_build_fold_indirect_ref (current_class_ptr);
17478 tree vtbl_ptr = build_vfield_ref (ref, TREE_TYPE (binfo));
17479 tree vtbl = build_zero_cst (TREE_TYPE (vtbl_ptr));
17480 tree stmt = cp_build_modify_expr (input_location, vtbl_ptr,
17481 NOP_EXPR, vtbl,
17482 tf_warning_or_error);
17483 /* If the vptr is shared with some virtual nearly empty base,
17484 don't clear it if not in charge, the dtor of the virtual
17485 nearly empty base will do that later. */
17486 if (CLASSTYPE_VBASECLASSES (current_class_type))
17488 tree c = current_class_type;
17489 while (CLASSTYPE_PRIMARY_BINFO (c))
17491 if (BINFO_VIRTUAL_P (CLASSTYPE_PRIMARY_BINFO (c)))
17493 stmt = convert_to_void (stmt, ICV_STATEMENT,
17494 tf_warning_or_error);
17495 stmt = build_if_in_charge (stmt);
17496 break;
17498 c = BINFO_TYPE (CLASSTYPE_PRIMARY_BINFO (c));
17501 finish_decl_cleanup (NULL_TREE, stmt);
17503 else
17504 finish_decl_cleanup (NULL_TREE, build_clobber_this ());
17507 /* And insert cleanups for our bases and members so that they
17508 will be properly destroyed if we throw. */
17509 push_base_cleanups ();
17513 /* At the end of every destructor we generate code to delete the object if
17514 necessary. Do that now. */
17516 static void
17517 finish_destructor_body (void)
17519 tree exprstmt;
17521 /* Any return from a destructor will end up here; that way all base
17522 and member cleanups will be run when the function returns. */
17523 add_stmt (build_stmt (input_location, LABEL_EXPR, cdtor_label));
17525 if (targetm.cxx.cdtor_returns_this ())
17527 tree val;
17529 val = DECL_ARGUMENTS (current_function_decl);
17530 suppress_warning (val, OPT_Wuse_after_free);
17531 val = build2 (MODIFY_EXPR, TREE_TYPE (val),
17532 DECL_RESULT (current_function_decl), val);
17533 /* Return the address of the object. */
17534 exprstmt = build_stmt (input_location, RETURN_EXPR, val);
17535 add_stmt (exprstmt);
17539 /* Do the necessary processing for the beginning of a function body, which
17540 in this case includes member-initializers, but not the catch clauses of
17541 a function-try-block. Currently, this means opening a binding level
17542 for the member-initializers (in a ctor), member cleanups (in a dtor),
17543 and capture proxies (in a lambda operator()). */
17545 tree
17546 begin_function_body (void)
17548 if (! FUNCTION_NEEDS_BODY_BLOCK (current_function_decl))
17549 return NULL_TREE;
17551 if (processing_template_decl)
17552 /* Do nothing now. */;
17553 else
17554 /* Always keep the BLOCK node associated with the outermost pair of
17555 curly braces of a function. These are needed for correct
17556 operation of dwarfout.c. */
17557 keep_next_level (true);
17559 tree stmt = begin_compound_stmt (BCS_FN_BODY);
17561 if (processing_template_decl)
17562 /* Do nothing now. */;
17563 else if (DECL_DESTRUCTOR_P (current_function_decl))
17564 begin_destructor_body ();
17566 return stmt;
17569 /* Do the processing for the end of a function body. Currently, this means
17570 closing out the cleanups for fully-constructed bases and members, and in
17571 the case of the destructor, deleting the object if desired. Again, this
17572 is only meaningful for [cd]tors, since they are the only functions where
17573 there is a significant distinction between the main body and any
17574 function catch clauses. Handling, say, main() return semantics here
17575 would be wrong, as flowing off the end of a function catch clause for
17576 main() would also need to return 0. */
17578 void
17579 finish_function_body (tree compstmt)
17581 if (compstmt == NULL_TREE)
17582 return;
17584 /* Close the block. */
17585 finish_compound_stmt (compstmt);
17587 if (processing_template_decl)
17588 /* Do nothing now. */;
17589 else if (DECL_CONSTRUCTOR_P (current_function_decl))
17590 finish_constructor_body ();
17591 else if (DECL_DESTRUCTOR_P (current_function_decl))
17592 finish_destructor_body ();
17595 /* Given a function, returns the BLOCK corresponding to the outermost level
17596 of curly braces, skipping the artificial block created for constructor
17597 initializers. */
17599 tree
17600 outer_curly_brace_block (tree fndecl)
17602 tree block = DECL_INITIAL (fndecl);
17603 if (BLOCK_OUTER_CURLY_BRACE_P (block))
17604 return block;
17605 block = BLOCK_SUBBLOCKS (block);
17606 if (BLOCK_OUTER_CURLY_BRACE_P (block))
17607 return block;
17608 block = BLOCK_SUBBLOCKS (block);
17609 gcc_assert (BLOCK_OUTER_CURLY_BRACE_P (block));
17610 return block;
17613 /* If FNDECL is a class's key method, add the class to the list of
17614 keyed classes that should be emitted. */
17616 static void
17617 record_key_method_defined (tree fndecl)
17619 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
17620 && DECL_VIRTUAL_P (fndecl)
17621 && !processing_template_decl)
17623 tree fnclass = DECL_CONTEXT (fndecl);
17624 if (fndecl == CLASSTYPE_KEY_METHOD (fnclass))
17625 vec_safe_push (keyed_classes, fnclass);
17629 /* Attempt to add a fix-it hint to RICHLOC suggesting the insertion
17630 of "return *this;" immediately before its location, using FNDECL's
17631 first statement (if any) to give the indentation, if appropriate. */
17633 static void
17634 add_return_star_this_fixit (gcc_rich_location *richloc, tree fndecl)
17636 location_t indent = UNKNOWN_LOCATION;
17637 tree stmts = expr_first (DECL_SAVED_TREE (fndecl));
17638 if (stmts)
17639 indent = EXPR_LOCATION (stmts);
17640 richloc->add_fixit_insert_formatted ("return *this;",
17641 richloc->get_loc (),
17642 indent);
17645 /* This function carries out the subset of finish_function operations needed
17646 to emit the compiler-generated outlined helper functions used by the
17647 coroutines implementation. */
17649 static void
17650 emit_coro_helper (tree helper)
17652 /* This is a partial set of the operations done by finish_function()
17653 plus emitting the result. */
17654 set_cfun (NULL);
17655 current_function_decl = helper;
17656 begin_scope (sk_function_parms, NULL);
17657 store_parm_decls (DECL_ARGUMENTS (helper));
17658 announce_function (helper);
17659 allocate_struct_function (helper, false);
17660 cfun->language = ggc_cleared_alloc<language_function> ();
17661 poplevel (1, 0, 1);
17662 maybe_save_constexpr_fundef (helper);
17663 /* We must start each function with a clear fold cache. */
17664 clear_fold_cache ();
17665 cp_fold_function (helper);
17666 DECL_CONTEXT (DECL_RESULT (helper)) = helper;
17667 BLOCK_SUPERCONTEXT (DECL_INITIAL (helper)) = helper;
17668 /* This function has coroutine IFNs that we should handle in middle
17669 end lowering. */
17670 cfun->coroutine_component = true;
17671 cp_genericize (helper);
17672 expand_or_defer_fn (helper);
17675 /* Finish up a function declaration and compile that function
17676 all the way to assembler language output. The free the storage
17677 for the function definition. INLINE_P is TRUE if we just
17678 finished processing the body of an in-class inline function
17679 definition. (This processing will have taken place after the
17680 class definition is complete.) */
17682 tree
17683 finish_function (bool inline_p)
17685 tree fndecl = current_function_decl;
17686 tree fntype, ctype = NULL_TREE;
17687 tree resumer = NULL_TREE, destroyer = NULL_TREE;
17688 bool coro_p = flag_coroutines
17689 && !processing_template_decl
17690 && DECL_COROUTINE_P (fndecl);
17691 bool coro_emit_helpers = false;
17693 /* When we get some parse errors, we can end up without a
17694 current_function_decl, so cope. */
17695 if (fndecl == NULL_TREE)
17696 return error_mark_node;
17698 if (!DECL_OMP_DECLARE_REDUCTION_P (fndecl))
17699 finish_lambda_scope ();
17701 if (c_dialect_objc ())
17702 objc_finish_function ();
17704 record_key_method_defined (fndecl);
17706 fntype = TREE_TYPE (fndecl);
17708 /* TREE_READONLY (fndecl) = 1;
17709 This caused &foo to be of type ptr-to-const-function
17710 which then got a warning when stored in a ptr-to-function variable. */
17712 gcc_assert (building_stmt_list_p ());
17713 /* The current function is being defined, so its DECL_INITIAL should
17714 be set, and unless there's a multiple definition, it should be
17715 error_mark_node. */
17716 gcc_assert (DECL_INITIAL (fndecl) == error_mark_node);
17718 if (coro_p)
17720 /* Only try to emit the coroutine outlined helper functions if the
17721 transforms succeeded. Otherwise, treat errors in the same way as
17722 a regular function. */
17723 coro_emit_helpers = morph_fn_to_coro (fndecl, &resumer, &destroyer);
17725 /* We should handle coroutine IFNs in middle end lowering. */
17726 cfun->coroutine_component = true;
17728 /* Do not try to process the ramp's EH unless outlining succeeded. */
17729 if (coro_emit_helpers && use_eh_spec_block (fndecl))
17730 finish_eh_spec_block (TYPE_RAISES_EXCEPTIONS
17731 (TREE_TYPE (fndecl)),
17732 current_eh_spec_block);
17734 else
17735 /* For a cloned function, we've already got all the code we need;
17736 there's no need to add any extra bits. */
17737 if (!DECL_CLONED_FUNCTION_P (fndecl))
17739 /* Make it so that `main' always returns 0 by default. */
17740 if (DECL_MAIN_P (current_function_decl))
17741 finish_return_stmt (integer_zero_node);
17743 if (use_eh_spec_block (current_function_decl))
17744 finish_eh_spec_block (TYPE_RAISES_EXCEPTIONS
17745 (TREE_TYPE (current_function_decl)),
17746 current_eh_spec_block);
17749 /* If we're saving up tree structure, tie off the function now. */
17750 DECL_SAVED_TREE (fndecl) = pop_stmt_list (DECL_SAVED_TREE (fndecl));
17752 finish_fname_decls ();
17754 /* If this function can't throw any exceptions, remember that. */
17755 if (!processing_template_decl
17756 && !cp_function_chain->can_throw
17757 && !flag_non_call_exceptions
17758 && !decl_replaceable_p (fndecl,
17759 opt_for_fn (fndecl, flag_semantic_interposition)))
17760 TREE_NOTHROW (fndecl) = 1;
17762 /* This must come after expand_function_end because cleanups might
17763 have declarations (from inline functions) that need to go into
17764 this function's blocks. */
17766 /* If the current binding level isn't the outermost binding level
17767 for this function, either there is a bug, or we have experienced
17768 syntax errors and the statement tree is malformed. */
17769 if (current_binding_level->kind != sk_function_parms)
17771 /* Make sure we have already experienced errors. */
17772 gcc_assert (errorcount);
17774 /* Throw away the broken statement tree and extra binding
17775 levels. */
17776 DECL_SAVED_TREE (fndecl) = alloc_stmt_list ();
17778 while (current_binding_level->kind != sk_function_parms)
17780 if (current_binding_level->kind == sk_class)
17781 pop_nested_class ();
17782 else
17783 poplevel (0, 0, 0);
17786 poplevel (1, 0, 1);
17788 /* Statements should always be full-expressions at the outermost set
17789 of curly braces for a function. */
17790 gcc_assert (stmts_are_full_exprs_p ());
17792 /* If there are no return statements in a function with auto return type,
17793 the return type is void. But if the declared type is something like
17794 auto*, this is an error. */
17795 if (!processing_template_decl && FNDECL_USED_AUTO (fndecl)
17796 && TREE_TYPE (fntype) == DECL_SAVED_AUTO_RETURN_TYPE (fndecl))
17798 if (is_auto (DECL_SAVED_AUTO_RETURN_TYPE (fndecl))
17799 && !current_function_returns_value
17800 && !current_function_returns_null)
17802 /* We haven't applied return type deduction because we haven't
17803 seen any return statements. Do that now. */
17804 tree node = type_uses_auto (DECL_SAVED_AUTO_RETURN_TYPE (fndecl));
17805 do_auto_deduction (DECL_SAVED_AUTO_RETURN_TYPE (fndecl),
17806 void_node, node, tf_warning_or_error,
17807 adc_return_type);
17809 apply_deduced_return_type (fndecl, void_type_node);
17810 fntype = TREE_TYPE (fndecl);
17812 else if (!current_function_returns_value
17813 && !current_function_returns_null)
17815 error ("no return statements in function returning %qT",
17816 DECL_SAVED_AUTO_RETURN_TYPE (fndecl));
17817 inform (input_location, "only plain %<auto%> return type can be "
17818 "deduced to %<void%>");
17822 /* Remember that we were in class scope. */
17823 if (current_class_name)
17824 ctype = current_class_type;
17826 if (DECL_DELETED_FN (fndecl))
17828 DECL_INITIAL (fndecl) = error_mark_node;
17829 DECL_SAVED_TREE (fndecl) = NULL_TREE;
17830 goto cleanup;
17833 // If this is a concept, check that the definition is reasonable.
17834 if (DECL_DECLARED_CONCEPT_P (fndecl))
17835 check_function_concept (fndecl);
17837 if (flag_openmp)
17838 if (tree attr = lookup_attribute ("omp declare variant base",
17839 DECL_ATTRIBUTES (fndecl)))
17840 omp_declare_variant_finalize (fndecl, attr);
17842 /* Complain if there's just no return statement. */
17843 if ((warn_return_type
17844 || (cxx_dialect >= cxx14
17845 && DECL_DECLARED_CONSTEXPR_P (fndecl)))
17846 && !VOID_TYPE_P (TREE_TYPE (fntype))
17847 && !dependent_type_p (TREE_TYPE (fntype))
17848 && !current_function_returns_value && !current_function_returns_null
17849 /* Don't complain if we abort or throw. */
17850 && !current_function_returns_abnormally
17851 /* Don't complain if there's an infinite loop. */
17852 && !current_function_infinite_loop
17853 /* Don't complain if we are declared noreturn. */
17854 && !TREE_THIS_VOLATILE (fndecl)
17855 && !DECL_NAME (DECL_RESULT (fndecl))
17856 && !warning_suppressed_p (fndecl, OPT_Wreturn_type)
17857 /* Structor return values (if any) are set by the compiler. */
17858 && !DECL_CONSTRUCTOR_P (fndecl)
17859 && !DECL_DESTRUCTOR_P (fndecl)
17860 && targetm.warn_func_return (fndecl))
17862 gcc_rich_location richloc (input_location);
17863 /* Potentially add a "return *this;" fix-it hint for
17864 assignment operators. */
17865 if (IDENTIFIER_ASSIGN_OP_P (DECL_NAME (fndecl)))
17867 tree valtype = TREE_TYPE (DECL_RESULT (fndecl));
17868 if (TREE_CODE (valtype) == REFERENCE_TYPE
17869 && current_class_ref
17870 && same_type_ignoring_top_level_qualifiers_p
17871 (TREE_TYPE (valtype), TREE_TYPE (current_class_ref))
17872 && global_dc->option_enabled (OPT_Wreturn_type,
17873 global_dc->lang_mask,
17874 global_dc->option_state))
17875 add_return_star_this_fixit (&richloc, fndecl);
17877 if (cxx_dialect >= cxx14
17878 && DECL_DECLARED_CONSTEXPR_P (fndecl))
17879 error_at (&richloc, "no return statement in %<constexpr%> function "
17880 "returning non-void");
17881 else if (warning_at (&richloc, OPT_Wreturn_type,
17882 "no return statement in function returning "
17883 "non-void"))
17884 suppress_warning (fndecl, OPT_Wreturn_type);
17887 /* Lambda closure members are implicitly constexpr if possible. */
17888 if (cxx_dialect >= cxx17
17889 && LAMBDA_TYPE_P (CP_DECL_CONTEXT (fndecl)))
17890 DECL_DECLARED_CONSTEXPR_P (fndecl)
17891 = ((processing_template_decl
17892 || is_valid_constexpr_fn (fndecl, /*complain*/false))
17893 && potential_constant_expression (DECL_SAVED_TREE (fndecl)));
17895 /* Save constexpr function body before it gets munged by
17896 the NRV transformation. */
17897 maybe_save_constexpr_fundef (fndecl);
17899 /* Invoke the pre-genericize plugin before we start munging things. */
17900 if (!processing_template_decl)
17901 invoke_plugin_callbacks (PLUGIN_PRE_GENERICIZE, fndecl);
17903 /* Perform delayed folding before NRV transformation. */
17904 if (!processing_template_decl
17905 && !DECL_IMMEDIATE_FUNCTION_P (fndecl)
17906 && !DECL_OMP_DECLARE_REDUCTION_P (fndecl))
17907 cp_fold_function (fndecl);
17909 /* Set up the named return value optimization, if we can. Candidate
17910 variables are selected in check_return_expr. */
17911 if (current_function_return_value)
17913 tree r = current_function_return_value;
17914 tree outer;
17916 if (r != error_mark_node
17917 /* This is only worth doing for fns that return in memory--and
17918 simpler, since we don't have to worry about promoted modes. */
17919 && aggregate_value_p (TREE_TYPE (TREE_TYPE (fndecl)), fndecl)
17920 /* Only allow this for variables declared in the outer scope of
17921 the function so we know that their lifetime always ends with a
17922 return; see g++.dg/opt/nrv6.C. We could be more flexible if
17923 we were to do this optimization in tree-ssa. */
17924 && (outer = outer_curly_brace_block (fndecl))
17925 && chain_member (r, BLOCK_VARS (outer)))
17926 finalize_nrv (&DECL_SAVED_TREE (fndecl), r, DECL_RESULT (fndecl));
17928 current_function_return_value = NULL_TREE;
17931 /* Must mark the RESULT_DECL as being in this function. */
17932 DECL_CONTEXT (DECL_RESULT (fndecl)) = fndecl;
17934 /* Set the BLOCK_SUPERCONTEXT of the outermost function scope to point
17935 to the FUNCTION_DECL node itself. */
17936 BLOCK_SUPERCONTEXT (DECL_INITIAL (fndecl)) = fndecl;
17938 /* Store the end of the function, so that we get good line number
17939 info for the epilogue. */
17940 cfun->function_end_locus = input_location;
17942 /* Complain about parameters that are only set, but never otherwise used. */
17943 if (warn_unused_but_set_parameter
17944 && !processing_template_decl
17945 && errorcount == unused_but_set_errorcount
17946 && !DECL_CLONED_FUNCTION_P (fndecl))
17948 tree decl;
17950 for (decl = DECL_ARGUMENTS (fndecl);
17951 decl;
17952 decl = DECL_CHAIN (decl))
17953 if (TREE_USED (decl)
17954 && TREE_CODE (decl) == PARM_DECL
17955 && !DECL_READ_P (decl)
17956 && DECL_NAME (decl)
17957 && !DECL_ARTIFICIAL (decl)
17958 && !warning_suppressed_p (decl,OPT_Wunused_but_set_parameter)
17959 && !DECL_IN_SYSTEM_HEADER (decl)
17960 && TREE_TYPE (decl) != error_mark_node
17961 && !TYPE_REF_P (TREE_TYPE (decl))
17962 && (!CLASS_TYPE_P (TREE_TYPE (decl))
17963 || !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (decl))))
17964 warning_at (DECL_SOURCE_LOCATION (decl),
17965 OPT_Wunused_but_set_parameter,
17966 "parameter %qD set but not used", decl);
17967 unused_but_set_errorcount = errorcount;
17970 /* Complain about locally defined typedefs that are not used in this
17971 function. */
17972 maybe_warn_unused_local_typedefs ();
17974 /* Possibly warn about unused parameters. */
17975 if (warn_unused_parameter
17976 && !processing_template_decl
17977 && !DECL_CLONED_FUNCTION_P (fndecl))
17978 do_warn_unused_parameter (fndecl);
17980 /* Genericize before inlining. */
17981 if (!processing_template_decl
17982 && !DECL_IMMEDIATE_FUNCTION_P (fndecl)
17983 && !DECL_OMP_DECLARE_REDUCTION_P (fndecl))
17984 cp_genericize (fndecl);
17986 /* Emit the resumer and destroyer functions now, providing that we have
17987 not encountered some fatal error. */
17988 if (coro_emit_helpers)
17990 emit_coro_helper (resumer);
17991 emit_coro_helper (destroyer);
17994 cleanup:
17995 /* We're leaving the context of this function, so zap cfun. It's still in
17996 DECL_STRUCT_FUNCTION, and we'll restore it in tree_rest_of_compilation. */
17997 set_cfun (NULL);
17998 current_function_decl = NULL;
18000 /* If this is an in-class inline definition, we may have to pop the
18001 bindings for the template parameters that we added in
18002 maybe_begin_member_template_processing when start_function was
18003 called. */
18004 if (inline_p)
18005 maybe_end_member_template_processing ();
18007 /* Leave the scope of the class. */
18008 if (ctype)
18009 pop_nested_class ();
18011 --function_depth;
18013 /* Clean up. */
18014 current_function_decl = NULL_TREE;
18016 invoke_plugin_callbacks (PLUGIN_FINISH_PARSE_FUNCTION, fndecl);
18017 return fndecl;
18020 /* Create the FUNCTION_DECL for a function definition.
18021 DECLSPECS and DECLARATOR are the parts of the declaration;
18022 they describe the return type and the name of the function,
18023 but twisted together in a fashion that parallels the syntax of C.
18025 This function creates a binding context for the function body
18026 as well as setting up the FUNCTION_DECL in current_function_decl.
18028 Returns a FUNCTION_DECL on success.
18030 If the DECLARATOR is not suitable for a function (it defines a datum
18031 instead), we return 0, which tells yyparse to report a parse error.
18033 May return void_type_node indicating that this method is actually
18034 a friend. See grokfield for more details.
18036 Came here with a `.pushlevel' .
18038 DO NOT MAKE ANY CHANGES TO THIS CODE WITHOUT MAKING CORRESPONDING
18039 CHANGES TO CODE IN `grokfield'. */
18041 tree
18042 grokmethod (cp_decl_specifier_seq *declspecs,
18043 const cp_declarator *declarator, tree attrlist)
18045 tree fndecl = grokdeclarator (declarator, declspecs, MEMFUNCDEF, 0,
18046 &attrlist);
18048 if (fndecl == error_mark_node)
18049 return error_mark_node;
18051 if (attrlist)
18052 cplus_decl_attributes (&fndecl, attrlist, 0);
18054 /* Pass friends other than inline friend functions back. */
18055 if (fndecl == void_type_node)
18056 return fndecl;
18058 if (DECL_IN_AGGR_P (fndecl))
18060 if (DECL_CLASS_SCOPE_P (fndecl))
18061 error ("%qD is already defined in class %qT", fndecl,
18062 DECL_CONTEXT (fndecl));
18063 return error_mark_node;
18066 check_template_shadow (fndecl);
18068 /* p1779 ABI-Isolation makes inline not a default for in-class
18069 definitions in named module purview. If the user explicitly
18070 made it inline, grokdeclarator will already have done the right
18071 things. */
18072 if ((!named_module_purview_p ()
18073 || flag_module_implicit_inline
18074 /* Lambda's operator function remains inline. */
18075 || LAMBDA_TYPE_P (DECL_CONTEXT (fndecl)))
18076 /* If the user explicitly asked for this to be inline, we don't
18077 need to do more, but more importantly we want to warn if we
18078 can't inline it. */
18079 && !DECL_DECLARED_INLINE_P (fndecl))
18081 if (TREE_PUBLIC (fndecl))
18082 DECL_COMDAT (fndecl) = 1;
18083 DECL_DECLARED_INLINE_P (fndecl) = 1;
18084 /* It's ok if we can't inline this. */
18085 DECL_NO_INLINE_WARNING_P (fndecl) = 1;
18088 /* We process method specializations in finish_struct_1. */
18089 if (processing_template_decl && !DECL_TEMPLATE_SPECIALIZATION (fndecl))
18091 /* Avoid calling decl_spec_seq... until we have to. */
18092 bool friendp = decl_spec_seq_has_spec_p (declspecs, ds_friend);
18093 fndecl = push_template_decl (fndecl, friendp);
18094 if (fndecl == error_mark_node)
18095 return fndecl;
18098 if (DECL_CHAIN (fndecl) && !decl_spec_seq_has_spec_p (declspecs, ds_friend))
18100 fndecl = copy_node (fndecl);
18101 TREE_CHAIN (fndecl) = NULL_TREE;
18104 cp_finish_decl (fndecl, NULL_TREE, false, NULL_TREE, 0);
18106 DECL_IN_AGGR_P (fndecl) = 1;
18107 return fndecl;
18111 /* VAR is a VAR_DECL. If its type is incomplete, remember VAR so that
18112 we can lay it out later, when and if its type becomes complete.
18114 Also handle constexpr variables where the initializer involves
18115 an unlowered PTRMEM_CST because the class isn't complete yet. */
18117 void
18118 maybe_register_incomplete_var (tree var)
18120 gcc_assert (VAR_P (var));
18122 /* Keep track of variables with incomplete types. */
18123 if (!processing_template_decl && TREE_TYPE (var) != error_mark_node
18124 && DECL_EXTERNAL (var))
18126 tree inner_type = TREE_TYPE (var);
18128 while (TREE_CODE (inner_type) == ARRAY_TYPE)
18129 inner_type = TREE_TYPE (inner_type);
18130 inner_type = TYPE_MAIN_VARIANT (inner_type);
18132 if ((!COMPLETE_TYPE_P (inner_type) && CLASS_TYPE_P (inner_type))
18133 /* RTTI TD entries are created while defining the type_info. */
18134 || (TYPE_LANG_SPECIFIC (inner_type)
18135 && TYPE_BEING_DEFINED (inner_type)))
18137 incomplete_var iv = {var, inner_type};
18138 vec_safe_push (incomplete_vars, iv);
18140 else if (!(DECL_LANG_SPECIFIC (var) && DECL_TEMPLATE_INFO (var))
18141 && decl_constant_var_p (var)
18142 && (TYPE_PTRMEM_P (inner_type) || CLASS_TYPE_P (inner_type)))
18144 /* When the outermost open class is complete we can resolve any
18145 pointers-to-members. */
18146 tree context = outermost_open_class ();
18147 incomplete_var iv = {var, context};
18148 vec_safe_push (incomplete_vars, iv);
18153 /* Called when a class type (given by TYPE) is defined. If there are
18154 any existing VAR_DECLs whose type has been completed by this
18155 declaration, update them now. */
18157 void
18158 complete_vars (tree type)
18160 unsigned ix;
18161 incomplete_var *iv;
18163 for (ix = 0; vec_safe_iterate (incomplete_vars, ix, &iv); )
18165 if (same_type_p (type, iv->incomplete_type))
18167 tree var = iv->decl;
18168 tree type = TREE_TYPE (var);
18170 if (type != error_mark_node
18171 && (TYPE_MAIN_VARIANT (strip_array_types (type))
18172 == iv->incomplete_type))
18174 /* Complete the type of the variable. */
18175 complete_type (type);
18176 cp_apply_type_quals_to_decl (cp_type_quals (type), var);
18177 if (COMPLETE_TYPE_P (type))
18178 layout_var_decl (var);
18181 /* Remove this entry from the list. */
18182 incomplete_vars->unordered_remove (ix);
18184 else
18185 ix++;
18189 /* If DECL is of a type which needs a cleanup, build and return an
18190 expression to perform that cleanup here. Return NULL_TREE if no
18191 cleanup need be done. DECL can also be a _REF when called from
18192 split_nonconstant_init_1. */
18194 tree
18195 cxx_maybe_build_cleanup (tree decl, tsubst_flags_t complain)
18197 tree type;
18198 tree attr;
18199 tree cleanup;
18201 /* Assume no cleanup is required. */
18202 cleanup = NULL_TREE;
18204 if (error_operand_p (decl))
18205 return cleanup;
18207 /* Handle "__attribute__((cleanup))". We run the cleanup function
18208 before the destructor since the destructor is what actually
18209 terminates the lifetime of the object. */
18210 if (DECL_P (decl))
18211 attr = lookup_attribute ("cleanup", DECL_ATTRIBUTES (decl));
18212 else
18213 attr = NULL_TREE;
18214 if (attr)
18216 tree id;
18217 tree fn;
18218 tree arg;
18220 /* Get the name specified by the user for the cleanup function. */
18221 id = TREE_VALUE (TREE_VALUE (attr));
18222 /* Look up the name to find the cleanup function to call. It is
18223 important to use lookup_name here because that is what is
18224 used in c-common.cc:handle_cleanup_attribute when performing
18225 initial checks on the attribute. Note that those checks
18226 include ensuring that the function found is not an overloaded
18227 function, or an object with an overloaded call operator,
18228 etc.; we can rely on the fact that the function found is an
18229 ordinary FUNCTION_DECL. */
18230 fn = lookup_name (id);
18231 arg = build_address (decl);
18232 if (!mark_used (decl, complain) && !(complain & tf_error))
18233 return error_mark_node;
18234 cleanup = cp_build_function_call_nary (fn, complain, arg, NULL_TREE);
18235 if (cleanup == error_mark_node)
18236 return error_mark_node;
18238 /* Handle ordinary C++ destructors. */
18239 type = TREE_TYPE (decl);
18240 if (type_build_dtor_call (type))
18242 int flags = LOOKUP_NORMAL|LOOKUP_NONVIRTUAL|LOOKUP_DESTRUCTOR;
18243 tree addr;
18244 tree call;
18246 if (TREE_CODE (type) == ARRAY_TYPE)
18247 addr = decl;
18248 else
18249 addr = build_address (decl);
18251 call = build_delete (input_location, TREE_TYPE (addr), addr,
18252 sfk_complete_destructor, flags, 0, complain);
18253 if (call == error_mark_node)
18254 cleanup = error_mark_node;
18255 else if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
18256 /* Discard the call. */;
18257 else if (decl_maybe_constant_destruction (decl, type)
18258 && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
18259 cxx_constant_dtor (call, decl);
18260 else if (cleanup)
18261 cleanup = cp_build_compound_expr (cleanup, call, complain);
18262 else
18263 cleanup = call;
18266 /* build_delete sets the location of the destructor call to the
18267 current location, even though the destructor is going to be
18268 called later, at the end of the current scope. This can lead to
18269 a "jumpy" behavior for users of debuggers when they step around
18270 the end of the block. So let's unset the location of the
18271 destructor call instead. */
18272 protected_set_expr_location (cleanup, UNKNOWN_LOCATION);
18273 if (cleanup && CONVERT_EXPR_P (cleanup))
18274 protected_set_expr_location (TREE_OPERAND (cleanup, 0), UNKNOWN_LOCATION);
18276 if (cleanup
18277 && DECL_P (decl)
18278 && !lookup_attribute ("warn_unused", TYPE_ATTRIBUTES (TREE_TYPE (decl)))
18279 /* Treat objects with destructors as used; the destructor may do
18280 something substantive. */
18281 && !mark_used (decl, complain) && !(complain & tf_error))
18282 return error_mark_node;
18284 if (cleanup && cfun && !processing_template_decl
18285 && !expr_noexcept_p (cleanup, tf_none))
18286 cp_function_chain->throwing_cleanup = true;
18288 return cleanup;
18292 /* Return the FUNCTION_TYPE that corresponds to MEMFNTYPE, which can be a
18293 FUNCTION_DECL, METHOD_TYPE, FUNCTION_TYPE, pointer or reference to
18294 METHOD_TYPE or FUNCTION_TYPE, or pointer to member function. */
18296 tree
18297 static_fn_type (tree memfntype)
18299 tree fntype;
18300 tree args;
18302 if (TYPE_PTRMEMFUNC_P (memfntype))
18303 memfntype = TYPE_PTRMEMFUNC_FN_TYPE (memfntype);
18304 if (INDIRECT_TYPE_P (memfntype)
18305 || TREE_CODE (memfntype) == FUNCTION_DECL)
18306 memfntype = TREE_TYPE (memfntype);
18307 if (TREE_CODE (memfntype) == FUNCTION_TYPE)
18308 return memfntype;
18309 gcc_assert (TREE_CODE (memfntype) == METHOD_TYPE);
18310 args = TYPE_ARG_TYPES (memfntype);
18311 fntype = build_function_type (TREE_TYPE (memfntype), TREE_CHAIN (args));
18312 fntype = apply_memfn_quals (fntype, type_memfn_quals (memfntype));
18313 fntype = (cp_build_type_attribute_variant
18314 (fntype, TYPE_ATTRIBUTES (memfntype)));
18315 fntype = cxx_copy_lang_qualifiers (fntype, memfntype);
18316 return fntype;
18319 /* DECL was originally constructed as a non-static member function,
18320 but turned out to be static. Update it accordingly. */
18322 void
18323 revert_static_member_fn (tree decl)
18325 tree stype = static_fn_type (decl);
18326 cp_cv_quals quals = type_memfn_quals (stype);
18327 cp_ref_qualifier rqual = type_memfn_rqual (stype);
18329 if (quals != TYPE_UNQUALIFIED || rqual != REF_QUAL_NONE)
18330 stype = apply_memfn_quals (stype, TYPE_UNQUALIFIED, REF_QUAL_NONE);
18332 TREE_TYPE (decl) = stype;
18334 if (DECL_ARGUMENTS (decl))
18335 DECL_ARGUMENTS (decl) = DECL_CHAIN (DECL_ARGUMENTS (decl));
18336 DECL_STATIC_FUNCTION_P (decl) = 1;
18339 /* Return which tree structure is used by T, or TS_CP_GENERIC if T is
18340 one of the language-independent trees. */
18342 enum cp_tree_node_structure_enum
18343 cp_tree_node_structure (union lang_tree_node * t)
18345 switch (TREE_CODE (&t->generic))
18347 case ARGUMENT_PACK_SELECT: return TS_CP_ARGUMENT_PACK_SELECT;
18348 case BASELINK: return TS_CP_BASELINK;
18349 case CONSTRAINT_INFO: return TS_CP_CONSTRAINT_INFO;
18350 case DEFERRED_NOEXCEPT: return TS_CP_DEFERRED_NOEXCEPT;
18351 case DEFERRED_PARSE: return TS_CP_DEFERRED_PARSE;
18352 case IDENTIFIER_NODE: return TS_CP_IDENTIFIER;
18353 case LAMBDA_EXPR: return TS_CP_LAMBDA_EXPR;
18354 case BINDING_VECTOR: return TS_CP_BINDING_VECTOR;
18355 case OVERLOAD: return TS_CP_OVERLOAD;
18356 case PTRMEM_CST: return TS_CP_PTRMEM;
18357 case STATIC_ASSERT: return TS_CP_STATIC_ASSERT;
18358 case TEMPLATE_DECL: return TS_CP_TEMPLATE_DECL;
18359 case TEMPLATE_INFO: return TS_CP_TEMPLATE_INFO;
18360 case TEMPLATE_PARM_INDEX: return TS_CP_TPI;
18361 case TRAIT_EXPR: return TS_CP_TRAIT_EXPR;
18362 case USERDEF_LITERAL: return TS_CP_USERDEF_LITERAL;
18363 default: return TS_CP_GENERIC;
18367 /* Build the void_list_node (void_type_node having been created). */
18368 tree
18369 build_void_list_node (void)
18371 tree t = build_tree_list (NULL_TREE, void_type_node);
18372 return t;
18375 bool
18376 cp_missing_noreturn_ok_p (tree decl)
18378 /* A missing noreturn is ok for the `main' function. */
18379 return DECL_MAIN_P (decl);
18382 /* Return the decl used to identify the COMDAT group into which DECL should
18383 be placed. */
18385 tree
18386 cxx_comdat_group (tree decl)
18388 /* Virtual tables, construction virtual tables, and virtual table
18389 tables all go in a single COMDAT group, named after the primary
18390 virtual table. */
18391 if (VAR_P (decl) && DECL_VTABLE_OR_VTT_P (decl))
18392 decl = CLASSTYPE_VTABLES (DECL_CONTEXT (decl));
18393 /* For all other DECLs, the COMDAT group is the mangled name of the
18394 declaration itself. */
18395 else
18397 while (DECL_THUNK_P (decl))
18399 /* If TARGET_USE_LOCAL_THUNK_ALIAS_P, use_thunk puts the thunk
18400 into the same section as the target function. In that case
18401 we must return target's name. */
18402 tree target = THUNK_TARGET (decl);
18403 if (TARGET_USE_LOCAL_THUNK_ALIAS_P (target)
18404 && DECL_SECTION_NAME (target) != NULL
18405 && DECL_ONE_ONLY (target))
18406 decl = target;
18407 else
18408 break;
18412 return decl;
18415 /* Returns the return type for FN as written by the user, which may include
18416 a placeholder for a deduced return type. */
18418 tree
18419 fndecl_declared_return_type (tree fn)
18421 fn = STRIP_TEMPLATE (fn);
18422 if (FNDECL_USED_AUTO (fn))
18423 return DECL_SAVED_AUTO_RETURN_TYPE (fn);
18425 return TREE_TYPE (TREE_TYPE (fn));
18428 /* Returns true iff DECL is a variable or function declared with an auto type
18429 that has not yet been deduced to a real type. */
18431 bool
18432 undeduced_auto_decl (tree decl)
18434 if (cxx_dialect < cxx11)
18435 return false;
18436 STRIP_ANY_LOCATION_WRAPPER (decl);
18437 return ((VAR_OR_FUNCTION_DECL_P (decl)
18438 || TREE_CODE (decl) == TEMPLATE_DECL)
18439 && type_uses_auto (TREE_TYPE (decl)));
18442 /* Complain if DECL has an undeduced return type. */
18444 bool
18445 require_deduced_type (tree decl, tsubst_flags_t complain)
18447 if (undeduced_auto_decl (decl))
18449 if (warning_suppressed_p (decl) && seen_error ())
18450 /* We probably already complained about deduction failure. */;
18451 else if (complain & tf_error)
18452 error ("use of %qD before deduction of %<auto%>", decl);
18453 note_failed_type_completion_for_satisfaction (decl);
18454 return false;
18456 return true;
18459 /* Create a representation of the explicit-specifier with
18460 constant-expression of EXPR. COMPLAIN is as for tsubst. */
18462 tree
18463 build_explicit_specifier (tree expr, tsubst_flags_t complain)
18465 if (check_for_bare_parameter_packs (expr))
18466 return error_mark_node;
18468 if (instantiation_dependent_expression_p (expr))
18469 /* Wait for instantiation, tsubst_function_decl will handle it. */
18470 return expr;
18472 expr = build_converted_constant_bool_expr (expr, complain);
18473 expr = instantiate_non_dependent_expr_sfinae (expr, complain);
18474 expr = cxx_constant_value (expr);
18475 return expr;
18478 #include "gt-cp-decl.h"