f333a36b0e1edfca59e42dbbe7943ad9ef44dca3
[platform/upstream/gcc.git] / gcc / cp / decl.c
1 /* Process declarations and variables for -*- C++ -*- compiler.
2    Copyright (C) 1988-2020 Free Software Foundation, Inc.
3    Contributed by Michael Tiemann (tiemann@cygnus.com)
4
5 This file is part of GCC.
6
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.
11
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.
16
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/>.  */
20
21
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.  */
25
26 /* ??? not all decl nodes are given the most useful possible
27    line numbers.  For example, the CONST_DECLs for enum values.  */
28
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 "omp-general.h"
57
58 /* Possible cases of bad specifiers type used by bad_specifiers. */
59 enum bad_spec_place {
60   BSP_VAR,    /* variable */
61   BSP_PARM,   /* parameter */
62   BSP_TYPE,   /* type */
63   BSP_FIELD   /* field */
64 };
65
66 static const char *redeclaration_error_message (tree, tree);
67
68 static int decl_jump_unsafe (tree);
69 static void require_complete_types_for_parms (tree);
70 static tree grok_reference_init (tree, tree, tree, int);
71 static tree grokvardecl (tree, tree, tree, const cp_decl_specifier_seq *,
72                          int, int, int, bool, int, tree, location_t);
73 static void check_static_variable_definition (tree, tree);
74 static void record_unknown_type (tree, const char *);
75 static int member_function_or_else (tree, tree, enum overload_flags);
76 static tree local_variable_p_walkfn (tree *, int *, void *);
77 static const char *tag_name (enum tag_types);
78 static tree lookup_and_check_tag (enum tag_types, tree, TAG_how, bool);
79 static void maybe_deduce_size_from_array_init (tree, tree);
80 static void layout_var_decl (tree);
81 static tree check_initializer (tree, tree, int, vec<tree, va_gc> **);
82 static void make_rtl_for_nonlocal_decl (tree, tree, const char *);
83 static void copy_type_enum (tree , tree);
84 static void check_function_type (tree, tree);
85 static void finish_constructor_body (void);
86 static void begin_destructor_body (void);
87 static void finish_destructor_body (void);
88 static void record_key_method_defined (tree);
89 static tree create_array_type_for_decl (tree, tree, tree, location_t);
90 static tree get_atexit_node (void);
91 static tree get_dso_handle_node (void);
92 static tree start_cleanup_fn (void);
93 static void end_cleanup_fn (void);
94 static tree cp_make_fname_decl (location_t, tree, int);
95 static void initialize_predefined_identifiers (void);
96 static tree check_special_function_return_type
97        (special_function_kind, tree, tree, int, const location_t*);
98 static tree push_cp_library_fn (enum tree_code, tree, int);
99 static tree build_cp_library_fn (tree, enum tree_code, tree, int);
100 static void store_parm_decls (tree);
101 static void initialize_local_var (tree, tree);
102 static void expand_static_init (tree, tree);
103 static location_t smallest_type_location (const cp_decl_specifier_seq*);
104
105 /* The following symbols are subsumed in the cp_global_trees array, and
106    listed here individually for documentation purposes.
107
108    C++ extensions
109         tree wchar_decl_node;
110
111         tree vtable_entry_type;
112         tree delta_type_node;
113         tree __t_desc_type_node;
114
115         tree class_type_node;
116         tree unknown_type_node;
117
118    Array type `vtable_entry_type[]'
119
120         tree vtbl_type_node;
121         tree vtbl_ptr_type_node;
122
123    Namespaces,
124
125         tree std_node;
126         tree abi_node;
127
128    A FUNCTION_DECL which can call `abort'.  Not necessarily the
129    one that the user will declare, but sufficient to be called
130    by routines that want to abort the program.
131
132         tree abort_fndecl;
133
134    Used by RTTI
135         tree type_info_type_node, tinfo_decl_id, tinfo_decl_type;
136         tree tinfo_var_id;  */
137
138 tree cp_global_trees[CPTI_MAX];
139
140 /* A list of objects which have constructors or destructors
141    which reside in the global scope.  The decl is stored in
142    the TREE_VALUE slot and the initializer is stored
143    in the TREE_PURPOSE slot.  */
144 tree static_aggregates;
145
146 /* Like static_aggregates, but for thread_local variables.  */
147 tree tls_aggregates;
148
149 /* -- end of C++ */
150
151 /* A node for the integer constant 2.  */
152
153 tree integer_two_node;
154
155 /* vector of static decls.  */
156 vec<tree, va_gc> *static_decls;
157
158 /* vector of keyed classes.  */
159 vec<tree, va_gc> *keyed_classes;
160
161 /* Used only for jumps to as-yet undefined labels, since jumps to
162    defined labels can have their validity checked immediately.  */
163
164 struct GTY((chain_next ("%h.next"))) named_label_use_entry {
165   struct named_label_use_entry *next;
166   /* The binding level to which this entry is *currently* attached.
167      This is initially the binding level in which the goto appeared,
168      but is modified as scopes are closed.  */
169   cp_binding_level *binding_level;
170   /* The head of the names list that was current when the goto appeared,
171      or the inner scope popped.  These are the decls that will *not* be
172      skipped when jumping to the label.  */
173   tree names_in_scope;
174   /* The location of the goto, for error reporting.  */
175   location_t o_goto_locus;
176   /* True if an OpenMP structured block scope has been closed since
177      the goto appeared.  This means that the branch from the label will
178      illegally exit an OpenMP scope.  */
179   bool in_omp_scope;
180 };
181
182 /* A list of all LABEL_DECLs in the function that have names.  Here so
183    we can clear out their names' definitions at the end of the
184    function, and so we can check the validity of jumps to these labels.  */
185
186 struct GTY((for_user)) named_label_entry {
187
188   tree name;  /* Name of decl. */
189
190   tree label_decl; /* LABEL_DECL, unless deleted local label. */
191
192   named_label_entry *outer; /* Outer shadowed chain.  */
193
194   /* The binding level to which the label is *currently* attached.
195      This is initially set to the binding level in which the label
196      is defined, but is modified as scopes are closed.  */
197   cp_binding_level *binding_level;
198
199   /* The head of the names list that was current when the label was
200      defined, or the inner scope popped.  These are the decls that will
201      be skipped when jumping to the label.  */
202   tree names_in_scope;
203
204   /* A vector of all decls from all binding levels that would be
205      crossed by a backward branch to the label.  */
206   vec<tree, va_gc> *bad_decls;
207
208   /* A list of uses of the label, before the label is defined.  */
209   named_label_use_entry *uses;
210
211   /* The following bits are set after the label is defined, and are
212      updated as scopes are popped.  They indicate that a jump to the
213      label will illegally enter a scope of the given flavor.  */
214   bool in_try_scope;
215   bool in_catch_scope;
216   bool in_omp_scope;
217   bool in_transaction_scope;
218   bool in_constexpr_if;
219 };
220
221 #define named_labels cp_function_chain->x_named_labels
222 \f
223 /* The number of function bodies which we are currently processing.
224    (Zero if we are at namespace scope, one inside the body of a
225    function, two inside the body of a function in a local class, etc.)  */
226 int function_depth;
227
228 /* Whether the exception-specifier is part of a function type (i.e. C++17).  */
229 bool flag_noexcept_type;
230
231 /* States indicating how grokdeclarator() should handle declspecs marked
232    with __attribute__((deprecated)).  An object declared as
233    __attribute__((deprecated)) suppresses warnings of uses of other
234    deprecated items.  */
235 enum deprecated_states deprecated_state = DEPRECATED_NORMAL;
236
237 \f
238 /* A list of VAR_DECLs whose type was incomplete at the time the
239    variable was declared.  */
240
241 struct GTY(()) incomplete_var {
242   tree decl;
243   tree incomplete_type;
244 };
245
246
247 static GTY(()) vec<incomplete_var, va_gc> *incomplete_vars;
248 \f
249 /* Returns the kind of template specialization we are currently
250    processing, given that it's declaration contained N_CLASS_SCOPES
251    explicit scope qualifications.  */
252
253 tmpl_spec_kind
254 current_tmpl_spec_kind (int n_class_scopes)
255 {
256   int n_template_parm_scopes = 0;
257   int seen_specialization_p = 0;
258   int innermost_specialization_p = 0;
259   cp_binding_level *b;
260
261   /* Scan through the template parameter scopes.  */
262   for (b = current_binding_level;
263        b->kind == sk_template_parms;
264        b = b->level_chain)
265     {
266       /* If we see a specialization scope inside a parameter scope,
267          then something is wrong.  That corresponds to a declaration
268          like:
269
270             template <class T> template <> ...
271
272          which is always invalid since [temp.expl.spec] forbids the
273          specialization of a class member template if the enclosing
274          class templates are not explicitly specialized as well.  */
275       if (b->explicit_spec_p)
276         {
277           if (n_template_parm_scopes == 0)
278             innermost_specialization_p = 1;
279           else
280             seen_specialization_p = 1;
281         }
282       else if (seen_specialization_p == 1)
283         return tsk_invalid_member_spec;
284
285       ++n_template_parm_scopes;
286     }
287
288   /* Handle explicit instantiations.  */
289   if (processing_explicit_instantiation)
290     {
291       if (n_template_parm_scopes != 0)
292         /* We've seen a template parameter list during an explicit
293            instantiation.  For example:
294
295              template <class T> template void f(int);
296
297            This is erroneous.  */
298         return tsk_invalid_expl_inst;
299       else
300         return tsk_expl_inst;
301     }
302
303   if (n_template_parm_scopes < n_class_scopes)
304     /* We've not seen enough template headers to match all the
305        specialized classes present.  For example:
306
307          template <class T> void R<T>::S<T>::f(int);
308
309        This is invalid; there needs to be one set of template
310        parameters for each class.  */
311     return tsk_insufficient_parms;
312   else if (n_template_parm_scopes == n_class_scopes)
313     /* We're processing a non-template declaration (even though it may
314        be a member of a template class.)  For example:
315
316          template <class T> void S<T>::f(int);
317
318        The `class T' matches the `S<T>', leaving no template headers
319        corresponding to the `f'.  */
320     return tsk_none;
321   else if (n_template_parm_scopes > n_class_scopes + 1)
322     /* We've got too many template headers.  For example:
323
324          template <> template <class T> void f (T);
325
326        There need to be more enclosing classes.  */
327     return tsk_excessive_parms;
328   else
329     /* This must be a template.  It's of the form:
330
331          template <class T> template <class U> void S<T>::f(U);
332
333        This is a specialization if the innermost level was a
334        specialization; otherwise it's just a definition of the
335        template.  */
336     return innermost_specialization_p ? tsk_expl_spec : tsk_template;
337 }
338
339 /* Exit the current scope.  */
340
341 void
342 finish_scope (void)
343 {
344   poplevel (0, 0, 0);
345 }
346
347 /* When a label goes out of scope, check to see if that label was used
348    in a valid manner, and issue any appropriate warnings or errors.  */
349
350 static void
351 check_label_used (tree label)
352 {
353   if (!processing_template_decl)
354     {
355       if (DECL_INITIAL (label) == NULL_TREE)
356         {
357           location_t location;
358
359           error ("label %q+D used but not defined", label);
360           location = input_location;
361             /* FIXME want (LOCATION_FILE (input_location), (line)0) */
362           /* Avoid crashing later.  */
363           define_label (location, DECL_NAME (label));
364         }
365       else 
366         warn_for_unused_label (label);
367     }
368 }
369
370 /* Helper function to sort named label entries in a vector by DECL_UID.  */
371
372 static int
373 sort_labels (const void *a, const void *b)
374 {
375   tree label1 = *(tree const *) a;
376   tree label2 = *(tree const *) b;
377
378   /* DECL_UIDs can never be equal.  */
379   return DECL_UID (label1) > DECL_UID (label2) ? -1 : +1;
380 }
381
382 /* At the end of a function, all labels declared within the function
383    go out of scope.  BLOCK is the top-level block for the
384    function.  */
385
386 static void
387 pop_labels (tree block)
388 {
389   if (!named_labels)
390     return;
391
392   /* We need to add the labels to the block chain, so debug
393      information is emitted.  But, we want the order to be stable so
394      need to sort them first.  Otherwise the debug output could be
395      randomly ordered.  I guess it's mostly stable, unless the hash
396      table implementation changes.  */
397   auto_vec<tree, 32> labels (named_labels->elements ());
398   hash_table<named_label_hash>::iterator end (named_labels->end ());
399   for (hash_table<named_label_hash>::iterator iter
400          (named_labels->begin ()); iter != end; ++iter)
401     {
402       named_label_entry *ent = *iter;
403
404       gcc_checking_assert (!ent->outer);
405       if (ent->label_decl)
406         labels.quick_push (ent->label_decl);
407       ggc_free (ent);
408     }
409   named_labels = NULL;
410   labels.qsort (sort_labels);
411
412   while (labels.length ())
413     {
414       tree label = labels.pop ();
415
416       DECL_CHAIN (label) = BLOCK_VARS (block);
417       BLOCK_VARS (block) = label;
418
419       check_label_used (label);
420     }
421 }
422
423 /* At the end of a block with local labels, restore the outer definition.  */
424
425 static void
426 pop_local_label (tree id, tree label)
427 {
428   check_label_used (label);
429   named_label_entry **slot = named_labels->find_slot_with_hash
430     (id, IDENTIFIER_HASH_VALUE (id), NO_INSERT);
431   named_label_entry *ent = *slot;
432
433   if (ent->outer)
434     ent = ent->outer;
435   else
436     {
437       ent = ggc_cleared_alloc<named_label_entry> ();
438       ent->name = id;
439     }
440   *slot = ent;
441 }
442
443 /* The following two routines are used to interface to Objective-C++.
444    The binding level is purposely treated as an opaque type.  */
445
446 void *
447 objc_get_current_scope (void)
448 {
449   return current_binding_level;
450 }
451
452 /* The following routine is used by the NeXT-style SJLJ exceptions;
453    variables get marked 'volatile' so as to not be clobbered by
454    _setjmp()/_longjmp() calls.  All variables in the current scope,
455    as well as parent scopes up to (but not including) ENCLOSING_BLK
456    shall be thusly marked.  */
457
458 void
459 objc_mark_locals_volatile (void *enclosing_blk)
460 {
461   cp_binding_level *scope;
462
463   for (scope = current_binding_level;
464        scope && scope != enclosing_blk;
465        scope = scope->level_chain)
466     {
467       tree decl;
468
469       for (decl = scope->names; decl; decl = TREE_CHAIN (decl))
470         objc_volatilize_decl (decl);
471
472       /* Do not climb up past the current function.  */
473       if (scope->kind == sk_function_parms)
474         break;
475     }
476 }
477
478 /* True if B is the level for the condition of a constexpr if.  */
479
480 static bool
481 level_for_constexpr_if (cp_binding_level *b)
482 {
483   return (b->kind == sk_cond && b->this_entity
484           && TREE_CODE (b->this_entity) == IF_STMT
485           && IF_STMT_CONSTEXPR_P (b->this_entity));
486 }
487
488 /* Update data for defined and undefined labels when leaving a scope.  */
489
490 int
491 poplevel_named_label_1 (named_label_entry **slot, cp_binding_level *bl)
492 {
493   named_label_entry *ent = *slot;
494   cp_binding_level *obl = bl->level_chain;
495
496   if (ent->binding_level == bl)
497     {
498       tree decl;
499
500       /* ENT->NAMES_IN_SCOPE may contain a mixture of DECLs and
501          TREE_LISTs representing OVERLOADs, so be careful.  */
502       for (decl = ent->names_in_scope; decl; decl = (DECL_P (decl)
503                                                      ? DECL_CHAIN (decl)
504                                                      : TREE_CHAIN (decl)))
505         if (decl_jump_unsafe (decl))
506           vec_safe_push (ent->bad_decls, decl);
507
508       ent->binding_level = obl;
509       ent->names_in_scope = obl->names;
510       switch (bl->kind)
511         {
512         case sk_try:
513           ent->in_try_scope = true;
514           break;
515         case sk_catch:
516           ent->in_catch_scope = true;
517           break;
518         case sk_omp:
519           ent->in_omp_scope = true;
520           break;
521         case sk_transaction:
522           ent->in_transaction_scope = true;
523           break;
524         case sk_block:
525           if (level_for_constexpr_if (bl->level_chain))
526             ent->in_constexpr_if = true;
527           break;
528         default:
529           break;
530         }
531     }
532   else if (ent->uses)
533     {
534       struct named_label_use_entry *use;
535
536       for (use = ent->uses; use ; use = use->next)
537         if (use->binding_level == bl)
538           {
539             use->binding_level = obl;
540             use->names_in_scope = obl->names;
541             if (bl->kind == sk_omp)
542               use->in_omp_scope = true;
543           }
544     }
545
546   return 1;
547 }
548
549 /* Saved errorcount to avoid -Wunused-but-set-{parameter,variable} warnings
550    when errors were reported, except for -Werror-unused-but-set-*.  */
551 static int unused_but_set_errorcount;
552
553 /* Exit a binding level.
554    Pop the level off, and restore the state of the identifier-decl mappings
555    that were in effect when this level was entered.
556
557    If KEEP == 1, this level had explicit declarations, so
558    and create a "block" (a BLOCK node) for the level
559    to record its declarations and subblocks for symbol table output.
560
561    If FUNCTIONBODY is nonzero, this level is the body of a function,
562    so create a block as if KEEP were set and also clear out all
563    label names.
564
565    If REVERSE is nonzero, reverse the order of decls before putting
566    them into the BLOCK.  */
567
568 tree
569 poplevel (int keep, int reverse, int functionbody)
570 {
571   tree link;
572   /* The chain of decls was accumulated in reverse order.
573      Put it into forward order, just for cleanliness.  */
574   tree decls;
575   tree subblocks;
576   tree block;
577   tree decl;
578   scope_kind kind;
579
580   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
581  restart:
582
583   block = NULL_TREE;
584
585   gcc_assert (current_binding_level->kind != sk_class
586               && current_binding_level->kind != sk_namespace);
587
588   if (current_binding_level->kind == sk_cleanup)
589     functionbody = 0;
590   subblocks = functionbody >= 0 ? current_binding_level->blocks : 0;
591
592   gcc_assert (!vec_safe_length (current_binding_level->class_shadowed));
593
594   /* We used to use KEEP == 2 to indicate that the new block should go
595      at the beginning of the list of blocks at this binding level,
596      rather than the end.  This hack is no longer used.  */
597   gcc_assert (keep == 0 || keep == 1);
598
599   if (current_binding_level->keep)
600     keep = 1;
601
602   /* Any uses of undefined labels, and any defined labels, now operate
603      under constraints of next binding contour.  */
604   if (cfun && !functionbody && named_labels)
605     named_labels->traverse<cp_binding_level *, poplevel_named_label_1>
606                    (current_binding_level);
607
608   /* Get the decls in the order they were written.
609      Usually current_binding_level->names is in reverse order.
610      But parameter decls were previously put in forward order.  */
611
612   decls = current_binding_level->names;
613   if (reverse)
614     {
615       decls = nreverse (decls);
616       current_binding_level->names = decls;
617     }
618
619   /* If there were any declarations or structure tags in that level,
620      or if this level is a function body,
621      create a BLOCK to record them for the life of this function.  */
622   block = NULL_TREE;
623   /* Avoid function body block if possible.  */
624   if (functionbody && subblocks && BLOCK_CHAIN (subblocks) == NULL_TREE)
625     keep = 0;
626   else if (keep == 1 || functionbody)
627     block = make_node (BLOCK);
628   if (block != NULL_TREE)
629     {
630       BLOCK_VARS (block) = decls;
631       BLOCK_SUBBLOCKS (block) = subblocks;
632     }
633
634   /* In each subblock, record that this is its superior.  */
635   if (keep >= 0)
636     for (link = subblocks; link; link = BLOCK_CHAIN (link))
637       BLOCK_SUPERCONTEXT (link) = block;
638
639   /* Before we remove the declarations first check for unused variables.  */
640   if ((warn_unused_variable || warn_unused_but_set_variable)
641       && current_binding_level->kind != sk_template_parms
642       && !processing_template_decl)
643     for (tree d = get_local_decls (); d; d = TREE_CHAIN (d))
644       {
645         /* There are cases where D itself is a TREE_LIST.  See in
646            push_local_binding where the list of decls returned by
647            getdecls is built.  */
648         decl = TREE_CODE (d) == TREE_LIST ? TREE_VALUE (d) : d;
649
650         tree type = TREE_TYPE (decl);
651         if (VAR_P (decl)
652             && (! TREE_USED (decl) || !DECL_READ_P (decl))
653             && ! DECL_IN_SYSTEM_HEADER (decl)
654             /* For structured bindings, consider only real variables, not
655                subobjects.  */
656             && (DECL_DECOMPOSITION_P (decl) ? !DECL_DECOMP_BASE (decl)
657                 : (DECL_NAME (decl) && !DECL_ARTIFICIAL (decl)))
658             && type != error_mark_node
659             && (!CLASS_TYPE_P (type)
660                 || !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
661                 || lookup_attribute ("warn_unused",
662                                      TYPE_ATTRIBUTES (TREE_TYPE (decl)))))
663           {
664             if (! TREE_USED (decl))
665               {
666                 if (!DECL_NAME (decl) && DECL_DECOMPOSITION_P (decl))
667                   warning_at (DECL_SOURCE_LOCATION (decl),
668                               OPT_Wunused_variable,
669                               "unused structured binding declaration");
670                 else
671                   warning_at (DECL_SOURCE_LOCATION (decl),
672                               OPT_Wunused_variable, "unused variable %qD", decl);
673               }
674             else if (DECL_CONTEXT (decl) == current_function_decl
675                      // For -Wunused-but-set-variable leave references alone.
676                      && !TYPE_REF_P (TREE_TYPE (decl))
677                      && errorcount == unused_but_set_errorcount)
678               {
679                 if (!DECL_NAME (decl) && DECL_DECOMPOSITION_P (decl))
680                   warning_at (DECL_SOURCE_LOCATION (decl),
681                               OPT_Wunused_but_set_variable, "structured "
682                               "binding declaration set but not used");
683                 else
684                   warning_at (DECL_SOURCE_LOCATION (decl),
685                               OPT_Wunused_but_set_variable,
686                               "variable %qD set but not used", decl);
687                 unused_but_set_errorcount = errorcount;
688               }
689           }
690       }
691
692   /* Remove declarations for all the DECLs in this level.  */
693   for (link = decls; link; link = TREE_CHAIN (link))
694     {
695       tree name;
696       if (TREE_CODE (link) == TREE_LIST)
697         {
698           decl = TREE_VALUE (link);
699           name = TREE_PURPOSE (link);
700           gcc_checking_assert (name);
701         }
702       else
703         {
704           decl = link;
705           name = DECL_NAME (decl);
706         }
707
708       /* Remove the binding.  */
709       if (TREE_CODE (decl) == LABEL_DECL)
710         pop_local_label (name, decl);
711       else
712         pop_local_binding (name, decl);
713     }
714
715   /* Restore the IDENTIFIER_TYPE_VALUEs.  */
716   for (link = current_binding_level->type_shadowed;
717        link; link = TREE_CHAIN (link))
718     SET_IDENTIFIER_TYPE_VALUE (TREE_PURPOSE (link), TREE_VALUE (link));
719
720   /* There may be OVERLOADs (wrapped in TREE_LISTs) on the BLOCK_VARs
721      list if a `using' declaration put them there.  The debugging
722      back ends won't understand OVERLOAD, so we remove them here.
723      Because the BLOCK_VARS are (temporarily) shared with
724      CURRENT_BINDING_LEVEL->NAMES we must do this fixup after we have
725      popped all the bindings.  Also remove undeduced 'auto' decls,
726      which LTO doesn't understand, and can't have been used by anything.  */
727   if (block)
728     {
729       tree* d;
730
731       for (d = &BLOCK_VARS (block); *d; )
732         {
733           if (TREE_CODE (*d) == TREE_LIST
734               || (!processing_template_decl
735                   && undeduced_auto_decl (*d)))
736             *d = TREE_CHAIN (*d);
737           else
738             d = &DECL_CHAIN (*d);
739         }
740     }
741
742   /* If the level being exited is the top level of a function,
743      check over all the labels.  */
744   if (functionbody)
745     {
746       if (block)
747         {
748           /* Since this is the top level block of a function, the vars are
749              the function's parameters.  Don't leave them in the BLOCK
750              because they are found in the FUNCTION_DECL instead.  */
751           BLOCK_VARS (block) = 0;
752           pop_labels (block);
753         }
754       else
755         pop_labels (subblocks);
756     }
757
758   kind = current_binding_level->kind;
759   if (kind == sk_cleanup)
760     {
761       tree stmt;
762
763       /* If this is a temporary binding created for a cleanup, then we'll
764          have pushed a statement list level.  Pop that, create a new
765          BIND_EXPR for the block, and insert it into the stream.  */
766       stmt = pop_stmt_list (current_binding_level->statement_list);
767       stmt = c_build_bind_expr (input_location, block, stmt);
768       add_stmt (stmt);
769     }
770
771   leave_scope ();
772   if (functionbody)
773     {
774       /* The current function is being defined, so its DECL_INITIAL
775          should be error_mark_node.  */
776       gcc_assert (DECL_INITIAL (current_function_decl) == error_mark_node);
777       DECL_INITIAL (current_function_decl) = block ? block : subblocks;
778       if (subblocks)
779         {
780           if (FUNCTION_NEEDS_BODY_BLOCK (current_function_decl))
781             {
782               if (BLOCK_SUBBLOCKS (subblocks))
783                 BLOCK_OUTER_CURLY_BRACE_P (BLOCK_SUBBLOCKS (subblocks)) = 1;
784             }
785           else
786             BLOCK_OUTER_CURLY_BRACE_P (subblocks) = 1;
787         }
788     }
789   else if (block)
790     current_binding_level->blocks
791       = block_chainon (current_binding_level->blocks, block);
792
793   /* If we did not make a block for the level just exited,
794      any blocks made for inner levels
795      (since they cannot be recorded as subblocks in that level)
796      must be carried forward so they will later become subblocks
797      of something else.  */
798   else if (subblocks)
799     current_binding_level->blocks
800       = block_chainon (current_binding_level->blocks, subblocks);
801
802   /* Each and every BLOCK node created here in `poplevel' is important
803      (e.g. for proper debugging information) so if we created one
804      earlier, mark it as "used".  */
805   if (block)
806     TREE_USED (block) = 1;
807
808   /* All temporary bindings created for cleanups are popped silently.  */
809   if (kind == sk_cleanup)
810     goto restart;
811
812   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
813   return block;
814 }
815
816 /* Call wrapup_globals_declarations for the globals in NAMESPACE.  */
817 /* Diagnose odr-used extern inline variables without definitions
818    in the current TU.  */
819
820 int
821 wrapup_namespace_globals ()
822 {
823   if (vec<tree, va_gc> *statics = static_decls)
824     {
825       tree decl;
826       unsigned int i;
827       FOR_EACH_VEC_ELT (*statics, i, decl)
828         {
829           if (warn_unused_function
830               && TREE_CODE (decl) == FUNCTION_DECL
831               && DECL_INITIAL (decl) == 0
832               && DECL_EXTERNAL (decl)
833               && !TREE_PUBLIC (decl)
834               && !DECL_ARTIFICIAL (decl)
835               && !DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl)
836               && !TREE_NO_WARNING (decl))
837             warning_at (DECL_SOURCE_LOCATION (decl),
838                         OPT_Wunused_function,
839                         "%qF declared %<static%> but never defined", decl);
840
841           if (VAR_P (decl)
842               && DECL_EXTERNAL (decl)
843               && DECL_INLINE_VAR_P (decl)
844               && DECL_ODR_USED (decl))
845             error_at (DECL_SOURCE_LOCATION (decl),
846                       "odr-used inline variable %qD is not defined", decl);
847         }
848
849       /* Clear out the list, so we don't rescan next time.  */
850       static_decls = NULL;
851
852       /* Write out any globals that need to be output.  */
853       return wrapup_global_declarations (statics->address (),
854                                          statics->length ());
855     }
856   return 0;
857 }
858 \f
859 /* In C++, you don't have to write `struct S' to refer to `S'; you
860    can just use `S'.  We accomplish this by creating a TYPE_DECL as
861    if the user had written `typedef struct S S'.  Create and return
862    the TYPE_DECL for TYPE.  */
863
864 tree
865 create_implicit_typedef (tree name, tree type)
866 {
867   tree decl;
868
869   decl = build_decl (input_location, TYPE_DECL, name, type);
870   DECL_ARTIFICIAL (decl) = 1;
871   /* There are other implicit type declarations, like the one *within*
872      a class that allows you to write `S::S'.  We must distinguish
873      amongst these.  */
874   SET_DECL_IMPLICIT_TYPEDEF_P (decl);
875   TYPE_NAME (type) = decl;
876   TYPE_STUB_DECL (type) = decl;
877
878   return decl;
879 }
880
881 /* Function-scope local entities that need discriminators.  Each entry
882    is a {decl,name} pair.  VAR_DECLs for anon unions get their name
883    smashed, so we cannot rely on DECL_NAME.  */
884
885 static GTY((deletable)) vec<tree, va_gc> *local_entities;
886
887 /* Determine the mangling discriminator of local DECL.  There are
888    generally very few of these in any particular function.  */
889
890 void
891 determine_local_discriminator (tree decl)
892 {
893   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
894   retrofit_lang_decl (decl);
895   tree ctx = DECL_CONTEXT (decl);
896   tree name = (TREE_CODE (decl) == TYPE_DECL
897                && TYPE_UNNAMED_P (TREE_TYPE (decl))
898                ? NULL_TREE : DECL_NAME (decl));
899   size_t nelts = vec_safe_length (local_entities);
900   for (size_t i = 0; i < nelts; i += 2)
901     {
902       tree *pair = &(*local_entities)[i];
903       tree d = pair[0];
904       tree n = pair[1];
905       gcc_checking_assert (d != decl);
906       if (name == n
907           && TREE_CODE (decl) == TREE_CODE (d)
908           && ctx == DECL_CONTEXT (d))
909         {
910           tree disc = integer_one_node;
911           if (DECL_DISCRIMINATOR (d))
912             disc = build_int_cst (TREE_TYPE (disc),
913                                   TREE_INT_CST_LOW (DECL_DISCRIMINATOR (d)) + 1);
914           DECL_DISCRIMINATOR (decl) = disc;
915           /* Replace the saved decl.  */
916           pair[0] = decl;
917           decl = NULL_TREE;
918           break;
919         }
920     }
921
922   if (decl)
923     {
924       vec_safe_reserve (local_entities, 2);
925       local_entities->quick_push (decl);
926       local_entities->quick_push (name);
927     }
928
929   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
930 }
931
932 \f
933
934 /* Returns true if functions FN1 and FN2 have equivalent trailing
935    requires clauses.  */
936
937 static bool
938 function_requirements_equivalent_p (tree newfn, tree oldfn)
939 {
940   /* In the concepts TS, the combined constraints are compared.  */
941   if (cxx_dialect < cxx20)
942     {
943       tree ci1 = get_constraints (oldfn);
944       tree ci2 = get_constraints (newfn);
945       tree req1 = ci1 ? CI_ASSOCIATED_CONSTRAINTS (ci1) : NULL_TREE;
946       tree req2 = ci2 ? CI_ASSOCIATED_CONSTRAINTS (ci2) : NULL_TREE;
947       return cp_tree_equal (req1, req2);
948     }
949
950   /* Compare only trailing requirements.  */
951   tree reqs1 = get_trailing_function_requirements (newfn);
952   tree reqs2 = get_trailing_function_requirements (oldfn);
953   if ((reqs1 != NULL_TREE) != (reqs2 != NULL_TREE))
954     return false;
955
956   /* Substitution is needed when friends are involved.  */
957   reqs1 = maybe_substitute_reqs_for (reqs1, newfn);
958   reqs2 = maybe_substitute_reqs_for (reqs2, oldfn);
959
960   return cp_tree_equal (reqs1, reqs2);
961 }
962
963 /* Subroutine of duplicate_decls: return truthvalue of whether
964    or not types of these decls match.
965
966    For C++, we must compare the parameter list so that `int' can match
967    `int&' in a parameter position, but `int&' is not confused with
968    `const int&'.  */
969
970 int
971 decls_match (tree newdecl, tree olddecl, bool record_versions /* = true */)
972 {
973   int types_match;
974
975   if (newdecl == olddecl)
976     return 1;
977
978   if (TREE_CODE (newdecl) != TREE_CODE (olddecl))
979     /* If the two DECLs are not even the same kind of thing, we're not
980        interested in their types.  */
981     return 0;
982
983   gcc_assert (DECL_P (newdecl));
984
985   if (TREE_CODE (newdecl) == FUNCTION_DECL)
986     {
987       /* Specializations of different templates are different functions
988          even if they have the same type.  */
989       tree t1 = (DECL_USE_TEMPLATE (newdecl)
990                  ? DECL_TI_TEMPLATE (newdecl)
991                  : NULL_TREE);
992       tree t2 = (DECL_USE_TEMPLATE (olddecl)
993                  ? DECL_TI_TEMPLATE (olddecl)
994                  : NULL_TREE);
995       if (t1 != t2)
996         return 0;
997
998       if (CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl)
999           && ! (DECL_EXTERN_C_P (newdecl)
1000                 && DECL_EXTERN_C_P (olddecl)))
1001         return 0;
1002
1003       /* A new declaration doesn't match a built-in one unless it
1004          is also extern "C".  */
1005       if (DECL_IS_BUILTIN (olddecl)
1006           && DECL_EXTERN_C_P (olddecl) && !DECL_EXTERN_C_P (newdecl))
1007         return 0;
1008
1009       tree f1 = TREE_TYPE (newdecl);
1010       tree f2 = TREE_TYPE (olddecl);
1011       if (TREE_CODE (f1) != TREE_CODE (f2))
1012         return 0;
1013
1014       /* A declaration with deduced return type should use its pre-deduction
1015          type for declaration matching.  */
1016       tree r2 = fndecl_declared_return_type (olddecl);
1017       tree r1 = fndecl_declared_return_type (newdecl);
1018
1019       tree p1 = TYPE_ARG_TYPES (f1);
1020       tree p2 = TYPE_ARG_TYPES (f2);
1021
1022       if (same_type_p (r1, r2))
1023         {
1024           if (!prototype_p (f2) && DECL_EXTERN_C_P (olddecl)
1025               && fndecl_built_in_p (olddecl))
1026             {
1027               types_match = self_promoting_args_p (p1);
1028               if (p1 == void_list_node)
1029                 TREE_TYPE (newdecl) = TREE_TYPE (olddecl);
1030             }
1031           else
1032             types_match =
1033               compparms (p1, p2)
1034               && type_memfn_rqual (f1) == type_memfn_rqual (f2)
1035               && (TYPE_ATTRIBUTES (TREE_TYPE (newdecl)) == NULL_TREE
1036                   || comp_type_attributes (TREE_TYPE (newdecl),
1037                                            TREE_TYPE (olddecl)) != 0);
1038         }
1039       else
1040         types_match = 0;
1041
1042       /* Two function declarations match if either has a requires-clause
1043          then both have a requires-clause and their constraints-expressions
1044          are equivalent.  */
1045       if (types_match && flag_concepts)
1046         types_match = function_requirements_equivalent_p (newdecl, olddecl);
1047
1048       /* The decls dont match if they correspond to two different versions
1049          of the same function.   Disallow extern "C" functions to be
1050          versions for now.  */
1051       if (types_match
1052           && !DECL_EXTERN_C_P (newdecl)
1053           && !DECL_EXTERN_C_P (olddecl)
1054           && record_versions
1055           && maybe_version_functions (newdecl, olddecl,
1056                                       (!DECL_FUNCTION_VERSIONED (newdecl)
1057                                        || !DECL_FUNCTION_VERSIONED (olddecl))))
1058         return 0;
1059     }
1060   else if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1061     {
1062       if (!template_heads_equivalent_p (newdecl, olddecl))
1063         return 0;
1064
1065       tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1066       tree newres = DECL_TEMPLATE_RESULT (newdecl);
1067
1068       if (TREE_CODE (newres) != TREE_CODE (oldres))
1069         return 0;
1070
1071       /* Two template types match if they are the same. Otherwise, compare
1072          the underlying declarations.  */
1073       if (TREE_CODE (newres) == TYPE_DECL)
1074         types_match = same_type_p (TREE_TYPE (newres), TREE_TYPE (oldres));
1075       else
1076         types_match = decls_match (newres, oldres);
1077     }
1078   else
1079     {
1080       /* Need to check scope for variable declaration (VAR_DECL).
1081          For typedef (TYPE_DECL), scope is ignored.  */
1082       if (VAR_P (newdecl)
1083           && CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl)
1084           /* [dcl.link]
1085              Two declarations for an object with C language linkage
1086              with the same name (ignoring the namespace that qualify
1087              it) that appear in different namespace scopes refer to
1088              the same object.  */
1089           && !(DECL_EXTERN_C_P (olddecl) && DECL_EXTERN_C_P (newdecl)))
1090         return 0;
1091
1092       if (TREE_TYPE (newdecl) == error_mark_node)
1093         types_match = TREE_TYPE (olddecl) == error_mark_node;
1094       else if (TREE_TYPE (olddecl) == NULL_TREE)
1095         types_match = TREE_TYPE (newdecl) == NULL_TREE;
1096       else if (TREE_TYPE (newdecl) == NULL_TREE)
1097         types_match = 0;
1098       else
1099         types_match = comptypes (TREE_TYPE (newdecl),
1100                                  TREE_TYPE (olddecl),
1101                                  COMPARE_REDECLARATION);
1102     }
1103
1104   return types_match;
1105 }
1106
1107 /* NEWDECL and OLDDECL have identical signatures.  If they are
1108    different versions adjust them and return true.
1109    If RECORD is set to true, record function versions.  */
1110
1111 bool
1112 maybe_version_functions (tree newdecl, tree olddecl, bool record)
1113 {
1114   if (!targetm.target_option.function_versions (newdecl, olddecl))
1115     return false;
1116
1117   if (!DECL_FUNCTION_VERSIONED (olddecl))
1118     {
1119       DECL_FUNCTION_VERSIONED (olddecl) = 1;
1120       if (DECL_ASSEMBLER_NAME_SET_P (olddecl))
1121         mangle_decl (olddecl);
1122     }
1123
1124   if (!DECL_FUNCTION_VERSIONED (newdecl))
1125     {
1126       DECL_FUNCTION_VERSIONED (newdecl) = 1;
1127       if (DECL_ASSEMBLER_NAME_SET_P (newdecl))
1128         mangle_decl (newdecl);
1129     }
1130
1131   if (record)
1132     cgraph_node::record_function_versions (olddecl, newdecl);
1133
1134   return true;
1135 }
1136
1137 /* If NEWDECL is `static' and an `extern' was seen previously,
1138    warn about it.  OLDDECL is the previous declaration.
1139
1140    Note that this does not apply to the C++ case of declaring
1141    a variable `extern const' and then later `const'.
1142
1143    Don't complain about built-in functions, since they are beyond
1144    the user's control.  */
1145
1146 void
1147 warn_extern_redeclared_static (tree newdecl, tree olddecl)
1148 {
1149   if (TREE_CODE (newdecl) == TYPE_DECL
1150       || TREE_CODE (newdecl) == TEMPLATE_DECL
1151       || TREE_CODE (newdecl) == CONST_DECL
1152       || TREE_CODE (newdecl) == NAMESPACE_DECL)
1153     return;
1154
1155   /* Don't get confused by static member functions; that's a different
1156      use of `static'.  */
1157   if (TREE_CODE (newdecl) == FUNCTION_DECL
1158       && DECL_STATIC_FUNCTION_P (newdecl))
1159     return;
1160
1161   /* If the old declaration was `static', or the new one isn't, then
1162      everything is OK.  */
1163   if (DECL_THIS_STATIC (olddecl) || !DECL_THIS_STATIC (newdecl))
1164     return;
1165
1166   /* It's OK to declare a builtin function as `static'.  */
1167   if (TREE_CODE (olddecl) == FUNCTION_DECL
1168       && DECL_ARTIFICIAL (olddecl))
1169     return;
1170
1171   auto_diagnostic_group d;
1172   if (permerror (DECL_SOURCE_LOCATION (newdecl),
1173                  "%qD was declared %<extern%> and later %<static%>", newdecl))
1174     inform (DECL_SOURCE_LOCATION (olddecl),
1175             "previous declaration of %qD", olddecl);
1176 }
1177
1178 /* NEW_DECL is a redeclaration of OLD_DECL; both are functions or
1179    function templates.  If their exception specifications do not
1180    match, issue a diagnostic.  */
1181
1182 static void
1183 check_redeclaration_exception_specification (tree new_decl,
1184                                              tree old_decl)
1185 {
1186   tree new_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (new_decl));
1187   tree old_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (old_decl));
1188
1189   /* Two default specs are equivalent, don't force evaluation.  */
1190   if (UNEVALUATED_NOEXCEPT_SPEC_P (new_exceptions)
1191       && UNEVALUATED_NOEXCEPT_SPEC_P (old_exceptions))
1192     return;
1193
1194   if (!type_dependent_expression_p (old_decl))
1195     {
1196       maybe_instantiate_noexcept (new_decl);
1197       maybe_instantiate_noexcept (old_decl);
1198     }
1199   new_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (new_decl));
1200   old_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (old_decl));
1201
1202   /* [except.spec]
1203
1204      If any declaration of a function has an exception-specification,
1205      all declarations, including the definition and an explicit
1206      specialization, of that function shall have an
1207      exception-specification with the same set of type-ids.  */
1208   if (! DECL_IS_BUILTIN (old_decl)
1209       && !comp_except_specs (new_exceptions, old_exceptions, ce_normal))
1210     {
1211       const char *const msg
1212         = G_("declaration of %qF has a different exception specifier");
1213       bool complained = true;
1214       location_t new_loc = DECL_SOURCE_LOCATION (new_decl);
1215       auto_diagnostic_group d;
1216       if (DECL_IN_SYSTEM_HEADER (old_decl))
1217         complained = pedwarn (new_loc, OPT_Wsystem_headers, msg, new_decl);
1218       else if (!flag_exceptions)
1219         /* We used to silently permit mismatched eh specs with
1220            -fno-exceptions, so make them a pedwarn now.  */
1221         complained = pedwarn (new_loc, OPT_Wpedantic, msg, new_decl);
1222       else
1223         error_at (new_loc, msg, new_decl);
1224       if (complained)
1225         inform (DECL_SOURCE_LOCATION (old_decl),
1226                 "from previous declaration %qF", old_decl);
1227     }
1228 }
1229
1230 /* Return true if OLD_DECL and NEW_DECL agree on constexprness.
1231    Otherwise issue diagnostics.  */
1232
1233 static bool
1234 validate_constexpr_redeclaration (tree old_decl, tree new_decl)
1235 {
1236   old_decl = STRIP_TEMPLATE (old_decl);
1237   new_decl = STRIP_TEMPLATE (new_decl);
1238   if (!VAR_OR_FUNCTION_DECL_P (old_decl)
1239       || !VAR_OR_FUNCTION_DECL_P (new_decl))
1240     return true;
1241   if (DECL_DECLARED_CONSTEXPR_P (old_decl)
1242       == DECL_DECLARED_CONSTEXPR_P (new_decl))
1243     {
1244       if (TREE_CODE (old_decl) != FUNCTION_DECL)
1245         return true;
1246       if (DECL_IMMEDIATE_FUNCTION_P (old_decl)
1247           == DECL_IMMEDIATE_FUNCTION_P (new_decl))
1248         return true;
1249     }
1250   if (TREE_CODE (old_decl) == FUNCTION_DECL)
1251     {
1252       if (fndecl_built_in_p (old_decl))
1253         {
1254           /* Hide a built-in declaration.  */
1255           DECL_DECLARED_CONSTEXPR_P (old_decl)
1256             = DECL_DECLARED_CONSTEXPR_P (new_decl);
1257           if (DECL_IMMEDIATE_FUNCTION_P (new_decl))
1258             SET_DECL_IMMEDIATE_FUNCTION_P (old_decl);
1259           return true;
1260         }
1261       /* 7.1.5 [dcl.constexpr]
1262          Note: An explicit specialization can differ from the template
1263          declaration with respect to the constexpr specifier.  */
1264       if (! DECL_TEMPLATE_SPECIALIZATION (old_decl)
1265           && DECL_TEMPLATE_SPECIALIZATION (new_decl))
1266         return true;
1267
1268       const char *kind = "constexpr";
1269       if (DECL_IMMEDIATE_FUNCTION_P (old_decl)
1270           || DECL_IMMEDIATE_FUNCTION_P (new_decl))
1271         kind = "consteval";
1272       error_at (DECL_SOURCE_LOCATION (new_decl),
1273                 "redeclaration %qD differs in %qs "
1274                 "from previous declaration", new_decl,
1275                 kind);
1276       inform (DECL_SOURCE_LOCATION (old_decl),
1277               "previous declaration %qD", old_decl);
1278       return false;
1279     }
1280   return true;
1281 }
1282
1283 // If OLDDECL and NEWDECL are concept declarations with the same type
1284 // (i.e., and template parameters), but different requirements,
1285 // emit diagnostics and return true. Otherwise, return false.
1286 static inline bool
1287 check_concept_refinement (tree olddecl, tree newdecl)
1288 {
1289   if (!DECL_DECLARED_CONCEPT_P (olddecl) || !DECL_DECLARED_CONCEPT_P (newdecl))
1290     return false;
1291
1292   tree d1 = DECL_TEMPLATE_RESULT (olddecl);
1293   tree d2 = DECL_TEMPLATE_RESULT (newdecl);
1294   if (TREE_CODE (d1) != TREE_CODE (d2))
1295     return false;
1296
1297   tree t1 = TREE_TYPE (d1);
1298   tree t2 = TREE_TYPE (d2);
1299   if (TREE_CODE (d1) == FUNCTION_DECL)
1300     {
1301       if (compparms (TYPE_ARG_TYPES (t1), TYPE_ARG_TYPES (t2))
1302           && comp_template_parms (DECL_TEMPLATE_PARMS (olddecl),
1303                                   DECL_TEMPLATE_PARMS (newdecl))
1304           && !equivalently_constrained (olddecl, newdecl))
1305         {
1306           error ("cannot specialize concept %q#D", olddecl);
1307           return true;
1308         }
1309     }
1310   return false;
1311 }
1312
1313 /* DECL is a redeclaration of a function or function template.  If
1314    it does have default arguments issue a diagnostic.  Note: this
1315    function is used to enforce the requirements in C++11 8.3.6 about
1316    no default arguments in redeclarations.  */
1317
1318 static void
1319 check_redeclaration_no_default_args (tree decl)
1320 {
1321   gcc_assert (DECL_DECLARES_FUNCTION_P (decl));
1322
1323   for (tree t = FUNCTION_FIRST_USER_PARMTYPE (decl);
1324        t && t != void_list_node; t = TREE_CHAIN (t))
1325     if (TREE_PURPOSE (t))
1326       {
1327         permerror (DECL_SOURCE_LOCATION (decl),
1328                    "redeclaration of %q#D may not have default "
1329                    "arguments", decl);
1330         return;
1331       }
1332 }
1333
1334 /* NEWDECL is a redeclaration of a function or function template OLDDECL,
1335    in any case represented as FUNCTION_DECLs (the DECL_TEMPLATE_RESULTs of
1336    the TEMPLATE_DECLs in case of function templates).  This function is used
1337    to enforce the final part of C++17 11.3.6/4, about a single declaration:
1338    "If a friend declaration specifies a default argument expression, that
1339    declaration shall be a definition and shall be the only declaration of
1340    the function or function template in the translation unit."  */
1341
1342 static void
1343 check_no_redeclaration_friend_default_args (tree olddecl, tree newdecl,
1344                                             bool olddecl_hidden_p)
1345 {
1346   if (!olddecl_hidden_p && !DECL_FRIEND_P (newdecl))
1347     return;
1348
1349   for (tree t1 = FUNCTION_FIRST_USER_PARMTYPE (olddecl),
1350          t2 = FUNCTION_FIRST_USER_PARMTYPE (newdecl);
1351        t1 && t1 != void_list_node;
1352        t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2))
1353     if ((olddecl_hidden_p && TREE_PURPOSE (t1))
1354         || (DECL_FRIEND_P (newdecl) && TREE_PURPOSE (t2)))
1355       {
1356         auto_diagnostic_group d;
1357         if (permerror (DECL_SOURCE_LOCATION (newdecl),
1358                        "friend declaration of %q#D specifies default "
1359                        "arguments and isn%'t the only declaration", newdecl))
1360           inform (DECL_SOURCE_LOCATION (olddecl),
1361                   "previous declaration of %q#D", olddecl);
1362         return;
1363       }
1364 }
1365
1366 /* Merge tree bits that correspond to attributes noreturn, nothrow,
1367    const,  malloc, and pure from NEWDECL with those of OLDDECL.  */
1368
1369 static void
1370 merge_attribute_bits (tree newdecl, tree olddecl)
1371 {
1372   TREE_THIS_VOLATILE (newdecl) |= TREE_THIS_VOLATILE (olddecl);
1373   TREE_THIS_VOLATILE (olddecl) |= TREE_THIS_VOLATILE (newdecl);
1374   TREE_NOTHROW (newdecl) |= TREE_NOTHROW (olddecl);
1375   TREE_NOTHROW (olddecl) |= TREE_NOTHROW (newdecl);
1376   TREE_READONLY (newdecl) |= TREE_READONLY (olddecl);
1377   TREE_READONLY (olddecl) |= TREE_READONLY (newdecl);
1378   DECL_IS_MALLOC (newdecl) |= DECL_IS_MALLOC (olddecl);
1379   DECL_IS_MALLOC (olddecl) |= DECL_IS_MALLOC (newdecl);
1380   DECL_PURE_P (newdecl) |= DECL_PURE_P (olddecl);
1381   DECL_PURE_P (olddecl) |= DECL_PURE_P (newdecl);
1382   DECL_UNINLINABLE (newdecl) |= DECL_UNINLINABLE (olddecl);
1383   DECL_UNINLINABLE (olddecl) |= DECL_UNINLINABLE (newdecl);
1384 }
1385
1386 #define GNU_INLINE_P(fn) (DECL_DECLARED_INLINE_P (fn)                   \
1387                           && lookup_attribute ("gnu_inline",            \
1388                                                DECL_ATTRIBUTES (fn)))
1389
1390 /* A subroutine of duplicate_decls. Emits a diagnostic when newdecl
1391    ambiguates olddecl.  Returns true if an error occurs.  */
1392
1393 static bool
1394 duplicate_function_template_decls (tree newdecl, tree olddecl)
1395 {
1396
1397   tree newres = DECL_TEMPLATE_RESULT (newdecl);
1398   tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1399   /* Function template declarations can be differentiated by parameter
1400      and return type.  */
1401   if (compparms (TYPE_ARG_TYPES (TREE_TYPE (oldres)),
1402                  TYPE_ARG_TYPES (TREE_TYPE (newres)))
1403        && same_type_p (TREE_TYPE (TREE_TYPE (newdecl)),
1404                        TREE_TYPE (TREE_TYPE (olddecl))))
1405     {
1406       /* ... and also by their template-heads and requires-clauses.  */
1407       if (template_heads_equivalent_p (newdecl, olddecl)
1408           && function_requirements_equivalent_p (newres, oldres))
1409         {
1410           error ("ambiguating new declaration %q+#D", newdecl);
1411           inform (DECL_SOURCE_LOCATION (olddecl),
1412                   "old declaration %q#D", olddecl);
1413           return true;
1414         }
1415
1416       /* FIXME: The types are the same but the are differences
1417          in either the template heads or function requirements.
1418          We should be able to diagnose a set of common errors
1419          stemming from these declarations. For example:
1420
1421            template<typename T> requires C void f(...);
1422            template<typename T> void f(...) requires C;
1423
1424          These are functionally equivalent but not equivalent.  */
1425     }
1426
1427   return false;
1428 }
1429
1430 /* If NEWDECL is a redeclaration of OLDDECL, merge the declarations.
1431    If the redeclaration is invalid, a diagnostic is issued, and the
1432    error_mark_node is returned.  Otherwise, OLDDECL is returned.
1433
1434    If NEWDECL is not a redeclaration of OLDDECL, NULL_TREE is
1435    returned.
1436
1437    HIDING is true if the new decl is being hidden.  WAS_HIDDEN is true
1438    if the old decl was hidden.
1439
1440    Hidden decls can be anticipated builtins, injected friends, or
1441    (coming soon) injected from a local-extern decl.   */
1442
1443 tree
1444 duplicate_decls (tree newdecl, tree olddecl, bool hiding, bool was_hidden)
1445 {
1446   unsigned olddecl_uid = DECL_UID (olddecl);
1447   int olddecl_friend = 0, types_match = 0;
1448   int olddecl_hidden_friend = 0;
1449   int new_defines_function = 0;
1450   tree new_template_info;
1451   location_t olddecl_loc = DECL_SOURCE_LOCATION (olddecl);
1452   location_t newdecl_loc = DECL_SOURCE_LOCATION (newdecl);
1453
1454   if (newdecl == olddecl)
1455     return olddecl;
1456
1457   types_match = decls_match (newdecl, olddecl);
1458
1459   /* If either the type of the new decl or the type of the old decl is an
1460      error_mark_node, then that implies that we have already issued an
1461      error (earlier) for some bogus type specification, and in that case,
1462      it is rather pointless to harass the user with yet more error message
1463      about the same declaration, so just pretend the types match here.  */
1464   if (TREE_TYPE (newdecl) == error_mark_node
1465       || TREE_TYPE (olddecl) == error_mark_node)
1466     return error_mark_node;
1467
1468   /* Check for redeclaration and other discrepancies.  */
1469   if (TREE_CODE (olddecl) == FUNCTION_DECL
1470       && DECL_BUILTIN_P (olddecl))
1471     {
1472       if (TREE_CODE (newdecl) != FUNCTION_DECL)
1473         {
1474           /* Avoid warnings redeclaring built-ins which have not been
1475              explicitly declared.  */
1476           if (was_hidden)
1477             {
1478               if (TREE_PUBLIC (newdecl)
1479                   && CP_DECL_CONTEXT (newdecl) == global_namespace)
1480                 warning_at (newdecl_loc,
1481                             OPT_Wbuiltin_declaration_mismatch,
1482                             "built-in function %qD declared as non-function",
1483                             newdecl);
1484               return NULL_TREE;
1485             }
1486
1487           /* If you declare a built-in or predefined function name as static,
1488              the old definition is overridden, but optionally warn this was a
1489              bad choice of name.  */
1490           if (! TREE_PUBLIC (newdecl))
1491             {
1492               warning_at (newdecl_loc,
1493                           OPT_Wshadow, 
1494                           fndecl_built_in_p (olddecl)
1495                           ? G_("shadowing built-in function %q#D")
1496                           : G_("shadowing library function %q#D"), olddecl);
1497               /* Discard the old built-in function.  */
1498               return NULL_TREE;
1499             }
1500           /* If the built-in is not ansi, then programs can override
1501              it even globally without an error.  */
1502           else if (! fndecl_built_in_p (olddecl))
1503             warning_at (newdecl_loc, 0,
1504                         "library function %q#D redeclared as non-function %q#D",
1505                         olddecl, newdecl);
1506           else
1507             error_at (newdecl_loc,
1508                       "declaration of %q#D conflicts with built-in "
1509                       "declaration %q#D", newdecl, olddecl);
1510           return NULL_TREE;
1511         }
1512       else if (!types_match)
1513         {
1514           /* Avoid warnings redeclaring built-ins which have not been
1515              explicitly declared.  */
1516           if (was_hidden)
1517             {
1518               tree t1, t2;
1519
1520               /* A new declaration doesn't match a built-in one unless it
1521                  is also extern "C".  */
1522               gcc_assert (DECL_IS_BUILTIN (olddecl));
1523               gcc_assert (DECL_EXTERN_C_P (olddecl));
1524               if (!DECL_EXTERN_C_P (newdecl))
1525                 return NULL_TREE;
1526
1527               for (t1 = TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1528                    t2 = TYPE_ARG_TYPES (TREE_TYPE (olddecl));
1529                    t1 || t2;
1530                    t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2))
1531                 {
1532                   if (!t1 || !t2)
1533                     break;
1534                   /* FILE, tm types are not known at the time
1535                      we create the builtins.  */
1536                   for (unsigned i = 0;
1537                        i < sizeof (builtin_structptr_types)
1538                            / sizeof (builtin_structptr_type);
1539                        ++i)
1540                     if (TREE_VALUE (t2) == builtin_structptr_types[i].node)
1541                       {
1542                         tree t = TREE_VALUE (t1);
1543
1544                         if (TYPE_PTR_P (t)
1545                             && TYPE_IDENTIFIER (TREE_TYPE (t))
1546                             == get_identifier (builtin_structptr_types[i].str)
1547                             && compparms (TREE_CHAIN (t1), TREE_CHAIN (t2)))
1548                           {
1549                             tree oldargs = TYPE_ARG_TYPES (TREE_TYPE (olddecl));
1550
1551                             TYPE_ARG_TYPES (TREE_TYPE (olddecl))
1552                               = TYPE_ARG_TYPES (TREE_TYPE (newdecl));
1553                             types_match = decls_match (newdecl, olddecl);
1554                             if (types_match)
1555                               return duplicate_decls (newdecl, olddecl,
1556                                                       hiding, was_hidden);
1557                             TYPE_ARG_TYPES (TREE_TYPE (olddecl)) = oldargs;
1558                           }
1559                         goto next_arg;
1560                       }
1561
1562                   if (! same_type_p (TREE_VALUE (t1), TREE_VALUE (t2)))
1563                     break;
1564                 next_arg:;
1565                 }
1566
1567               warning_at (newdecl_loc,
1568                           OPT_Wbuiltin_declaration_mismatch,
1569                           "declaration of %q#D conflicts with built-in "
1570                           "declaration %q#D", newdecl, olddecl);
1571             }
1572           else if ((DECL_EXTERN_C_P (newdecl)
1573                     && DECL_EXTERN_C_P (olddecl))
1574                    || compparms (TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1575                                  TYPE_ARG_TYPES (TREE_TYPE (olddecl))))
1576             {
1577               /* Don't really override olddecl for __* prefixed builtins
1578                  except for __[^b]*_chk, the compiler might be using those
1579                  explicitly.  */
1580               if (fndecl_built_in_p (olddecl))
1581                 {
1582                   tree id = DECL_NAME (olddecl);
1583                   const char *name = IDENTIFIER_POINTER (id);
1584                   size_t len;
1585
1586                   if (name[0] == '_'
1587                       && name[1] == '_'
1588                       && (strncmp (name + 2, "builtin_",
1589                                    strlen ("builtin_")) == 0
1590                           || (len = strlen (name)) <= strlen ("___chk")
1591                           || memcmp (name + len - strlen ("_chk"),
1592                                      "_chk", strlen ("_chk") + 1) != 0))
1593                     {
1594                       if (DECL_INITIAL (newdecl))
1595                         {
1596                           error_at (newdecl_loc,
1597                                     "definition of %q#D ambiguates built-in "
1598                                     "declaration %q#D", newdecl, olddecl);
1599                           return error_mark_node;
1600                         }
1601                       auto_diagnostic_group d;
1602                       if (permerror (newdecl_loc,
1603                                      "new declaration %q#D ambiguates built-in"
1604                                      " declaration %q#D", newdecl, olddecl)
1605                           && flag_permissive)
1606                         inform (newdecl_loc,
1607                                 "ignoring the %q#D declaration", newdecl);
1608                       return flag_permissive ? olddecl : error_mark_node;
1609                     }
1610                 }
1611
1612               /* A near match; override the builtin.  */
1613
1614               if (TREE_PUBLIC (newdecl))
1615                 warning_at (newdecl_loc,
1616                             OPT_Wbuiltin_declaration_mismatch,
1617                             "new declaration %q#D ambiguates built-in "
1618                             "declaration %q#D", newdecl, olddecl);
1619               else
1620                 warning (OPT_Wshadow, 
1621                          fndecl_built_in_p (olddecl)
1622                          ? G_("shadowing built-in function %q#D")
1623                          : G_("shadowing library function %q#D"), olddecl);
1624             }
1625           else
1626             /* Discard the old built-in function.  */
1627             return NULL_TREE;
1628
1629           /* Replace the old RTL to avoid problems with inlining.  */
1630           COPY_DECL_RTL (newdecl, olddecl);
1631         }
1632       /* Even if the types match, prefer the new declarations type for
1633          built-ins which have not been explicitly declared, for
1634          exception lists, etc...  */
1635       else if (DECL_IS_BUILTIN (olddecl))
1636         {
1637           tree type = TREE_TYPE (newdecl);
1638           tree attribs = (*targetm.merge_type_attributes)
1639             (TREE_TYPE (olddecl), type);
1640
1641           type = cp_build_type_attribute_variant (type, attribs);
1642           TREE_TYPE (newdecl) = TREE_TYPE (olddecl) = type;
1643         }
1644
1645       /* If a function is explicitly declared "throw ()", propagate that to
1646          the corresponding builtin.  */
1647       if (DECL_BUILT_IN_CLASS (olddecl) == BUILT_IN_NORMAL
1648           && was_hidden
1649           && TREE_NOTHROW (newdecl)
1650           && !TREE_NOTHROW (olddecl))
1651         {
1652           enum built_in_function fncode = DECL_FUNCTION_CODE (olddecl);
1653           tree tmpdecl = builtin_decl_explicit (fncode);
1654           if (tmpdecl && tmpdecl != olddecl && types_match)
1655             TREE_NOTHROW (tmpdecl)  = 1;
1656         }
1657
1658       /* Whether or not the builtin can throw exceptions has no
1659          bearing on this declarator.  */
1660       TREE_NOTHROW (olddecl) = 0;
1661
1662       if (DECL_THIS_STATIC (newdecl) && !DECL_THIS_STATIC (olddecl))
1663         {
1664           /* If a builtin function is redeclared as `static', merge
1665              the declarations, but make the original one static.  */
1666           DECL_THIS_STATIC (olddecl) = 1;
1667           TREE_PUBLIC (olddecl) = 0;
1668
1669           /* Make the old declaration consistent with the new one so
1670              that all remnants of the builtin-ness of this function
1671              will be banished.  */
1672           SET_DECL_LANGUAGE (olddecl, DECL_LANGUAGE (newdecl));
1673           COPY_DECL_RTL (newdecl, olddecl);
1674         }
1675     }
1676   else if (TREE_CODE (olddecl) != TREE_CODE (newdecl))
1677     {
1678       /* C++ Standard, 3.3, clause 4:
1679          "[Note: a namespace name or a class template name must be unique
1680          in its declarative region (7.3.2, clause 14). ]"  */
1681       if (TREE_CODE (olddecl) == NAMESPACE_DECL
1682           || TREE_CODE (newdecl) == NAMESPACE_DECL)
1683         /* Namespace conflicts with not namespace.  */;
1684       else if (DECL_TYPE_TEMPLATE_P (olddecl)
1685                || DECL_TYPE_TEMPLATE_P (newdecl))
1686         /* Class template conflicts.  */;
1687       else if ((TREE_CODE (olddecl) == TEMPLATE_DECL
1688                 && DECL_TEMPLATE_RESULT (olddecl)
1689                 && TREE_CODE (DECL_TEMPLATE_RESULT (olddecl)) == VAR_DECL)
1690                || (TREE_CODE (newdecl) == TEMPLATE_DECL
1691                    && DECL_TEMPLATE_RESULT (newdecl)
1692                    && TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == VAR_DECL))
1693         /* Variable template conflicts.  */;
1694       else if (concept_definition_p (olddecl)
1695                || concept_definition_p (newdecl))
1696         /* Concept conflicts.  */;
1697       else if ((TREE_CODE (newdecl) == FUNCTION_DECL
1698                 && DECL_FUNCTION_TEMPLATE_P (olddecl))
1699                || (TREE_CODE (olddecl) == FUNCTION_DECL
1700                    && DECL_FUNCTION_TEMPLATE_P (newdecl)))
1701         {
1702           /* One is a function and the other is a template
1703              function.  */
1704           if (!UDLIT_OPER_P (DECL_NAME (newdecl)))
1705             return NULL_TREE;
1706
1707           /* There can only be one!  */
1708           if (TREE_CODE (newdecl) == TEMPLATE_DECL
1709               && check_raw_literal_operator (olddecl))
1710             error_at (newdecl_loc,
1711                       "literal operator %q#D conflicts with"
1712                       " raw literal operator", newdecl);
1713           else if (check_raw_literal_operator (newdecl))
1714             error_at (newdecl_loc,
1715                       "raw literal operator %q#D conflicts with"
1716                       " literal operator template", newdecl);
1717           else
1718             return NULL_TREE;
1719
1720           inform (olddecl_loc, "previous declaration %q#D", olddecl);
1721           return error_mark_node;
1722         }
1723       else if ((VAR_P (olddecl) && DECL_DECOMPOSITION_P (olddecl))
1724                || (VAR_P (newdecl) && DECL_DECOMPOSITION_P (newdecl)))
1725         /* A structured binding must be unique in its declarative region.  */;
1726       else if (DECL_IMPLICIT_TYPEDEF_P (olddecl)
1727                || DECL_IMPLICIT_TYPEDEF_P (newdecl))
1728         /* One is an implicit typedef, that's ok.  */
1729         return NULL_TREE;
1730
1731       error ("%q#D redeclared as different kind of entity", newdecl);
1732       inform (olddecl_loc, "previous declaration %q#D", olddecl);
1733
1734       return error_mark_node;
1735     }
1736   else if (!types_match)
1737     {
1738       if (CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl))
1739         /* These are certainly not duplicate declarations; they're
1740            from different scopes.  */
1741         return NULL_TREE;
1742
1743       if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1744         {
1745           tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1746           tree newres = DECL_TEMPLATE_RESULT (newdecl);
1747
1748           /* The name of a class template may not be declared to refer to
1749              any other template, class, function, object, namespace, value,
1750              or type in the same scope.  */
1751           if (TREE_CODE (oldres) == TYPE_DECL
1752               || TREE_CODE (newres) == TYPE_DECL)
1753             {
1754               error_at (newdecl_loc,
1755                         "conflicting declaration of template %q#D", newdecl);
1756               inform (olddecl_loc,
1757                       "previous declaration %q#D", olddecl);
1758               return error_mark_node;
1759             }
1760
1761           else if (TREE_CODE (oldres) == FUNCTION_DECL
1762                    && TREE_CODE (newres) == FUNCTION_DECL)
1763             {
1764               if (duplicate_function_template_decls (newdecl, olddecl))
1765                 return error_mark_node;
1766               return NULL_TREE;
1767             }
1768           else if (check_concept_refinement (olddecl, newdecl))
1769             return error_mark_node;
1770           return NULL_TREE;
1771         }
1772       if (TREE_CODE (newdecl) == FUNCTION_DECL)
1773         {
1774           if (DECL_EXTERN_C_P (newdecl) && DECL_EXTERN_C_P (olddecl))
1775             {
1776               error_at (newdecl_loc,
1777                         "conflicting declaration of C function %q#D",
1778                         newdecl);
1779               inform (olddecl_loc,
1780                       "previous declaration %q#D", olddecl);
1781               return NULL_TREE;
1782             }
1783           /* For function versions, params and types match, but they
1784              are not ambiguous.  */
1785           else if ((!DECL_FUNCTION_VERSIONED (newdecl)
1786                     && !DECL_FUNCTION_VERSIONED (olddecl))
1787                    // The functions have the same parameter types.
1788                    && compparms (TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1789                                  TYPE_ARG_TYPES (TREE_TYPE (olddecl)))
1790                    // And the same constraints.
1791                    && equivalently_constrained (newdecl, olddecl))
1792             {
1793               error_at (newdecl_loc,
1794                         "ambiguating new declaration of %q#D", newdecl);
1795               inform (olddecl_loc,
1796                       "old declaration %q#D", olddecl);
1797               return error_mark_node;
1798             }
1799           else
1800             return NULL_TREE;
1801         }
1802       else
1803         {
1804           error_at (newdecl_loc, "conflicting declaration %q#D", newdecl);
1805           inform (olddecl_loc,
1806                   "previous declaration as %q#D", olddecl);
1807           return error_mark_node;
1808         }
1809     }
1810   else if (TREE_CODE (newdecl) == FUNCTION_DECL
1811            && DECL_OMP_DECLARE_REDUCTION_P (newdecl))
1812     {
1813       /* OMP UDRs are never duplicates. */
1814       gcc_assert (DECL_OMP_DECLARE_REDUCTION_P (olddecl));
1815       error_at (newdecl_loc,
1816                 "redeclaration of %<pragma omp declare reduction%>");
1817       inform (olddecl_loc,
1818               "previous %<pragma omp declare reduction%> declaration");
1819       return error_mark_node;
1820     }
1821   else if (TREE_CODE (newdecl) == FUNCTION_DECL
1822             && ((DECL_TEMPLATE_SPECIALIZATION (olddecl)
1823                  && (!DECL_TEMPLATE_INFO (newdecl)
1824                      || (DECL_TI_TEMPLATE (newdecl)
1825                          != DECL_TI_TEMPLATE (olddecl))))
1826                 || (DECL_TEMPLATE_SPECIALIZATION (newdecl)
1827                     && (!DECL_TEMPLATE_INFO (olddecl)
1828                         || (DECL_TI_TEMPLATE (olddecl)
1829                             != DECL_TI_TEMPLATE (newdecl))))))
1830     /* It's OK to have a template specialization and a non-template
1831        with the same type, or to have specializations of two
1832        different templates with the same type.  Note that if one is a
1833        specialization, and the other is an instantiation of the same
1834        template, that we do not exit at this point.  That situation
1835        can occur if we instantiate a template class, and then
1836        specialize one of its methods.  This situation is valid, but
1837        the declarations must be merged in the usual way.  */
1838     return NULL_TREE;
1839   else if (TREE_CODE (newdecl) == FUNCTION_DECL
1840            && ((DECL_TEMPLATE_INSTANTIATION (olddecl)
1841                 && !DECL_USE_TEMPLATE (newdecl))
1842                || (DECL_TEMPLATE_INSTANTIATION (newdecl)
1843                    && !DECL_USE_TEMPLATE (olddecl))))
1844     /* One of the declarations is a template instantiation, and the
1845        other is not a template at all.  That's OK.  */
1846     return NULL_TREE;
1847   else if (TREE_CODE (newdecl) == NAMESPACE_DECL)
1848     {
1849       /* In [namespace.alias] we have:
1850
1851            In a declarative region, a namespace-alias-definition can be
1852            used to redefine a namespace-alias declared in that declarative
1853            region to refer only to the namespace to which it already
1854            refers.
1855
1856          Therefore, if we encounter a second alias directive for the same
1857          alias, we can just ignore the second directive.  */
1858       if (DECL_NAMESPACE_ALIAS (newdecl)
1859           && (DECL_NAMESPACE_ALIAS (newdecl)
1860               == DECL_NAMESPACE_ALIAS (olddecl)))
1861         return olddecl;
1862
1863       /* Leave it to update_binding to merge or report error.  */
1864       return NULL_TREE;
1865     }
1866   else
1867     {
1868       const char *errmsg = redeclaration_error_message (newdecl, olddecl);
1869       if (errmsg)
1870         {
1871           auto_diagnostic_group d;
1872           error_at (newdecl_loc, errmsg, newdecl);
1873           if (DECL_NAME (olddecl) != NULL_TREE)
1874             inform (olddecl_loc,
1875                     (DECL_INITIAL (olddecl) && namespace_bindings_p ())
1876                     ? G_("%q#D previously defined here")
1877                     : G_("%q#D previously declared here"), olddecl);
1878           return error_mark_node;
1879         }
1880       else if (TREE_CODE (olddecl) == FUNCTION_DECL
1881                && DECL_INITIAL (olddecl) != NULL_TREE
1882                && !prototype_p (TREE_TYPE (olddecl))
1883                && prototype_p (TREE_TYPE (newdecl)))
1884         {
1885           /* Prototype decl follows defn w/o prototype.  */
1886           auto_diagnostic_group d;
1887           if (warning_at (newdecl_loc, 0,
1888                           "prototype specified for %q#D", newdecl))
1889             inform (olddecl_loc,
1890                     "previous non-prototype definition here");
1891         }
1892       else if (VAR_OR_FUNCTION_DECL_P (olddecl)
1893                && DECL_LANGUAGE (newdecl) != DECL_LANGUAGE (olddecl))
1894         {
1895           /* [dcl.link]
1896              If two declarations of the same function or object
1897              specify different linkage-specifications ..., the program
1898              is ill-formed.... Except for functions with C++ linkage,
1899              a function declaration without a linkage specification
1900              shall not precede the first linkage specification for
1901              that function.  A function can be declared without a
1902              linkage specification after an explicit linkage
1903              specification has been seen; the linkage explicitly
1904              specified in the earlier declaration is not affected by
1905              such a function declaration.
1906
1907              DR 563 raises the question why the restrictions on
1908              functions should not also apply to objects.  Older
1909              versions of G++ silently ignore the linkage-specification
1910              for this example:
1911
1912                namespace N { 
1913                  extern int i;
1914                  extern "C" int i;
1915                }
1916
1917              which is clearly wrong.  Therefore, we now treat objects
1918              like functions.  */
1919           if (current_lang_depth () == 0)
1920             {
1921               /* There is no explicit linkage-specification, so we use
1922                  the linkage from the previous declaration.  */
1923               retrofit_lang_decl (newdecl);
1924               SET_DECL_LANGUAGE (newdecl, DECL_LANGUAGE (olddecl));
1925             }
1926           else
1927             {
1928               auto_diagnostic_group d;
1929               error_at (newdecl_loc,
1930                         "conflicting declaration of %q#D with %qL linkage",
1931                         newdecl, DECL_LANGUAGE (newdecl));
1932               inform (olddecl_loc,
1933                       "previous declaration with %qL linkage",
1934                       DECL_LANGUAGE (olddecl));
1935             }
1936         }
1937
1938       if (DECL_LANG_SPECIFIC (olddecl) && DECL_USE_TEMPLATE (olddecl))
1939         ;
1940       else if (TREE_CODE (olddecl) == FUNCTION_DECL)
1941         {
1942           /* Note: free functions, as TEMPLATE_DECLs, are handled below.  */
1943           if (DECL_FUNCTION_MEMBER_P (olddecl)
1944               && (/* grokfndecl passes member function templates too
1945                      as FUNCTION_DECLs.  */
1946                   DECL_TEMPLATE_INFO (olddecl)
1947                   /* C++11 8.3.6/6.
1948                      Default arguments for a member function of a class
1949                      template shall be specified on the initial declaration
1950                      of the member function within the class template.  */
1951                   || CLASSTYPE_TEMPLATE_INFO (CP_DECL_CONTEXT (olddecl))))
1952             check_redeclaration_no_default_args (newdecl);
1953           else
1954             {
1955               tree t1 = FUNCTION_FIRST_USER_PARMTYPE (olddecl);
1956               tree t2 = FUNCTION_FIRST_USER_PARMTYPE (newdecl);
1957               int i = 1;
1958
1959               for (; t1 && t1 != void_list_node;
1960                    t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2), i++)
1961                 if (TREE_PURPOSE (t1) && TREE_PURPOSE (t2))
1962                   {
1963                     if (simple_cst_equal (TREE_PURPOSE (t1),
1964                                           TREE_PURPOSE (t2)) == 1)
1965                       {
1966                         auto_diagnostic_group d;
1967                         if (permerror (newdecl_loc,
1968                                        "default argument given for parameter "
1969                                        "%d of %q#D", i, newdecl))
1970                           inform (olddecl_loc,
1971                                   "previous specification in %q#D here",
1972                                   olddecl);
1973                       }
1974                     else
1975                       {
1976                         auto_diagnostic_group d;
1977                         error_at (newdecl_loc,
1978                                   "default argument given for parameter %d "
1979                                   "of %q#D", i, newdecl);
1980                         inform (olddecl_loc,
1981                                 "previous specification in %q#D here",
1982                                 olddecl);
1983                       }
1984                   }
1985
1986               /* C++17 11.3.6/4: "If a friend declaration specifies a default
1987                  argument expression, that declaration... shall be the only
1988                  declaration of the function or function template in the
1989                  translation unit."  */
1990               check_no_redeclaration_friend_default_args
1991                 (olddecl, newdecl, was_hidden);
1992             }
1993         }
1994     }
1995
1996   /* Do not merge an implicit typedef with an explicit one.  In:
1997
1998        class A;
1999        ...
2000        typedef class A A __attribute__ ((foo));
2001
2002      the attribute should apply only to the typedef.  */
2003   if (TREE_CODE (olddecl) == TYPE_DECL
2004       && (DECL_IMPLICIT_TYPEDEF_P (olddecl)
2005           || DECL_IMPLICIT_TYPEDEF_P (newdecl)))
2006     return NULL_TREE;
2007
2008   if (!validate_constexpr_redeclaration (olddecl, newdecl))
2009     return error_mark_node;
2010
2011   /* We have committed to returning OLDDECL at this point.  */
2012
2013   /* If new decl is `static' and an `extern' was seen previously,
2014      warn about it.  */
2015   warn_extern_redeclared_static (newdecl, olddecl);
2016
2017   /* True to merge attributes between the declarations, false to
2018      set OLDDECL's attributes to those of NEWDECL (for template
2019      explicit specializations that specify their own attributes
2020      independent of those specified for the primary template).  */
2021   const bool merge_attr = (TREE_CODE (newdecl) != FUNCTION_DECL
2022                            || !DECL_TEMPLATE_SPECIALIZATION (newdecl)
2023                            || DECL_TEMPLATE_SPECIALIZATION (olddecl));
2024
2025   if (TREE_CODE (newdecl) == FUNCTION_DECL)
2026     {
2027       if (merge_attr)
2028         {
2029           if (diagnose_mismatched_attributes (olddecl, newdecl))
2030             inform (olddecl_loc, DECL_INITIAL (olddecl)
2031                     ? G_("previous definition of %qD here")
2032                     : G_("previous declaration of %qD here"), olddecl);
2033
2034           /* [dcl.attr.noreturn]: The first declaration of a function shall
2035              specify the noreturn attribute if any declaration of that function
2036              specifies the noreturn attribute.  */
2037           tree a;
2038           if (TREE_THIS_VOLATILE (newdecl)
2039               && !TREE_THIS_VOLATILE (olddecl)
2040               /* This applies to [[noreturn]] only, not its GNU variants.  */
2041               && (a = lookup_attribute ("noreturn", DECL_ATTRIBUTES (newdecl)))
2042               && cxx11_attribute_p (a)
2043               && get_attribute_namespace (a) == NULL_TREE)
2044             {
2045               error_at (newdecl_loc, "function %qD declared %<[[noreturn]]%> "
2046                         "but its first declaration was not", newdecl);
2047               inform (olddecl_loc, "previous declaration of %qD", olddecl);
2048             }
2049         }
2050
2051       /* Now that functions must hold information normally held
2052          by field decls, there is extra work to do so that
2053          declaration information does not get destroyed during
2054          definition.  */
2055       if (DECL_VINDEX (olddecl))
2056         DECL_VINDEX (newdecl) = DECL_VINDEX (olddecl);
2057       if (DECL_CONTEXT (olddecl))
2058         DECL_CONTEXT (newdecl) = DECL_CONTEXT (olddecl);
2059       DECL_STATIC_CONSTRUCTOR (newdecl) |= DECL_STATIC_CONSTRUCTOR (olddecl);
2060       DECL_STATIC_DESTRUCTOR (newdecl) |= DECL_STATIC_DESTRUCTOR (olddecl);
2061       DECL_PURE_VIRTUAL_P (newdecl) |= DECL_PURE_VIRTUAL_P (olddecl);
2062       DECL_VIRTUAL_P (newdecl) |= DECL_VIRTUAL_P (olddecl);
2063       DECL_INVALID_OVERRIDER_P (newdecl) |= DECL_INVALID_OVERRIDER_P (olddecl);
2064       DECL_FINAL_P (newdecl) |= DECL_FINAL_P (olddecl);
2065       DECL_OVERRIDE_P (newdecl) |= DECL_OVERRIDE_P (olddecl);
2066       DECL_THIS_STATIC (newdecl) |= DECL_THIS_STATIC (olddecl);
2067       DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (newdecl)
2068         |= DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (olddecl);
2069       if (DECL_OVERLOADED_OPERATOR_P (olddecl))
2070         DECL_OVERLOADED_OPERATOR_CODE_RAW (newdecl)
2071           = DECL_OVERLOADED_OPERATOR_CODE_RAW (olddecl);
2072       new_defines_function = DECL_INITIAL (newdecl) != NULL_TREE;
2073
2074       /* Optionally warn about more than one declaration for the same
2075          name, but don't warn about a function declaration followed by a
2076          definition.  */
2077       if (warn_redundant_decls && ! DECL_ARTIFICIAL (olddecl)
2078           && !(new_defines_function && DECL_INITIAL (olddecl) == NULL_TREE)
2079           /* Don't warn about extern decl followed by definition.  */
2080           && !(DECL_EXTERNAL (olddecl) && ! DECL_EXTERNAL (newdecl))
2081           /* Don't warn if at least one is/was hidden.  */
2082           && !(hiding || was_hidden)
2083           /* Don't warn about declaration followed by specialization.  */
2084           && (! DECL_TEMPLATE_SPECIALIZATION (newdecl)
2085               || DECL_TEMPLATE_SPECIALIZATION (olddecl)))
2086         {
2087           auto_diagnostic_group d;
2088           if (warning_at (newdecl_loc,
2089                           OPT_Wredundant_decls,
2090                           "redundant redeclaration of %qD in same scope",
2091                           newdecl))
2092             inform (olddecl_loc,
2093                     "previous declaration of %qD", olddecl);
2094         }
2095
2096       /* [dcl.fct.def.delete] A deleted definition of a function shall be the
2097          first declaration of the function or, for an explicit specialization
2098          of a function template, the first declaration of that
2099          specialization.  */
2100       if (!(DECL_TEMPLATE_INSTANTIATION (olddecl)
2101             && DECL_TEMPLATE_SPECIALIZATION (newdecl)))
2102         {
2103           if (DECL_DELETED_FN (newdecl))
2104             {
2105               auto_diagnostic_group d;
2106               pedwarn (newdecl_loc, OPT_Wpedantic,
2107                        "deleted definition of %qD is not first declaration",
2108                        newdecl);
2109               inform (olddecl_loc,
2110                       "previous declaration of %qD", olddecl);
2111             }
2112           DECL_DELETED_FN (newdecl) |= DECL_DELETED_FN (olddecl);
2113         }
2114     }
2115
2116   /* Deal with C++: must preserve virtual function table size.  */
2117   if (TREE_CODE (olddecl) == TYPE_DECL)
2118     {
2119       tree newtype = TREE_TYPE (newdecl);
2120       tree oldtype = TREE_TYPE (olddecl);
2121
2122       if (newtype != error_mark_node && oldtype != error_mark_node
2123           && TYPE_LANG_SPECIFIC (newtype) && TYPE_LANG_SPECIFIC (oldtype))
2124         CLASSTYPE_FRIEND_CLASSES (newtype)
2125           = CLASSTYPE_FRIEND_CLASSES (oldtype);
2126
2127       DECL_ORIGINAL_TYPE (newdecl) = DECL_ORIGINAL_TYPE (olddecl);
2128     }
2129
2130   /* Copy all the DECL_... slots specified in the new decl except for
2131      any that we copy here from the old type.  */
2132   if (merge_attr)
2133     DECL_ATTRIBUTES (newdecl)
2134       = (*targetm.merge_decl_attributes) (olddecl, newdecl);
2135   else
2136     DECL_ATTRIBUTES (olddecl) = DECL_ATTRIBUTES (newdecl);
2137
2138   if (DECL_DECLARES_FUNCTION_P (olddecl))
2139     {
2140       olddecl_friend = DECL_FRIEND_P (STRIP_TEMPLATE (olddecl));
2141       olddecl_hidden_friend = olddecl_friend && was_hidden;
2142     }
2143
2144   if (TREE_CODE (newdecl) == TEMPLATE_DECL)
2145     {
2146       tree old_result = DECL_TEMPLATE_RESULT (olddecl);
2147       tree new_result = DECL_TEMPLATE_RESULT (newdecl);
2148       TREE_TYPE (olddecl) = TREE_TYPE (old_result);
2149
2150       /* The new decl should not already have gathered any
2151          specializations.  */
2152       gcc_assert (!DECL_TEMPLATE_SPECIALIZATIONS (newdecl));
2153
2154       DECL_ATTRIBUTES (old_result)
2155         = (*targetm.merge_decl_attributes) (old_result, new_result);
2156
2157       if (DECL_FUNCTION_TEMPLATE_P (newdecl))
2158         {
2159           if (DECL_SOURCE_LOCATION (newdecl)
2160               != DECL_SOURCE_LOCATION (olddecl))
2161             {
2162               /* Per C++11 8.3.6/4, default arguments cannot be added in
2163                  later declarations of a function template.  */
2164               check_redeclaration_no_default_args (newdecl);
2165               /* C++17 11.3.6/4: "If a friend declaration specifies a default
2166                  argument expression, that declaration... shall be the only
2167                  declaration of the function or function template in the
2168                  translation unit."  */
2169               check_no_redeclaration_friend_default_args
2170                 (old_result, new_result, olddecl_hidden_friend);
2171             }
2172
2173           check_default_args (newdecl);
2174
2175           if (GNU_INLINE_P (old_result) != GNU_INLINE_P (new_result)
2176               && DECL_INITIAL (new_result))
2177             {
2178               if (DECL_INITIAL (old_result))
2179                 DECL_UNINLINABLE (old_result) = 1;
2180               else
2181                 DECL_UNINLINABLE (old_result) = DECL_UNINLINABLE (new_result);
2182               DECL_EXTERNAL (old_result) = DECL_EXTERNAL (new_result);
2183               DECL_NOT_REALLY_EXTERN (old_result)
2184                 = DECL_NOT_REALLY_EXTERN (new_result);
2185               DECL_INTERFACE_KNOWN (old_result)
2186                 = DECL_INTERFACE_KNOWN (new_result);
2187               DECL_DECLARED_INLINE_P (old_result)
2188                 = DECL_DECLARED_INLINE_P (new_result);
2189               DECL_DISREGARD_INLINE_LIMITS (old_result)
2190                 |= DECL_DISREGARD_INLINE_LIMITS (new_result);
2191
2192             }
2193           else
2194             {
2195               DECL_DECLARED_INLINE_P (old_result)
2196                 |= DECL_DECLARED_INLINE_P (new_result);
2197               DECL_DISREGARD_INLINE_LIMITS (old_result)
2198                 |= DECL_DISREGARD_INLINE_LIMITS (new_result);
2199               check_redeclaration_exception_specification (newdecl, olddecl);
2200
2201               merge_attribute_bits (new_result, old_result);
2202             }
2203         }
2204
2205       /* If the new declaration is a definition, update the file and
2206          line information on the declaration, and also make
2207          the old declaration the same definition.  */
2208       if (DECL_INITIAL (new_result) != NULL_TREE)
2209         {
2210           DECL_SOURCE_LOCATION (olddecl)
2211             = DECL_SOURCE_LOCATION (old_result)
2212             = DECL_SOURCE_LOCATION (newdecl);
2213           DECL_INITIAL (old_result) = DECL_INITIAL (new_result);
2214           if (DECL_FUNCTION_TEMPLATE_P (newdecl))
2215             {
2216               tree parm;
2217               DECL_ARGUMENTS (old_result)
2218                 = DECL_ARGUMENTS (new_result);
2219               for (parm = DECL_ARGUMENTS (old_result); parm;
2220                    parm = DECL_CHAIN (parm))
2221                 DECL_CONTEXT (parm) = old_result;
2222             }
2223         }
2224
2225       return olddecl;
2226     }
2227
2228   if (types_match)
2229     {
2230       if (TREE_CODE (newdecl) == FUNCTION_DECL)
2231         check_redeclaration_exception_specification (newdecl, olddecl);
2232
2233       /* Automatically handles default parameters.  */
2234       tree oldtype = TREE_TYPE (olddecl);
2235       tree newtype;
2236
2237       /* For typedefs use the old type, as the new type's DECL_NAME points
2238          at newdecl, which will be ggc_freed.  */
2239       if (TREE_CODE (newdecl) == TYPE_DECL)
2240         {
2241           /* But NEWTYPE might have an attribute, honor that.  */
2242           tree tem = TREE_TYPE (newdecl);
2243           newtype = oldtype;
2244
2245           if (TYPE_USER_ALIGN (tem))
2246             {
2247               if (TYPE_ALIGN (tem) > TYPE_ALIGN (newtype))
2248                 SET_TYPE_ALIGN (newtype, TYPE_ALIGN (tem));
2249               TYPE_USER_ALIGN (newtype) = true;
2250             }
2251
2252           /* And remove the new type from the variants list.  */
2253           if (TYPE_NAME (TREE_TYPE (newdecl)) == newdecl)
2254             {
2255               tree remove = TREE_TYPE (newdecl);
2256               if (TYPE_MAIN_VARIANT (remove) == remove)
2257                 {
2258                   gcc_assert (TYPE_NEXT_VARIANT (remove) == NULL_TREE);
2259                   /* If remove is the main variant, no need to remove that
2260                      from the list.  One of the DECL_ORIGINAL_TYPE
2261                      variants, e.g. created for aligned attribute, might still
2262                      refer to the newdecl TYPE_DECL though, so remove that one
2263                      in that case.  */
2264                   if (tree orig = DECL_ORIGINAL_TYPE (newdecl))
2265                     if (orig != remove)
2266                       for (tree t = TYPE_MAIN_VARIANT (orig); t;
2267                            t = TYPE_MAIN_VARIANT (t))
2268                         if (TYPE_NAME (TYPE_NEXT_VARIANT (t)) == newdecl)
2269                           {
2270                             TYPE_NEXT_VARIANT (t)
2271                               = TYPE_NEXT_VARIANT (TYPE_NEXT_VARIANT (t));
2272                             break;
2273                           }
2274                 }           
2275               else
2276                 for (tree t = TYPE_MAIN_VARIANT (remove); ;
2277                      t = TYPE_NEXT_VARIANT (t))
2278                   if (TYPE_NEXT_VARIANT (t) == remove)
2279                     {
2280                       TYPE_NEXT_VARIANT (t) = TYPE_NEXT_VARIANT (remove);
2281                       break;
2282                     }
2283             }
2284         }
2285       else if (merge_attr)
2286         newtype = merge_types (TREE_TYPE (newdecl), TREE_TYPE (olddecl));
2287       else
2288         newtype = TREE_TYPE (newdecl);
2289
2290       if (VAR_P (newdecl))
2291         {
2292           DECL_THIS_EXTERN (newdecl) |= DECL_THIS_EXTERN (olddecl);
2293           /* For already initialized vars, TREE_READONLY could have been
2294              cleared in cp_finish_decl, because the var needs runtime
2295              initialization or destruction.  Make sure not to set
2296              TREE_READONLY on it again.  */
2297           if (DECL_INITIALIZED_P (olddecl)
2298               && !DECL_EXTERNAL (olddecl)
2299               && !TREE_READONLY (olddecl))
2300             TREE_READONLY (newdecl) = 0;
2301           DECL_INITIALIZED_P (newdecl) |= DECL_INITIALIZED_P (olddecl);
2302           DECL_NONTRIVIALLY_INITIALIZED_P (newdecl)
2303             |= DECL_NONTRIVIALLY_INITIALIZED_P (olddecl);
2304           if (DECL_DEPENDENT_INIT_P (olddecl))
2305             SET_DECL_DEPENDENT_INIT_P (newdecl, true);
2306           DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (newdecl)
2307             |= DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (olddecl);
2308           DECL_DECLARED_CONSTEXPR_P (newdecl)
2309             |= DECL_DECLARED_CONSTEXPR_P (olddecl);
2310           DECL_DECLARED_CONSTINIT_P (newdecl)
2311             |= DECL_DECLARED_CONSTINIT_P (olddecl);
2312
2313           /* Merge the threadprivate attribute from OLDDECL into NEWDECL.  */
2314           if (DECL_LANG_SPECIFIC (olddecl)
2315               && CP_DECL_THREADPRIVATE_P (olddecl))
2316             {
2317               /* Allocate a LANG_SPECIFIC structure for NEWDECL, if needed.  */
2318               retrofit_lang_decl (newdecl);
2319               CP_DECL_THREADPRIVATE_P (newdecl) = 1;
2320             }
2321         }
2322
2323       /* An explicit specialization of a function template or of a member
2324          function of a class template can be declared transaction_safe
2325          independently of whether the corresponding template entity is declared
2326          transaction_safe. */
2327       if (flag_tm && TREE_CODE (newdecl) == FUNCTION_DECL
2328           && DECL_TEMPLATE_INSTANTIATION (olddecl)
2329           && DECL_TEMPLATE_SPECIALIZATION (newdecl)
2330           && tx_safe_fn_type_p (newtype)
2331           && !tx_safe_fn_type_p (TREE_TYPE (newdecl)))
2332         newtype = tx_unsafe_fn_variant (newtype);
2333
2334       TREE_TYPE (newdecl) = TREE_TYPE (olddecl) = newtype;
2335
2336       if (TREE_CODE (newdecl) == FUNCTION_DECL)
2337         check_default_args (newdecl);
2338
2339       /* Lay the type out, unless already done.  */
2340       if (! same_type_p (newtype, oldtype)
2341           && TREE_TYPE (newdecl) != error_mark_node
2342           && !(processing_template_decl && uses_template_parms (newdecl)))
2343         layout_type (TREE_TYPE (newdecl));
2344
2345       if ((VAR_P (newdecl)
2346            || TREE_CODE (newdecl) == PARM_DECL
2347            || TREE_CODE (newdecl) == RESULT_DECL
2348            || TREE_CODE (newdecl) == FIELD_DECL
2349            || TREE_CODE (newdecl) == TYPE_DECL)
2350           && !(processing_template_decl && uses_template_parms (newdecl)))
2351         layout_decl (newdecl, 0);
2352
2353       /* Merge deprecatedness.  */
2354       if (TREE_DEPRECATED (newdecl))
2355         TREE_DEPRECATED (olddecl) = 1;
2356
2357       /* Preserve function specific target and optimization options */
2358       if (TREE_CODE (newdecl) == FUNCTION_DECL)
2359         {
2360           if (DECL_FUNCTION_SPECIFIC_TARGET (olddecl)
2361               && !DECL_FUNCTION_SPECIFIC_TARGET (newdecl))
2362             DECL_FUNCTION_SPECIFIC_TARGET (newdecl)
2363               = DECL_FUNCTION_SPECIFIC_TARGET (olddecl);
2364
2365           if (DECL_FUNCTION_SPECIFIC_OPTIMIZATION (olddecl)
2366               && !DECL_FUNCTION_SPECIFIC_OPTIMIZATION (newdecl))
2367             DECL_FUNCTION_SPECIFIC_OPTIMIZATION (newdecl)
2368               = DECL_FUNCTION_SPECIFIC_OPTIMIZATION (olddecl);
2369         }
2370       else
2371         {
2372           /* Merge the const type qualifier.  */
2373           if (TREE_READONLY (newdecl))
2374             TREE_READONLY (olddecl) = 1;
2375           /* Merge the volatile type qualifier.  */
2376           if (TREE_THIS_VOLATILE (newdecl))
2377             TREE_THIS_VOLATILE (olddecl) = 1;
2378         }
2379
2380       /* Merge the initialization information.  */
2381       if (DECL_INITIAL (newdecl) == NULL_TREE
2382           && DECL_INITIAL (olddecl) != NULL_TREE)
2383         {
2384           DECL_INITIAL (newdecl) = DECL_INITIAL (olddecl);
2385           DECL_SOURCE_LOCATION (newdecl) = DECL_SOURCE_LOCATION (olddecl);
2386           if (TREE_CODE (newdecl) == FUNCTION_DECL)
2387             {
2388               DECL_SAVED_TREE (newdecl) = DECL_SAVED_TREE (olddecl);
2389               DECL_STRUCT_FUNCTION (newdecl) = DECL_STRUCT_FUNCTION (olddecl);
2390             }
2391         }
2392
2393       if (TREE_CODE (newdecl) == FUNCTION_DECL)
2394         {
2395           DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (newdecl)
2396             |= DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (olddecl);
2397           DECL_NO_LIMIT_STACK (newdecl) |= DECL_NO_LIMIT_STACK (olddecl);
2398           if (DECL_IS_OPERATOR_NEW_P (olddecl))
2399             DECL_SET_IS_OPERATOR_NEW (newdecl, true);
2400           DECL_LOOPING_CONST_OR_PURE_P (newdecl)
2401             |= DECL_LOOPING_CONST_OR_PURE_P (olddecl);
2402           DECL_IS_REPLACEABLE_OPERATOR (newdecl)
2403             |= DECL_IS_REPLACEABLE_OPERATOR (olddecl);
2404
2405           if (merge_attr)
2406             merge_attribute_bits (newdecl, olddecl);
2407           else
2408             {
2409               /* Merge the noreturn bit.  */
2410               TREE_THIS_VOLATILE (olddecl) = TREE_THIS_VOLATILE (newdecl);
2411               TREE_READONLY (olddecl) = TREE_READONLY (newdecl);
2412               TREE_NOTHROW (olddecl) = TREE_NOTHROW (newdecl);
2413               DECL_IS_MALLOC (olddecl) = DECL_IS_MALLOC (newdecl);
2414               DECL_PURE_P (olddecl) = DECL_PURE_P (newdecl);
2415             }
2416           /* Keep the old RTL.  */
2417           COPY_DECL_RTL (olddecl, newdecl);
2418         }
2419       else if (VAR_P (newdecl)
2420                && (DECL_SIZE (olddecl) || !DECL_SIZE (newdecl)))
2421         {
2422           /* Keep the old RTL.  We cannot keep the old RTL if the old
2423              declaration was for an incomplete object and the new
2424              declaration is not since many attributes of the RTL will
2425              change.  */
2426           COPY_DECL_RTL (olddecl, newdecl);
2427         }
2428     }
2429   /* If cannot merge, then use the new type and qualifiers,
2430      and don't preserve the old rtl.  */
2431   else
2432     {
2433       /* Clean out any memory we had of the old declaration.  */
2434       tree oldstatic = value_member (olddecl, static_aggregates);
2435       if (oldstatic)
2436         TREE_VALUE (oldstatic) = error_mark_node;
2437
2438       TREE_TYPE (olddecl) = TREE_TYPE (newdecl);
2439       TREE_READONLY (olddecl) = TREE_READONLY (newdecl);
2440       TREE_THIS_VOLATILE (olddecl) = TREE_THIS_VOLATILE (newdecl);
2441       TREE_NOTHROW (olddecl) = TREE_NOTHROW (newdecl);
2442       TREE_SIDE_EFFECTS (olddecl) = TREE_SIDE_EFFECTS (newdecl);
2443     }
2444
2445   /* Merge the storage class information.  */
2446   merge_weak (newdecl, olddecl);
2447
2448   DECL_DEFER_OUTPUT (newdecl) |= DECL_DEFER_OUTPUT (olddecl);
2449   TREE_PUBLIC (newdecl) = TREE_PUBLIC (olddecl);
2450   TREE_STATIC (olddecl) = TREE_STATIC (newdecl) |= TREE_STATIC (olddecl);
2451   if (! DECL_EXTERNAL (olddecl))
2452     DECL_EXTERNAL (newdecl) = 0;
2453   if (! DECL_COMDAT (olddecl))
2454     DECL_COMDAT (newdecl) = 0;
2455
2456   new_template_info = NULL_TREE;
2457   if (DECL_LANG_SPECIFIC (newdecl) && DECL_LANG_SPECIFIC (olddecl))
2458     {
2459       bool new_redefines_gnu_inline = false;
2460
2461       if (new_defines_function
2462           && ((DECL_INTERFACE_KNOWN (olddecl)
2463                && TREE_CODE (olddecl) == FUNCTION_DECL)
2464               || (TREE_CODE (olddecl) == TEMPLATE_DECL
2465                   && (TREE_CODE (DECL_TEMPLATE_RESULT (olddecl))
2466                       == FUNCTION_DECL))))
2467         new_redefines_gnu_inline = GNU_INLINE_P (STRIP_TEMPLATE (olddecl));
2468
2469       if (!new_redefines_gnu_inline)
2470         {
2471           DECL_INTERFACE_KNOWN (newdecl) |= DECL_INTERFACE_KNOWN (olddecl);
2472           DECL_NOT_REALLY_EXTERN (newdecl) |= DECL_NOT_REALLY_EXTERN (olddecl);
2473           DECL_COMDAT (newdecl) |= DECL_COMDAT (olddecl);
2474         }
2475       DECL_TEMPLATE_INSTANTIATED (newdecl)
2476         |= DECL_TEMPLATE_INSTANTIATED (olddecl);
2477       DECL_ODR_USED (newdecl) |= DECL_ODR_USED (olddecl);
2478
2479       /* If the OLDDECL is an instantiation and/or specialization,
2480          then the NEWDECL must be too.  But, it may not yet be marked
2481          as such if the caller has created NEWDECL, but has not yet
2482          figured out that it is a redeclaration.  */
2483       if (!DECL_USE_TEMPLATE (newdecl))
2484         DECL_USE_TEMPLATE (newdecl) = DECL_USE_TEMPLATE (olddecl);
2485
2486       /* Don't really know how much of the language-specific
2487          values we should copy from old to new.  */
2488       DECL_IN_AGGR_P (newdecl) = DECL_IN_AGGR_P (olddecl);
2489       DECL_INITIALIZED_IN_CLASS_P (newdecl)
2490         |= DECL_INITIALIZED_IN_CLASS_P (olddecl);
2491
2492       if (LANG_DECL_HAS_MIN (newdecl))
2493         {
2494           DECL_ACCESS (newdecl) = DECL_ACCESS (olddecl);
2495           if (DECL_TEMPLATE_INFO (newdecl))
2496             {
2497               new_template_info = DECL_TEMPLATE_INFO (newdecl);
2498               if (DECL_TEMPLATE_INSTANTIATION (olddecl)
2499                   && DECL_TEMPLATE_SPECIALIZATION (newdecl))
2500                 /* Remember the presence of explicit specialization args.  */
2501                 TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (olddecl))
2502                   = TINFO_USED_TEMPLATE_ID (new_template_info);
2503             }
2504           DECL_TEMPLATE_INFO (newdecl) = DECL_TEMPLATE_INFO (olddecl);
2505         }
2506
2507       if (DECL_DECLARES_FUNCTION_P (newdecl))
2508         {
2509           /* Only functions have these fields.  */
2510           DECL_NONCONVERTING_P (newdecl) = DECL_NONCONVERTING_P (olddecl);
2511           DECL_BEFRIENDING_CLASSES (newdecl)
2512             = chainon (DECL_BEFRIENDING_CLASSES (newdecl),
2513                        DECL_BEFRIENDING_CLASSES (olddecl));
2514           /* DECL_THUNKS is only valid for virtual functions,
2515              otherwise it is a DECL_FRIEND_CONTEXT.  */
2516           if (DECL_VIRTUAL_P (newdecl))
2517             SET_DECL_THUNKS (newdecl, DECL_THUNKS (olddecl));
2518         }
2519       else if (VAR_P (newdecl))
2520         {
2521           /* Only variables have this field.  */
2522           if (VAR_HAD_UNKNOWN_BOUND (olddecl))
2523             SET_VAR_HAD_UNKNOWN_BOUND (newdecl);
2524         }
2525     }
2526
2527   if (TREE_CODE (newdecl) == FUNCTION_DECL)
2528     {
2529       tree parm;
2530
2531       /* Merge parameter attributes. */
2532       tree oldarg, newarg;
2533       for (oldarg = DECL_ARGUMENTS(olddecl), newarg = DECL_ARGUMENTS(newdecl);
2534            oldarg && newarg;
2535            oldarg = DECL_CHAIN(oldarg), newarg = DECL_CHAIN(newarg))
2536         {
2537           DECL_ATTRIBUTES (newarg)
2538             = (*targetm.merge_decl_attributes) (oldarg, newarg);
2539           DECL_ATTRIBUTES (oldarg) = DECL_ATTRIBUTES (newarg);
2540         }
2541
2542       if (DECL_TEMPLATE_INSTANTIATION (olddecl)
2543           && !DECL_TEMPLATE_INSTANTIATION (newdecl))
2544         {
2545           /* If newdecl is not a specialization, then it is not a
2546              template-related function at all.  And that means that we
2547              should have exited above, returning 0.  */
2548           gcc_assert (DECL_TEMPLATE_SPECIALIZATION (newdecl));
2549
2550           if (DECL_ODR_USED (olddecl))
2551             /* From [temp.expl.spec]:
2552
2553                If a template, a member template or the member of a class
2554                template is explicitly specialized then that
2555                specialization shall be declared before the first use of
2556                that specialization that would cause an implicit
2557                instantiation to take place, in every translation unit in
2558                which such a use occurs.  */
2559             error ("explicit specialization of %qD after first use",
2560                       olddecl);
2561
2562           SET_DECL_TEMPLATE_SPECIALIZATION (olddecl);
2563           DECL_COMDAT (newdecl) = (TREE_PUBLIC (newdecl)
2564                                    && DECL_DECLARED_INLINE_P (newdecl));
2565
2566           /* Don't propagate visibility from the template to the
2567              specialization here.  We'll do that in determine_visibility if
2568              appropriate.  */
2569           DECL_VISIBILITY_SPECIFIED (olddecl) = 0;
2570
2571           /* [temp.expl.spec/14] We don't inline explicit specialization
2572              just because the primary template says so.  */
2573           gcc_assert (!merge_attr);
2574
2575           DECL_DECLARED_INLINE_P (olddecl)
2576             = DECL_DECLARED_INLINE_P (newdecl);
2577
2578           DECL_DISREGARD_INLINE_LIMITS (olddecl)
2579             = DECL_DISREGARD_INLINE_LIMITS (newdecl);
2580
2581           DECL_UNINLINABLE (olddecl) = DECL_UNINLINABLE (newdecl);
2582         }
2583       else if (new_defines_function && DECL_INITIAL (olddecl))
2584         {
2585           /* Never inline re-defined extern inline functions.
2586              FIXME: this could be better handled by keeping both
2587              function as separate declarations.  */
2588           DECL_UNINLINABLE (newdecl) = 1;
2589         }
2590       else
2591         {
2592           if (DECL_PENDING_INLINE_P (olddecl))
2593             {
2594               DECL_PENDING_INLINE_P (newdecl) = 1;
2595               DECL_PENDING_INLINE_INFO (newdecl)
2596                 = DECL_PENDING_INLINE_INFO (olddecl);
2597             }
2598           else if (DECL_PENDING_INLINE_P (newdecl))
2599             ;
2600           else if (DECL_SAVED_AUTO_RETURN_TYPE (newdecl) == NULL)
2601             DECL_SAVED_AUTO_RETURN_TYPE (newdecl)
2602               = DECL_SAVED_AUTO_RETURN_TYPE (olddecl);
2603
2604           DECL_DECLARED_INLINE_P (newdecl) |= DECL_DECLARED_INLINE_P (olddecl);
2605
2606           DECL_UNINLINABLE (newdecl) = DECL_UNINLINABLE (olddecl)
2607             = (DECL_UNINLINABLE (newdecl) || DECL_UNINLINABLE (olddecl));
2608
2609           DECL_DISREGARD_INLINE_LIMITS (newdecl)
2610             = DECL_DISREGARD_INLINE_LIMITS (olddecl)
2611             = (DECL_DISREGARD_INLINE_LIMITS (newdecl)
2612                || DECL_DISREGARD_INLINE_LIMITS (olddecl));
2613         }
2614
2615       /* Preserve abstractness on cloned [cd]tors.  */
2616       DECL_ABSTRACT_P (newdecl) = DECL_ABSTRACT_P (olddecl);
2617
2618       /* Update newdecl's parms to point at olddecl.  */
2619       for (parm = DECL_ARGUMENTS (newdecl); parm;
2620            parm = DECL_CHAIN (parm))
2621         DECL_CONTEXT (parm) = olddecl;
2622
2623       if (! types_match)
2624         {
2625           SET_DECL_LANGUAGE (olddecl, DECL_LANGUAGE (newdecl));
2626           COPY_DECL_ASSEMBLER_NAME (newdecl, olddecl);
2627           COPY_DECL_RTL (newdecl, olddecl);
2628         }
2629       if (! types_match || new_defines_function)
2630         {
2631           /* These need to be copied so that the names are available.
2632              Note that if the types do match, we'll preserve inline
2633              info and other bits, but if not, we won't.  */
2634           DECL_ARGUMENTS (olddecl) = DECL_ARGUMENTS (newdecl);
2635           DECL_RESULT (olddecl) = DECL_RESULT (newdecl);
2636         }
2637       /* If redeclaring a builtin function, it stays built in
2638          if newdecl is a gnu_inline definition, or if newdecl is just
2639          a declaration.  */
2640       if (fndecl_built_in_p (olddecl)
2641           && (new_defines_function ? GNU_INLINE_P (newdecl) : types_match))
2642         {
2643           copy_decl_built_in_function (newdecl, olddecl);
2644           /* If we're keeping the built-in definition, keep the rtl,
2645              regardless of declaration matches.  */
2646           COPY_DECL_RTL (olddecl, newdecl);
2647           if (DECL_BUILT_IN_CLASS (newdecl) == BUILT_IN_NORMAL)
2648             {
2649               enum built_in_function fncode = DECL_FUNCTION_CODE (newdecl);
2650               switch (fncode)
2651                 {
2652                   /* If a compatible prototype of these builtin functions
2653                      is seen, assume the runtime implements it with the
2654                      expected semantics.  */
2655                 case BUILT_IN_STPCPY:
2656                   if (builtin_decl_explicit_p (fncode))
2657                     set_builtin_decl_implicit_p (fncode, true);
2658                   break;
2659                 default:
2660                   if (builtin_decl_explicit_p (fncode))
2661                     set_builtin_decl_declared_p (fncode, true);
2662                   break;
2663                 }
2664
2665               copy_attributes_to_builtin (newdecl);
2666             }
2667         }
2668       if (new_defines_function)
2669         /* If defining a function declared with other language
2670            linkage, use the previously declared language linkage.  */
2671         SET_DECL_LANGUAGE (newdecl, DECL_LANGUAGE (olddecl));
2672       else if (types_match)
2673         {
2674           DECL_RESULT (newdecl) = DECL_RESULT (olddecl);
2675           /* Don't clear out the arguments if we're just redeclaring a
2676              function.  */
2677           if (DECL_ARGUMENTS (olddecl))
2678             DECL_ARGUMENTS (newdecl) = DECL_ARGUMENTS (olddecl);
2679         }
2680     }
2681   else if (TREE_CODE (newdecl) == NAMESPACE_DECL)
2682     NAMESPACE_LEVEL (newdecl) = NAMESPACE_LEVEL (olddecl);
2683
2684   /* Now preserve various other info from the definition.  */
2685   TREE_ADDRESSABLE (newdecl) = TREE_ADDRESSABLE (olddecl);
2686   TREE_ASM_WRITTEN (newdecl) = TREE_ASM_WRITTEN (olddecl);
2687   DECL_COMMON (newdecl) = DECL_COMMON (olddecl);
2688   COPY_DECL_ASSEMBLER_NAME (olddecl, newdecl);
2689
2690   /* Warn about conflicting visibility specifications.  */
2691   if (DECL_VISIBILITY_SPECIFIED (olddecl)
2692       && DECL_VISIBILITY_SPECIFIED (newdecl)
2693       && DECL_VISIBILITY (newdecl) != DECL_VISIBILITY (olddecl))
2694     {
2695       auto_diagnostic_group d;
2696       if (warning_at (newdecl_loc, OPT_Wattributes,
2697                       "%qD: visibility attribute ignored because it "
2698                       "conflicts with previous declaration", newdecl))
2699         inform (olddecl_loc,
2700                 "previous declaration of %qD", olddecl);
2701     }
2702   /* Choose the declaration which specified visibility.  */
2703   if (DECL_VISIBILITY_SPECIFIED (olddecl))
2704     {
2705       DECL_VISIBILITY (newdecl) = DECL_VISIBILITY (olddecl);
2706       DECL_VISIBILITY_SPECIFIED (newdecl) = 1;
2707     }
2708   /* Init priority used to be merged from newdecl to olddecl by the memcpy,
2709      so keep this behavior.  */
2710   if (VAR_P (newdecl) && DECL_HAS_INIT_PRIORITY_P (newdecl))
2711     {
2712       SET_DECL_INIT_PRIORITY (olddecl, DECL_INIT_PRIORITY (newdecl));
2713       DECL_HAS_INIT_PRIORITY_P (olddecl) = 1;
2714     }
2715   /* Likewise for DECL_ALIGN, DECL_USER_ALIGN and DECL_PACKED.  */
2716   if (DECL_ALIGN (olddecl) > DECL_ALIGN (newdecl))
2717     {
2718       SET_DECL_ALIGN (newdecl, DECL_ALIGN (olddecl));
2719       DECL_USER_ALIGN (newdecl) |= DECL_USER_ALIGN (olddecl);
2720     }
2721   DECL_USER_ALIGN (olddecl) = DECL_USER_ALIGN (newdecl);
2722   if (DECL_WARN_IF_NOT_ALIGN (olddecl)
2723       > DECL_WARN_IF_NOT_ALIGN (newdecl))
2724     SET_DECL_WARN_IF_NOT_ALIGN (newdecl,
2725                                 DECL_WARN_IF_NOT_ALIGN (olddecl));
2726   if (TREE_CODE (newdecl) == FIELD_DECL)
2727     DECL_PACKED (olddecl) = DECL_PACKED (newdecl);
2728
2729   /* The DECL_LANG_SPECIFIC information in OLDDECL will be replaced
2730      with that from NEWDECL below.  */
2731   if (DECL_LANG_SPECIFIC (olddecl))
2732     {
2733       gcc_assert (DECL_LANG_SPECIFIC (olddecl)
2734                   != DECL_LANG_SPECIFIC (newdecl));
2735       ggc_free (DECL_LANG_SPECIFIC (olddecl));
2736     }
2737
2738   /* Merge the USED information.  */
2739   if (TREE_USED (olddecl))
2740     TREE_USED (newdecl) = 1;
2741   else if (TREE_USED (newdecl))
2742     TREE_USED (olddecl) = 1;
2743
2744   if (VAR_P (newdecl))
2745     {
2746       if (DECL_READ_P (olddecl))
2747         DECL_READ_P (newdecl) = 1;
2748       else if (DECL_READ_P (newdecl))
2749         DECL_READ_P (olddecl) = 1;
2750     }
2751
2752   if (DECL_PRESERVE_P (olddecl))
2753     DECL_PRESERVE_P (newdecl) = 1;
2754   else if (DECL_PRESERVE_P (newdecl))
2755     DECL_PRESERVE_P (olddecl) = 1;
2756
2757   /* Merge the DECL_FUNCTION_VERSIONED information.  newdecl will be copied
2758      to olddecl and deleted.  */
2759   if (TREE_CODE (newdecl) == FUNCTION_DECL
2760       && DECL_FUNCTION_VERSIONED (olddecl))
2761     {
2762       /* Set the flag for newdecl so that it gets copied to olddecl.  */
2763       DECL_FUNCTION_VERSIONED (newdecl) = 1;
2764       /* newdecl will be purged after copying to olddecl and is no longer
2765          a version.  */
2766       cgraph_node::delete_function_version_by_decl (newdecl);
2767     }
2768
2769   if (TREE_CODE (newdecl) == FUNCTION_DECL)
2770     {
2771       int function_size;
2772       struct symtab_node *snode = symtab_node::get (olddecl);
2773
2774       function_size = sizeof (struct tree_decl_common);
2775
2776       memcpy ((char *) olddecl + sizeof (struct tree_common),
2777               (char *) newdecl + sizeof (struct tree_common),
2778               function_size - sizeof (struct tree_common));
2779
2780       memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
2781               (char *) newdecl + sizeof (struct tree_decl_common),
2782               sizeof (struct tree_function_decl) - sizeof (struct tree_decl_common));
2783
2784       /* Preserve symtab node mapping.  */
2785       olddecl->decl_with_vis.symtab_node = snode;
2786
2787       if (new_template_info)
2788         /* If newdecl is a template instantiation, it is possible that
2789            the following sequence of events has occurred:
2790
2791            o A friend function was declared in a class template.  The
2792            class template was instantiated.
2793
2794            o The instantiation of the friend declaration was
2795            recorded on the instantiation list, and is newdecl.
2796
2797            o Later, however, instantiate_class_template called pushdecl
2798            on the newdecl to perform name injection.  But, pushdecl in
2799            turn called duplicate_decls when it discovered that another
2800            declaration of a global function with the same name already
2801            existed.
2802
2803            o Here, in duplicate_decls, we decided to clobber newdecl.
2804
2805            If we're going to do that, we'd better make sure that
2806            olddecl, and not newdecl, is on the list of
2807            instantiations so that if we try to do the instantiation
2808            again we won't get the clobbered declaration.  */
2809         reregister_specialization (newdecl,
2810                                    new_template_info,
2811                                    olddecl);
2812     }
2813   else
2814     {
2815       size_t size = tree_code_size (TREE_CODE (newdecl));
2816
2817       memcpy ((char *) olddecl + sizeof (struct tree_common),
2818               (char *) newdecl + sizeof (struct tree_common),
2819               sizeof (struct tree_decl_common) - sizeof (struct tree_common));
2820       switch (TREE_CODE (newdecl))
2821         {
2822         case LABEL_DECL:
2823         case VAR_DECL:
2824         case RESULT_DECL:
2825         case PARM_DECL:
2826         case FIELD_DECL:
2827         case TYPE_DECL:
2828         case CONST_DECL:
2829           {
2830             struct symtab_node *snode = NULL;
2831
2832             if (VAR_P (newdecl)
2833                 && (TREE_STATIC (olddecl) || TREE_PUBLIC (olddecl)
2834                     || DECL_EXTERNAL (olddecl)))
2835               snode = symtab_node::get (olddecl);
2836             memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
2837                     (char *) newdecl + sizeof (struct tree_decl_common),
2838                     size - sizeof (struct tree_decl_common)
2839                     + TREE_CODE_LENGTH (TREE_CODE (newdecl)) * sizeof (char *));
2840             if (VAR_P (newdecl))
2841               olddecl->decl_with_vis.symtab_node = snode;
2842           }
2843           break;
2844         default:
2845           memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
2846                   (char *) newdecl + sizeof (struct tree_decl_common),
2847                   sizeof (struct tree_decl_non_common) - sizeof (struct tree_decl_common)
2848                   + TREE_CODE_LENGTH (TREE_CODE (newdecl)) * sizeof (char *));
2849           break;
2850         }
2851     }
2852
2853   if (VAR_OR_FUNCTION_DECL_P (newdecl))
2854     {
2855       if (DECL_EXTERNAL (olddecl)
2856           || TREE_PUBLIC (olddecl)
2857           || TREE_STATIC (olddecl))
2858         {
2859           /* Merge the section attribute.
2860              We want to issue an error if the sections conflict but that must be
2861              done later in decl_attributes since we are called before attributes
2862              are assigned.  */
2863           if (DECL_SECTION_NAME (newdecl) != NULL)
2864             set_decl_section_name (olddecl, DECL_SECTION_NAME (newdecl));
2865
2866           if (DECL_ONE_ONLY (newdecl))
2867             {
2868               struct symtab_node *oldsym, *newsym;
2869               if (TREE_CODE (olddecl) == FUNCTION_DECL)
2870                 oldsym = cgraph_node::get_create (olddecl);
2871               else
2872                 oldsym = varpool_node::get_create (olddecl);
2873               newsym = symtab_node::get (newdecl);
2874               oldsym->set_comdat_group (newsym->get_comdat_group ());
2875             }
2876         }
2877
2878       if (VAR_P (newdecl)
2879           && CP_DECL_THREAD_LOCAL_P (newdecl))
2880         {
2881           CP_DECL_THREAD_LOCAL_P (olddecl) = true;
2882           if (!processing_template_decl)
2883             set_decl_tls_model (olddecl, DECL_TLS_MODEL (newdecl));
2884         }
2885     }
2886
2887   DECL_UID (olddecl) = olddecl_uid;
2888   if (olddecl_friend)
2889     DECL_FRIEND_P (olddecl) = true;
2890
2891   /* NEWDECL contains the merged attribute lists.
2892      Update OLDDECL to be the same.  */
2893   DECL_ATTRIBUTES (olddecl) = DECL_ATTRIBUTES (newdecl);
2894
2895   /* If OLDDECL had its DECL_RTL instantiated, re-invoke make_decl_rtl
2896     so that encode_section_info has a chance to look at the new decl
2897     flags and attributes.  */
2898   if (DECL_RTL_SET_P (olddecl)
2899       && (TREE_CODE (olddecl) == FUNCTION_DECL
2900           || (VAR_P (olddecl)
2901               && TREE_STATIC (olddecl))))
2902     make_decl_rtl (olddecl);
2903
2904   /* The NEWDECL will no longer be needed.  Because every out-of-class
2905      declaration of a member results in a call to duplicate_decls,
2906      freeing these nodes represents in a significant savings.
2907
2908      Before releasing the node, be sore to remove function from symbol
2909      table that might have been inserted there to record comdat group.
2910      Be sure to however do not free DECL_STRUCT_FUNCTION because this
2911      structure is shared in between newdecl and oldecl.  */
2912   if (TREE_CODE (newdecl) == FUNCTION_DECL)
2913     DECL_STRUCT_FUNCTION (newdecl) = NULL;
2914   if (VAR_OR_FUNCTION_DECL_P (newdecl))
2915     {
2916       struct symtab_node *snode = symtab_node::get (newdecl);
2917       if (snode)
2918         snode->remove ();
2919     }
2920
2921   /* Remove the associated constraints for newdecl, if any, before
2922      reclaiming memory. */
2923   if (flag_concepts)
2924     remove_constraints (newdecl);
2925
2926   ggc_free (newdecl);
2927
2928   return olddecl;
2929 }
2930 \f
2931 /* Return zero if the declaration NEWDECL is valid
2932    when the declaration OLDDECL (assumed to be for the same name)
2933    has already been seen.
2934    Otherwise return an error message format string with a %s
2935    where the identifier should go.  */
2936
2937 static const char *
2938 redeclaration_error_message (tree newdecl, tree olddecl)
2939 {
2940   if (TREE_CODE (newdecl) == TYPE_DECL)
2941     {
2942       /* Because C++ can put things into name space for free,
2943          constructs like "typedef struct foo { ... } foo"
2944          would look like an erroneous redeclaration.  */
2945       if (same_type_p (TREE_TYPE (newdecl), TREE_TYPE (olddecl)))
2946         return NULL;
2947       else
2948         return G_("redefinition of %q#D");
2949     }
2950   else if (TREE_CODE (newdecl) == FUNCTION_DECL)
2951     {
2952       /* If this is a pure function, its olddecl will actually be
2953          the original initialization to `0' (which we force to call
2954          abort()).  Don't complain about redefinition in this case.  */
2955       if (DECL_LANG_SPECIFIC (olddecl) && DECL_PURE_VIRTUAL_P (olddecl)
2956           && DECL_INITIAL (olddecl) == NULL_TREE)
2957         return NULL;
2958
2959       /* If both functions come from different namespaces, this is not
2960          a redeclaration - this is a conflict with a used function.  */
2961       if (DECL_NAMESPACE_SCOPE_P (olddecl)
2962           && DECL_CONTEXT (olddecl) != DECL_CONTEXT (newdecl)
2963           && ! decls_match (olddecl, newdecl))
2964         return G_("%qD conflicts with used function");
2965
2966       /* We'll complain about linkage mismatches in
2967          warn_extern_redeclared_static.  */
2968
2969       /* Defining the same name twice is no good.  */
2970       if (decl_defined_p (olddecl)
2971           && decl_defined_p (newdecl))
2972         {
2973           if (DECL_NAME (olddecl) == NULL_TREE)
2974             return G_("%q#D not declared in class");
2975           else if (!GNU_INLINE_P (olddecl)
2976                    || GNU_INLINE_P (newdecl))
2977             return G_("redefinition of %q#D");
2978         }
2979
2980       if (DECL_DECLARED_INLINE_P (olddecl) && DECL_DECLARED_INLINE_P (newdecl))
2981         {
2982           bool olda = GNU_INLINE_P (olddecl);
2983           bool newa = GNU_INLINE_P (newdecl);
2984
2985           if (olda != newa)
2986             {
2987               if (newa)
2988                 return G_("%q+D redeclared inline with "
2989                           "%<gnu_inline%> attribute");
2990               else
2991                 return G_("%q+D redeclared inline without "
2992                           "%<gnu_inline%> attribute");
2993             }
2994         }
2995
2996       if (deduction_guide_p (olddecl)
2997           && deduction_guide_p (newdecl))
2998         return G_("deduction guide %q+D redeclared");
2999
3000       /* [class.compare.default]: A definition of a comparison operator as
3001          defaulted that appears in a class shall be the first declaration of
3002          that function.  */
3003       special_function_kind sfk = special_function_p (olddecl);
3004       if (sfk == sfk_comparison && DECL_DEFAULTED_FN (newdecl))
3005         return G_("comparison operator %q+D defaulted after "
3006                   "its first declaration");
3007
3008       check_abi_tag_redeclaration
3009         (olddecl, lookup_attribute ("abi_tag", DECL_ATTRIBUTES (olddecl)),
3010          lookup_attribute ("abi_tag", DECL_ATTRIBUTES (newdecl)));
3011
3012       return NULL;
3013     }
3014   else if (TREE_CODE (newdecl) == TEMPLATE_DECL)
3015     {
3016       tree nt, ot;
3017
3018       if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == CONCEPT_DECL)
3019         return G_("redefinition of %q#D");
3020
3021       if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) != FUNCTION_DECL)
3022         return redeclaration_error_message (DECL_TEMPLATE_RESULT (newdecl),
3023                                             DECL_TEMPLATE_RESULT (olddecl));
3024
3025       if (DECL_TEMPLATE_RESULT (newdecl) == DECL_TEMPLATE_RESULT (olddecl))
3026         return NULL;
3027
3028       nt = DECL_TEMPLATE_RESULT (newdecl);
3029       if (DECL_TEMPLATE_INFO (nt))
3030         nt = DECL_TEMPLATE_RESULT (template_for_substitution (nt));
3031       ot = DECL_TEMPLATE_RESULT (olddecl);
3032       if (DECL_TEMPLATE_INFO (ot))
3033         ot = DECL_TEMPLATE_RESULT (template_for_substitution (ot));
3034       if (DECL_INITIAL (nt) && DECL_INITIAL (ot)
3035           && (!GNU_INLINE_P (ot) || GNU_INLINE_P (nt)))
3036         return G_("redefinition of %q#D");
3037
3038       if (DECL_DECLARED_INLINE_P (ot) && DECL_DECLARED_INLINE_P (nt))
3039         {
3040           bool olda = GNU_INLINE_P (ot);
3041           bool newa = GNU_INLINE_P (nt);
3042
3043           if (olda != newa)
3044             {
3045               if (newa)
3046                 return G_("%q+D redeclared inline with "
3047                           "%<gnu_inline%> attribute");
3048               else
3049                 return G_("%q+D redeclared inline without "
3050                           "%<gnu_inline%> attribute");
3051             }
3052         }
3053
3054       if (deduction_guide_p (olddecl)
3055           && deduction_guide_p (newdecl))
3056         return G_("deduction guide %q+D redeclared");
3057
3058       /* Core issue #226 (C++11):
3059
3060            If a friend function template declaration specifies a
3061            default template-argument, that declaration shall be a
3062            definition and shall be the only declaration of the
3063            function template in the translation unit.  */
3064       if ((cxx_dialect != cxx98)
3065           && TREE_CODE (ot) == FUNCTION_DECL && DECL_FRIEND_P (ot)
3066           && !check_default_tmpl_args (nt, DECL_TEMPLATE_PARMS (newdecl),
3067                                        /*is_primary=*/true,
3068                                        /*is_partial=*/false,
3069                                        /*is_friend_decl=*/2))
3070         return G_("redeclaration of friend %q#D "
3071                   "may not have default template arguments");
3072
3073       return NULL;
3074     }
3075   else if (VAR_P (newdecl)
3076            && CP_DECL_THREAD_LOCAL_P (newdecl) != CP_DECL_THREAD_LOCAL_P (olddecl)
3077            && (! DECL_LANG_SPECIFIC (olddecl)
3078                || ! CP_DECL_THREADPRIVATE_P (olddecl)
3079                || CP_DECL_THREAD_LOCAL_P (newdecl)))
3080     {
3081       /* Only variables can be thread-local, and all declarations must
3082          agree on this property.  */
3083       if (CP_DECL_THREAD_LOCAL_P (newdecl))
3084         return G_("thread-local declaration of %q#D follows "
3085                   "non-thread-local declaration");
3086       else
3087         return G_("non-thread-local declaration of %q#D follows "
3088                   "thread-local declaration");
3089     }
3090   else if (toplevel_bindings_p () || DECL_NAMESPACE_SCOPE_P (newdecl))
3091     {
3092       /* The objects have been declared at namespace scope.  If either
3093          is a member of an anonymous union, then this is an invalid
3094          redeclaration.  For example:
3095
3096            int i;
3097            union { int i; };
3098
3099            is invalid.  */
3100       if ((VAR_P (newdecl) && DECL_ANON_UNION_VAR_P (newdecl))
3101           || (VAR_P (olddecl) && DECL_ANON_UNION_VAR_P (olddecl)))
3102         return G_("redeclaration of %q#D");
3103       /* If at least one declaration is a reference, there is no
3104          conflict.  For example:
3105
3106            int i = 3;
3107            extern int i;
3108
3109          is valid.  */
3110       if (DECL_EXTERNAL (newdecl) || DECL_EXTERNAL (olddecl))
3111         return NULL;
3112
3113       /* Static data member declared outside a class definition
3114          if the variable is defined within the class with constexpr
3115          specifier is declaration rather than definition (and
3116          deprecated).  */
3117       if (cxx_dialect >= cxx17
3118           && VAR_P (olddecl)
3119           && DECL_CLASS_SCOPE_P (olddecl)
3120           && DECL_DECLARED_CONSTEXPR_P (olddecl)
3121           && !DECL_INITIAL (newdecl))
3122         {
3123           DECL_EXTERNAL (newdecl) = 1;
3124           /* For now, only warn with explicit -Wdeprecated.  */
3125           if (global_options_set.x_warn_deprecated)
3126             {
3127               auto_diagnostic_group d;
3128               if (warning_at (DECL_SOURCE_LOCATION (newdecl), OPT_Wdeprecated,
3129                                 "redundant redeclaration of %<constexpr%> "
3130                                 "static data member %qD", newdecl))
3131                 inform (DECL_SOURCE_LOCATION (olddecl),
3132                           "previous declaration of %qD", olddecl);
3133             }
3134           return NULL;
3135         }
3136
3137       /* Reject two definitions.  */
3138       return G_("redefinition of %q#D");
3139     }
3140   else
3141     {
3142       /* Objects declared with block scope:  */
3143       /* Reject two definitions, and reject a definition
3144          together with an external reference.  */
3145       if (!(DECL_EXTERNAL (newdecl) && DECL_EXTERNAL (olddecl)))
3146         return G_("redeclaration of %q#D");
3147       return NULL;
3148     }
3149 }
3150 \f
3151
3152 /* Hash and equality functions for the named_label table.  */
3153
3154 hashval_t
3155 named_label_hash::hash (const value_type entry)
3156 {
3157   return IDENTIFIER_HASH_VALUE (entry->name);
3158 }
3159
3160 bool
3161 named_label_hash::equal (const value_type entry, compare_type name)
3162 {
3163   return name == entry->name;
3164 }
3165
3166 /* Look for a label named ID in the current function.  If one cannot
3167    be found, create one.  Return the named_label_entry, or NULL on
3168    failure.  */
3169
3170 static named_label_entry *
3171 lookup_label_1 (tree id, bool making_local_p)
3172 {
3173   /* You can't use labels at global scope.  */
3174   if (current_function_decl == NULL_TREE)
3175     {
3176       error ("label %qE referenced outside of any function", id);
3177       return NULL;
3178     }
3179
3180   if (!named_labels)
3181     named_labels = hash_table<named_label_hash>::create_ggc (13);
3182
3183   hashval_t hash = IDENTIFIER_HASH_VALUE (id);
3184   named_label_entry **slot
3185     = named_labels->find_slot_with_hash (id, hash, INSERT);
3186   named_label_entry *old = *slot;
3187   
3188   if (old && old->label_decl)
3189     {
3190       if (!making_local_p)
3191         return old;
3192
3193       if (old->binding_level == current_binding_level)
3194         {
3195           error ("local label %qE conflicts with existing label", id);
3196           inform (DECL_SOURCE_LOCATION (old->label_decl), "previous label");
3197           return NULL;
3198         }
3199     }
3200
3201   /* We are making a new decl, create or reuse the named_label_entry  */
3202   named_label_entry *ent = NULL;
3203   if (old && !old->label_decl)
3204     ent = old;
3205   else
3206     {
3207       ent = ggc_cleared_alloc<named_label_entry> ();
3208       ent->name = id;
3209       ent->outer = old;
3210       *slot = ent;
3211     }
3212
3213   /* Now create the LABEL_DECL.  */
3214   tree decl = build_decl (input_location, LABEL_DECL, id, void_type_node);
3215
3216   DECL_CONTEXT (decl) = current_function_decl;
3217   SET_DECL_MODE (decl, VOIDmode);
3218   if (making_local_p)
3219     {
3220       C_DECLARED_LABEL_FLAG (decl) = true;
3221       DECL_CHAIN (decl) = current_binding_level->names;
3222       current_binding_level->names = decl;
3223     }
3224
3225   ent->label_decl = decl;
3226
3227   return ent;
3228 }
3229
3230 /* Wrapper for lookup_label_1.  */
3231
3232 tree
3233 lookup_label (tree id)
3234 {
3235   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
3236   named_label_entry *ent = lookup_label_1 (id, false);
3237   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
3238   return ent ? ent->label_decl : NULL_TREE;
3239 }
3240
3241 tree
3242 declare_local_label (tree id)
3243 {
3244   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
3245   named_label_entry *ent = lookup_label_1 (id, true);
3246   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
3247   return ent ? ent->label_decl : NULL_TREE;
3248 }
3249
3250 /* Returns nonzero if it is ill-formed to jump past the declaration of
3251    DECL.  Returns 2 if it's also a real problem.  */
3252
3253 static int
3254 decl_jump_unsafe (tree decl)
3255 {
3256   /* [stmt.dcl]/3: A program that jumps from a point where a local variable
3257      with automatic storage duration is not in scope to a point where it is
3258      in scope is ill-formed unless the variable has scalar type, class type
3259      with a trivial default constructor and a trivial destructor, a
3260      cv-qualified version of one of these types, or an array of one of the
3261      preceding types and is declared without an initializer (8.5).  */
3262   tree type = TREE_TYPE (decl);
3263
3264   if (!VAR_P (decl) || TREE_STATIC (decl)
3265       || type == error_mark_node)
3266     return 0;
3267
3268   if (DECL_NONTRIVIALLY_INITIALIZED_P (decl)
3269       || variably_modified_type_p (type, NULL_TREE))
3270     return 2;
3271
3272   if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
3273     return 1;
3274
3275   return 0;
3276 }
3277
3278 /* A subroutine of check_previous_goto_1 and check_goto to identify a branch
3279    to the user.  */
3280
3281 static bool
3282 identify_goto (tree decl, location_t loc, const location_t *locus,
3283                diagnostic_t diag_kind)
3284 {
3285   bool complained
3286     = emit_diagnostic (diag_kind, loc, 0,
3287                        decl ? N_("jump to label %qD")
3288                        : N_("jump to case label"), decl);
3289   if (complained && locus)
3290     inform (*locus, "  from here");
3291   return complained;
3292 }
3293
3294 /* Check that a single previously seen jump to a newly defined label
3295    is OK.  DECL is the LABEL_DECL or 0; LEVEL is the binding_level for
3296    the jump context; NAMES are the names in scope in LEVEL at the jump
3297    context; LOCUS is the source position of the jump or 0.  Returns
3298    true if all is well.  */
3299
3300 static bool
3301 check_previous_goto_1 (tree decl, cp_binding_level* level, tree names,
3302                        bool exited_omp, const location_t *locus)
3303 {
3304   cp_binding_level *b;
3305   bool complained = false;
3306   int identified = 0;
3307   bool saw_eh = false, saw_omp = false, saw_tm = false, saw_cxif = false;
3308
3309   if (exited_omp)
3310     {
3311       complained = identify_goto (decl, input_location, locus, DK_ERROR);
3312       if (complained)
3313         inform (input_location, "  exits OpenMP structured block");
3314       saw_omp = true;
3315       identified = 2;
3316     }
3317
3318   for (b = current_binding_level; b ; b = b->level_chain)
3319     {
3320       tree new_decls, old_decls = (b == level ? names : NULL_TREE);
3321
3322       for (new_decls = b->names; new_decls != old_decls;
3323            new_decls = (DECL_P (new_decls) ? DECL_CHAIN (new_decls)
3324                         : TREE_CHAIN (new_decls)))
3325         {
3326           int problem = decl_jump_unsafe (new_decls);
3327           if (! problem)
3328             continue;
3329
3330           if (!identified)
3331             {
3332               complained = identify_goto (decl, input_location, locus,
3333                                           problem > 1
3334                                           ? DK_ERROR : DK_PERMERROR);
3335               identified = 1;
3336             }
3337           if (complained)
3338             {
3339               if (problem > 1)
3340                 inform (DECL_SOURCE_LOCATION (new_decls),
3341                         "  crosses initialization of %q#D", new_decls);
3342               else
3343                 inform (DECL_SOURCE_LOCATION (new_decls),
3344                         "  enters scope of %q#D, which has "
3345                         "non-trivial destructor", new_decls);
3346             }
3347         }
3348
3349       if (b == level)
3350         break;
3351
3352       const char *inf = NULL;
3353       location_t loc = input_location;
3354       switch (b->kind)
3355         {
3356         case sk_try:
3357           if (!saw_eh)
3358             inf = G_("  enters %<try%> block");
3359           saw_eh = true;
3360           break;
3361
3362         case sk_catch:
3363           if (!saw_eh)
3364             inf = G_("  enters %<catch%> block");
3365           saw_eh = true;
3366           break;
3367
3368         case sk_omp:
3369           if (!saw_omp)
3370             inf = G_("  enters OpenMP structured block");
3371           saw_omp = true;
3372           break;
3373
3374         case sk_transaction:
3375           if (!saw_tm)
3376             inf = G_("  enters synchronized or atomic statement");
3377           saw_tm = true;
3378           break;
3379
3380         case sk_block:
3381           if (!saw_cxif && level_for_constexpr_if (b->level_chain))
3382             {
3383               inf = G_("  enters %<constexpr if%> statement");
3384               loc = EXPR_LOCATION (b->level_chain->this_entity);
3385               saw_cxif = true;
3386             }
3387           break;
3388
3389         default:
3390           break;
3391         }
3392
3393       if (inf)
3394         {
3395           if (identified < 2)
3396             complained = identify_goto (decl, input_location, locus, DK_ERROR);
3397           identified = 2;
3398           if (complained)
3399             inform (loc, inf);
3400         }
3401     }
3402
3403   return !identified;
3404 }
3405
3406 static void
3407 check_previous_goto (tree decl, struct named_label_use_entry *use)
3408 {
3409   check_previous_goto_1 (decl, use->binding_level,
3410                          use->names_in_scope, use->in_omp_scope,
3411                          &use->o_goto_locus);
3412 }
3413
3414 static bool
3415 check_switch_goto (cp_binding_level* level)
3416 {
3417   return check_previous_goto_1 (NULL_TREE, level, level->names, false, NULL);
3418 }
3419
3420 /* Check that a new jump to a label DECL is OK.  Called by
3421    finish_goto_stmt.  */
3422
3423 void
3424 check_goto (tree decl)
3425 {
3426   /* We can't know where a computed goto is jumping.
3427      So we assume that it's OK.  */
3428   if (TREE_CODE (decl) != LABEL_DECL)
3429     return;
3430
3431   /* We didn't record any information about this label when we created it,
3432      and there's not much point since it's trivial to analyze as a return.  */
3433   if (decl == cdtor_label)
3434     return;
3435
3436   hashval_t hash = IDENTIFIER_HASH_VALUE (DECL_NAME (decl));
3437   named_label_entry **slot
3438     = named_labels->find_slot_with_hash (DECL_NAME (decl), hash, NO_INSERT);
3439   named_label_entry *ent = *slot;
3440
3441   /* If the label hasn't been defined yet, defer checking.  */
3442   if (! DECL_INITIAL (decl))
3443     {
3444       /* Don't bother creating another use if the last goto had the
3445          same data, and will therefore create the same set of errors.  */
3446       if (ent->uses
3447           && ent->uses->names_in_scope == current_binding_level->names)
3448         return;
3449
3450       named_label_use_entry *new_use
3451         = ggc_alloc<named_label_use_entry> ();
3452       new_use->binding_level = current_binding_level;
3453       new_use->names_in_scope = current_binding_level->names;
3454       new_use->o_goto_locus = input_location;
3455       new_use->in_omp_scope = false;
3456
3457       new_use->next = ent->uses;
3458       ent->uses = new_use;
3459       return;
3460     }
3461
3462   bool saw_catch = false, complained = false;
3463   int identified = 0;
3464   tree bad;
3465   unsigned ix;
3466
3467   if (ent->in_try_scope || ent->in_catch_scope || ent->in_transaction_scope
3468       || ent->in_constexpr_if
3469       || ent->in_omp_scope || !vec_safe_is_empty (ent->bad_decls))
3470     {
3471       diagnostic_t diag_kind = DK_PERMERROR;
3472       if (ent->in_try_scope || ent->in_catch_scope || ent->in_constexpr_if
3473           || ent->in_transaction_scope || ent->in_omp_scope)
3474         diag_kind = DK_ERROR;
3475       complained = identify_goto (decl, DECL_SOURCE_LOCATION (decl),
3476                                   &input_location, diag_kind);
3477       identified = 1 + (diag_kind == DK_ERROR);
3478     }
3479
3480   FOR_EACH_VEC_SAFE_ELT (ent->bad_decls, ix, bad)
3481     {
3482       int u = decl_jump_unsafe (bad);
3483
3484       if (u > 1 && DECL_ARTIFICIAL (bad))
3485         {
3486           /* Can't skip init of __exception_info.  */
3487           if (identified == 1)
3488             {
3489               complained = identify_goto (decl, DECL_SOURCE_LOCATION (decl),
3490                                           &input_location, DK_ERROR);
3491               identified = 2;
3492             }
3493           if (complained)
3494             inform (DECL_SOURCE_LOCATION (bad), "  enters %<catch%> block");
3495           saw_catch = true;
3496         }
3497       else if (complained)
3498         {
3499           if (u > 1)
3500             inform (DECL_SOURCE_LOCATION (bad),
3501                     "  skips initialization of %q#D", bad);
3502           else
3503             inform (DECL_SOURCE_LOCATION (bad),
3504                     "  enters scope of %q#D which has "
3505                     "non-trivial destructor", bad);
3506         }
3507     }
3508
3509   if (complained)
3510     {
3511       if (ent->in_try_scope)
3512         inform (input_location, "  enters %<try%> block");
3513       else if (ent->in_catch_scope && !saw_catch)
3514         inform (input_location, "  enters %<catch%> block");
3515       else if (ent->in_transaction_scope)
3516         inform (input_location, "  enters synchronized or atomic statement");
3517       else if (ent->in_constexpr_if)
3518         inform (input_location, "  enters %<constexpr if%> statement");
3519     }
3520
3521   if (ent->in_omp_scope)
3522     {
3523       if (complained)
3524         inform (input_location, "  enters OpenMP structured block");
3525     }
3526   else if (flag_openmp)
3527     for (cp_binding_level *b = current_binding_level; b ; b = b->level_chain)
3528       {
3529         if (b == ent->binding_level)
3530           break;
3531         if (b->kind == sk_omp)
3532           {
3533             if (identified < 2)
3534               {
3535                 complained = identify_goto (decl,
3536                                             DECL_SOURCE_LOCATION (decl),
3537                                             &input_location, DK_ERROR);
3538                 identified = 2;
3539               }
3540             if (complained)
3541               inform (input_location, "  exits OpenMP structured block");
3542             break;
3543           }
3544       }
3545 }
3546
3547 /* Check that a return is ok wrt OpenMP structured blocks.
3548    Called by finish_return_stmt.  Returns true if all is well.  */
3549
3550 bool
3551 check_omp_return (void)
3552 {
3553   for (cp_binding_level *b = current_binding_level; b ; b = b->level_chain)
3554     if (b->kind == sk_omp)
3555       {
3556         error ("invalid exit from OpenMP structured block");
3557         return false;
3558       }
3559     else if (b->kind == sk_function_parms)
3560       break;
3561   return true;
3562 }
3563
3564 /* Define a label, specifying the location in the source file.
3565    Return the LABEL_DECL node for the label.  */
3566
3567 static tree
3568 define_label_1 (location_t location, tree name)
3569 {
3570   /* After labels, make any new cleanups in the function go into their
3571      own new (temporary) binding contour.  */
3572   for (cp_binding_level *p = current_binding_level;
3573        p->kind != sk_function_parms;
3574        p = p->level_chain)
3575     p->more_cleanups_ok = 0;
3576
3577   named_label_entry *ent = lookup_label_1 (name, false);
3578   tree decl = ent->label_decl;
3579
3580   if (DECL_INITIAL (decl) != NULL_TREE)
3581     {
3582       error ("duplicate label %qD", decl);
3583       return error_mark_node;
3584     }
3585   else
3586     {
3587       /* Mark label as having been defined.  */
3588       DECL_INITIAL (decl) = error_mark_node;
3589       /* Say where in the source.  */
3590       DECL_SOURCE_LOCATION (decl) = location;
3591
3592       ent->binding_level = current_binding_level;
3593       ent->names_in_scope = current_binding_level->names;
3594
3595       for (named_label_use_entry *use = ent->uses; use; use = use->next)
3596         check_previous_goto (decl, use);
3597       ent->uses = NULL;
3598     }
3599
3600   return decl;
3601 }
3602
3603 /* Wrapper for define_label_1.  */
3604
3605 tree
3606 define_label (location_t location, tree name)
3607 {
3608   bool running = timevar_cond_start (TV_NAME_LOOKUP);
3609   tree ret = define_label_1 (location, name);
3610   timevar_cond_stop (TV_NAME_LOOKUP, running);
3611   return ret;
3612 }
3613
3614
3615 struct cp_switch
3616 {
3617   cp_binding_level *level;
3618   struct cp_switch *next;
3619   /* The SWITCH_STMT being built.  */
3620   tree switch_stmt;
3621   /* A splay-tree mapping the low element of a case range to the high
3622      element, or NULL_TREE if there is no high element.  Used to
3623      determine whether or not a new case label duplicates an old case
3624      label.  We need a tree, rather than simply a hash table, because
3625      of the GNU case range extension.  */
3626   splay_tree cases;
3627   /* Remember whether a default: case label has been seen.  */
3628   bool has_default_p;
3629   /* Remember whether a BREAK_STMT has been seen in this SWITCH_STMT.  */
3630   bool break_stmt_seen_p;
3631   /* Set if inside of {FOR,DO,WHILE}_BODY nested inside of a switch,
3632      where BREAK_STMT doesn't belong to the SWITCH_STMT.  */
3633   bool in_loop_body_p;
3634 };
3635
3636 /* A stack of the currently active switch statements.  The innermost
3637    switch statement is on the top of the stack.  There is no need to
3638    mark the stack for garbage collection because it is only active
3639    during the processing of the body of a function, and we never
3640    collect at that point.  */
3641
3642 static struct cp_switch *switch_stack;
3643
3644 /* Called right after a switch-statement condition is parsed.
3645    SWITCH_STMT is the switch statement being parsed.  */
3646
3647 void
3648 push_switch (tree switch_stmt)
3649 {
3650   struct cp_switch *p = XNEW (struct cp_switch);
3651   p->level = current_binding_level;
3652   p->next = switch_stack;
3653   p->switch_stmt = switch_stmt;
3654   p->cases = splay_tree_new (case_compare, NULL, NULL);
3655   p->has_default_p = false;
3656   p->break_stmt_seen_p = false;
3657   p->in_loop_body_p = false;
3658   switch_stack = p;
3659 }
3660
3661 void
3662 pop_switch (void)
3663 {
3664   struct cp_switch *cs = switch_stack;
3665   location_t switch_location;
3666
3667   /* Emit warnings as needed.  */
3668   switch_location = cp_expr_loc_or_input_loc (cs->switch_stmt);
3669   const bool bool_cond_p
3670     = (SWITCH_STMT_TYPE (cs->switch_stmt)
3671        && TREE_CODE (SWITCH_STMT_TYPE (cs->switch_stmt)) == BOOLEAN_TYPE);
3672   if (!processing_template_decl)
3673     c_do_switch_warnings (cs->cases, switch_location,
3674                           SWITCH_STMT_TYPE (cs->switch_stmt),
3675                           SWITCH_STMT_COND (cs->switch_stmt), bool_cond_p);
3676
3677   /* For the benefit of block_may_fallthru remember if the switch body
3678      case labels cover all possible values and if there are break; stmts.  */
3679   if (cs->has_default_p
3680       || (!processing_template_decl
3681           && c_switch_covers_all_cases_p (cs->cases,
3682                                           SWITCH_STMT_TYPE (cs->switch_stmt))))
3683     SWITCH_STMT_ALL_CASES_P (cs->switch_stmt) = 1;
3684   if (!cs->break_stmt_seen_p)
3685     SWITCH_STMT_NO_BREAK_P (cs->switch_stmt) = 1;
3686   gcc_assert (!cs->in_loop_body_p);
3687   splay_tree_delete (cs->cases);
3688   switch_stack = switch_stack->next;
3689   free (cs);
3690 }
3691
3692 /* Note that a BREAK_STMT is about to be added.  If it is inside of
3693    a SWITCH_STMT and not inside of a loop body inside of it, note
3694    in switch_stack we've seen a BREAK_STMT.  */
3695
3696 void
3697 note_break_stmt (void)
3698 {
3699   if (switch_stack && !switch_stack->in_loop_body_p)
3700     switch_stack->break_stmt_seen_p = true;
3701 }
3702
3703 /* Note the start of processing of an iteration statement's body.
3704    The note_break_stmt function will do nothing while processing it.
3705    Return a flag that should be passed to note_iteration_stmt_body_end.  */
3706
3707 bool
3708 note_iteration_stmt_body_start (void)
3709 {
3710   if (!switch_stack)
3711     return false;
3712   bool ret = switch_stack->in_loop_body_p;
3713   switch_stack->in_loop_body_p = true;
3714   return ret;
3715 }
3716
3717 /* Note the end of processing of an iteration statement's body.  */
3718
3719 void
3720 note_iteration_stmt_body_end (bool prev)
3721 {
3722   if (switch_stack)
3723     switch_stack->in_loop_body_p = prev;
3724 }
3725
3726 /* Convert a case constant VALUE in a switch to the type TYPE of the switch
3727    condition.  Note that if TYPE and VALUE are already integral we don't
3728    really do the conversion because the language-independent
3729    warning/optimization code will work better that way.  */
3730
3731 static tree
3732 case_conversion (tree type, tree value)
3733 {
3734   if (value == NULL_TREE)
3735     return value;
3736
3737   value = mark_rvalue_use (value);
3738
3739   if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3740     type = type_promotes_to (type);
3741
3742   tree ovalue = value;
3743   /* The constant-expression VALUE shall be a converted constant expression
3744      of the adjusted type of the switch condition, which doesn't allow
3745      narrowing conversions.  */
3746   value = build_converted_constant_expr (type, value, tf_warning_or_error);
3747
3748   if (cxx_dialect >= cxx11
3749       && (SCOPED_ENUM_P (type)
3750           || !INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (ovalue))))
3751     /* Use the converted value.  */;
3752   else
3753     /* The already integral case.  */
3754     value = ovalue;
3755
3756   return cxx_constant_value (value);
3757 }
3758
3759 /* Note that we've seen a definition of a case label, and complain if this
3760    is a bad place for one.  */
3761
3762 tree
3763 finish_case_label (location_t loc, tree low_value, tree high_value)
3764 {
3765   tree cond, r;
3766   cp_binding_level *p;
3767   tree type;
3768
3769   if (low_value == NULL_TREE && high_value == NULL_TREE)
3770     switch_stack->has_default_p = true;
3771
3772   if (processing_template_decl)
3773     {
3774       tree label;
3775
3776       /* For templates, just add the case label; we'll do semantic
3777          analysis at instantiation-time.  */
3778       label = build_decl (loc, LABEL_DECL, NULL_TREE, void_type_node);
3779       return add_stmt (build_case_label (low_value, high_value, label));
3780     }
3781
3782   /* Find the condition on which this switch statement depends.  */
3783   cond = SWITCH_STMT_COND (switch_stack->switch_stmt);
3784   if (cond && TREE_CODE (cond) == TREE_LIST)
3785     cond = TREE_VALUE (cond);
3786
3787   if (!check_switch_goto (switch_stack->level))
3788     return error_mark_node;
3789
3790   type = SWITCH_STMT_TYPE (switch_stack->switch_stmt);
3791   if (type == error_mark_node)
3792     return error_mark_node;
3793
3794   low_value = case_conversion (type, low_value);
3795   high_value = case_conversion (type, high_value);
3796
3797   r = c_add_case_label (loc, switch_stack->cases, cond, low_value, high_value);
3798
3799   /* After labels, make any new cleanups in the function go into their
3800      own new (temporary) binding contour.  */
3801   for (p = current_binding_level;
3802        p->kind != sk_function_parms;
3803        p = p->level_chain)
3804     p->more_cleanups_ok = 0;
3805
3806   return r;
3807 }
3808 \f
3809 struct typename_info {
3810   tree scope;
3811   tree name;
3812   tree template_id;
3813   bool enum_p;
3814   bool class_p;
3815 };
3816
3817 struct typename_hasher : ggc_ptr_hash<tree_node>
3818 {
3819   typedef typename_info *compare_type;
3820
3821   /* Hash a TYPENAME_TYPE.  */
3822
3823   static hashval_t
3824   hash (tree t)
3825   {
3826     hashval_t hash;
3827
3828     hash = (htab_hash_pointer (TYPE_CONTEXT (t))
3829             ^ htab_hash_pointer (TYPE_IDENTIFIER (t)));
3830
3831     return hash;
3832   }
3833
3834   /* Compare two TYPENAME_TYPEs.  */
3835
3836   static bool
3837   equal (tree t1, const typename_info *t2)
3838   {
3839     return (TYPE_IDENTIFIER (t1) == t2->name
3840             && TYPE_CONTEXT (t1) == t2->scope
3841             && TYPENAME_TYPE_FULLNAME (t1) == t2->template_id
3842             && TYPENAME_IS_ENUM_P (t1) == t2->enum_p
3843             && TYPENAME_IS_CLASS_P (t1) == t2->class_p);
3844   }
3845 };
3846
3847 /* Build a TYPENAME_TYPE.  If the type is `typename T::t', CONTEXT is
3848    the type of `T', NAME is the IDENTIFIER_NODE for `t'.
3849
3850    Returns the new TYPENAME_TYPE.  */
3851
3852 static GTY (()) hash_table<typename_hasher> *typename_htab;
3853
3854 tree
3855 build_typename_type (tree context, tree name, tree fullname,
3856                      enum tag_types tag_type)
3857 {
3858   typename_info ti;
3859
3860   if (typename_htab == NULL)
3861     typename_htab = hash_table<typename_hasher>::create_ggc (61);
3862
3863   ti.scope = FROB_CONTEXT (context);
3864   ti.name = name;
3865   ti.template_id = fullname;
3866   ti.enum_p = tag_type == enum_type;
3867   ti.class_p = (tag_type == class_type
3868                 || tag_type == record_type
3869                 || tag_type == union_type);
3870   hashval_t hash =  (htab_hash_pointer (ti.scope)
3871                      ^ htab_hash_pointer (ti.name));
3872
3873   /* See if we already have this type.  */
3874   tree *e = typename_htab->find_slot_with_hash (&ti, hash, INSERT);
3875   tree t = *e;
3876   if (*e)
3877     t = *e;
3878   else
3879     {
3880       /* Build the TYPENAME_TYPE.  */
3881       t = cxx_make_type (TYPENAME_TYPE);
3882       TYPE_CONTEXT (t) = ti.scope;
3883       TYPENAME_TYPE_FULLNAME (t) = ti.template_id;
3884       TYPENAME_IS_ENUM_P (t) = ti.enum_p;
3885       TYPENAME_IS_CLASS_P (t) = ti.class_p;
3886
3887       /* Build the corresponding TYPE_DECL.  */
3888       tree d = build_decl (input_location, TYPE_DECL, name, t);
3889       TYPE_NAME (t) = d;
3890       TYPE_STUB_DECL (t) = d;
3891       DECL_CONTEXT (d) = ti.scope;
3892       DECL_ARTIFICIAL (d) = 1;
3893
3894       /* Store it in the hash table.  */
3895       *e = t;
3896
3897       /* TYPENAME_TYPEs must always be compared structurally, because
3898          they may or may not resolve down to another type depending on
3899          the currently open classes. */
3900       SET_TYPE_STRUCTURAL_EQUALITY (t);
3901     }
3902
3903   return t;
3904 }
3905
3906 /* Resolve `typename CONTEXT::NAME'.  TAG_TYPE indicates the tag
3907    provided to name the type.  Returns an appropriate type, unless an
3908    error occurs, in which case error_mark_node is returned.  If we
3909    locate a non-artificial TYPE_DECL and TF_KEEP_TYPE_DECL is set, we
3910    return that, rather than the _TYPE it corresponds to, in other
3911    cases we look through the type decl.  If TF_ERROR is set, complain
3912    about errors, otherwise be quiet.  */
3913
3914 tree
3915 make_typename_type (tree context, tree name, enum tag_types tag_type,
3916                     tsubst_flags_t complain)
3917 {
3918   tree fullname;
3919   tree t;
3920   bool want_template;
3921
3922   if (name == error_mark_node
3923       || context == NULL_TREE
3924       || context == error_mark_node)
3925     return error_mark_node;
3926
3927   if (TYPE_P (name))
3928     {
3929       if (!(TYPE_LANG_SPECIFIC (name)
3930             && (CLASSTYPE_IS_TEMPLATE (name)
3931                 || CLASSTYPE_USE_TEMPLATE (name))))
3932         name = TYPE_IDENTIFIER (name);
3933       else
3934         /* Create a TEMPLATE_ID_EXPR for the type.  */
3935         name = build_nt (TEMPLATE_ID_EXPR,
3936                          CLASSTYPE_TI_TEMPLATE (name),
3937                          CLASSTYPE_TI_ARGS (name));
3938     }
3939   else if (TREE_CODE (name) == TYPE_DECL)
3940     name = DECL_NAME (name);
3941
3942   fullname = name;
3943
3944   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
3945     {
3946       name = TREE_OPERAND (name, 0);
3947       if (DECL_TYPE_TEMPLATE_P (name))
3948         name = TREE_OPERAND (fullname, 0) = DECL_NAME (name);
3949       if (TREE_CODE (name) != IDENTIFIER_NODE)
3950         {
3951           if (complain & tf_error)
3952             error ("%qD is not a type", name);
3953           return error_mark_node;
3954         }
3955     }
3956   if (TREE_CODE (name) == TEMPLATE_DECL)
3957     {
3958       if (complain & tf_error)
3959         error ("%qD used without template arguments", name);
3960       return error_mark_node;
3961     }
3962   gcc_assert (identifier_p (name));
3963   gcc_assert (TYPE_P (context));
3964
3965   if (TREE_CODE (context) == TYPE_PACK_EXPANSION)
3966     /* This can happen for C++17 variadic using (c++/88986).  */;
3967   else if (!MAYBE_CLASS_TYPE_P (context))
3968     {
3969       if (complain & tf_error)
3970         error ("%q#T is not a class", context);
3971       return error_mark_node;
3972     }
3973   
3974   /* When the CONTEXT is a dependent type,  NAME could refer to a
3975      dependent base class of CONTEXT.  But look inside it anyway
3976      if CONTEXT is a currently open scope, in case it refers to a
3977      member of the current instantiation or a non-dependent base;
3978      lookup will stop when we hit a dependent base.  */
3979   if (!dependent_scope_p (context))
3980     /* We should only set WANT_TYPE when we're a nested typename type.
3981        Then we can give better diagnostics if we find a non-type.  */
3982     t = lookup_field (context, name, 2, /*want_type=*/true);
3983   else
3984     t = NULL_TREE;
3985
3986   if ((!t || TREE_CODE (t) == TREE_LIST) && dependent_type_p (context))
3987     return build_typename_type (context, name, fullname, tag_type);
3988
3989   want_template = TREE_CODE (fullname) == TEMPLATE_ID_EXPR;
3990   
3991   if (!t)
3992     {
3993       if (complain & tf_error)
3994         {
3995           if (!COMPLETE_TYPE_P (context))
3996             cxx_incomplete_type_error (NULL_TREE, context);
3997           else
3998             error (want_template ? G_("no class template named %q#T in %q#T")
3999                    : G_("no type named %q#T in %q#T"), name, context);
4000         }
4001       return error_mark_node;
4002     }
4003   
4004   /* Pull out the template from an injected-class-name (or multiple).  */
4005   if (want_template)
4006     t = maybe_get_template_decl_from_type_decl (t);
4007
4008   if (TREE_CODE (t) == TREE_LIST)
4009     {
4010       if (complain & tf_error)
4011         {
4012           error ("lookup of %qT in %qT is ambiguous", name, context);
4013           print_candidates (t);
4014         }
4015       return error_mark_node;
4016     }
4017
4018   if (want_template && !DECL_TYPE_TEMPLATE_P (t))
4019     {
4020       if (complain & tf_error)
4021         error ("%<typename %T::%D%> names %q#T, which is not a class template",
4022                context, name, t);
4023       return error_mark_node;
4024     }
4025   if (!want_template && TREE_CODE (t) != TYPE_DECL)
4026     {
4027       if (complain & tf_error)
4028         error ("%<typename %T::%D%> names %q#T, which is not a type",
4029                context, name, t);
4030       return error_mark_node;
4031     }
4032
4033   if (!check_accessibility_of_qualified_id (t, /*object_type=*/NULL_TREE,
4034                                             context, complain))
4035     return error_mark_node;
4036
4037   if (want_template)
4038     return lookup_template_class (t, TREE_OPERAND (fullname, 1),
4039                                   NULL_TREE, context,
4040                                   /*entering_scope=*/0,
4041                                   complain | tf_user);
4042   
4043   if (DECL_ARTIFICIAL (t) || !(complain & tf_keep_type_decl))
4044     t = TREE_TYPE (t);
4045
4046   maybe_record_typedef_use (t);
4047
4048   return t;
4049 }
4050
4051 /* Resolve `CONTEXT::template NAME'.  Returns a TEMPLATE_DECL if the name
4052    can be resolved or an UNBOUND_CLASS_TEMPLATE, unless an error occurs,
4053    in which case error_mark_node is returned.
4054
4055    If PARM_LIST is non-NULL, also make sure that the template parameter
4056    list of TEMPLATE_DECL matches.
4057
4058    If COMPLAIN zero, don't complain about any errors that occur.  */
4059
4060 tree
4061 make_unbound_class_template (tree context, tree name, tree parm_list,
4062                              tsubst_flags_t complain)
4063 {
4064   if (TYPE_P (name))
4065     name = TYPE_IDENTIFIER (name);
4066   else if (DECL_P (name))
4067     name = DECL_NAME (name);
4068   gcc_assert (identifier_p (name));
4069
4070   if (!dependent_type_p (context)
4071       || currently_open_class (context))
4072     {
4073       tree tmpl = NULL_TREE;
4074
4075       if (MAYBE_CLASS_TYPE_P (context))
4076         tmpl = lookup_field (context, name, 0, false);
4077
4078       if (tmpl && TREE_CODE (tmpl) == TYPE_DECL)
4079         tmpl = maybe_get_template_decl_from_type_decl (tmpl);
4080
4081       if (!tmpl || !DECL_TYPE_TEMPLATE_P (tmpl))
4082         {
4083           if (complain & tf_error)
4084             error ("no class template named %q#T in %q#T", name, context);
4085           return error_mark_node;
4086         }
4087
4088       if (parm_list
4089           && !comp_template_parms (DECL_TEMPLATE_PARMS (tmpl), parm_list))
4090         {
4091           if (complain & tf_error)
4092             {
4093               error ("template parameters do not match template %qD", tmpl);
4094               inform (DECL_SOURCE_LOCATION (tmpl),
4095                       "%qD declared here", tmpl);
4096             }
4097           return error_mark_node;
4098         }
4099
4100       if (!perform_or_defer_access_check (TYPE_BINFO (context), tmpl, tmpl,
4101                                           complain))
4102         return error_mark_node;
4103
4104       return tmpl;
4105     }
4106
4107   /* Build the UNBOUND_CLASS_TEMPLATE.  */
4108   tree t = cxx_make_type (UNBOUND_CLASS_TEMPLATE);
4109   TYPE_CONTEXT (t) = FROB_CONTEXT (context);
4110   TREE_TYPE (t) = NULL_TREE;
4111   SET_TYPE_STRUCTURAL_EQUALITY (t);
4112
4113   /* Build the corresponding TEMPLATE_DECL.  */
4114   tree d = build_decl (input_location, TEMPLATE_DECL, name, t);
4115   TYPE_NAME (t) = d;
4116   TYPE_STUB_DECL (t) = d;
4117   DECL_CONTEXT (d) = TYPE_CONTEXT (t);
4118   DECL_ARTIFICIAL (d) = 1;
4119   DECL_TEMPLATE_PARMS (d) = parm_list;
4120
4121   return t;
4122 }
4123
4124 \f
4125
4126 /* Push the declarations of builtin types into the global namespace.
4127    RID_INDEX is the index of the builtin type in the array
4128    RID_POINTERS.  NAME is the name used when looking up the builtin
4129    type.  TYPE is the _TYPE node for the builtin type.
4130
4131    The calls to set_global_binding below should be
4132    eliminated.  Built-in types should not be looked up name; their
4133    names are keywords that the parser can recognize.  However, there
4134    is code in c-common.c that uses identifier_global_value to look up
4135    built-in types by name.  */
4136
4137 void
4138 record_builtin_type (enum rid rid_index,
4139                      const char* name,
4140                      tree type)
4141 {
4142   tree decl = NULL_TREE;
4143
4144   if (name)
4145     {
4146       tree tname = get_identifier (name);
4147       tree tdecl = build_decl (BUILTINS_LOCATION, TYPE_DECL, tname, type);
4148       DECL_ARTIFICIAL (tdecl) = 1;
4149       set_global_binding (tdecl);
4150       decl = tdecl;
4151     }
4152
4153   if ((int) rid_index < (int) RID_MAX)
4154     if (tree rname = ridpointers[(int) rid_index])
4155       if (!decl || DECL_NAME (decl) != rname)
4156         {
4157           tree rdecl = build_decl (BUILTINS_LOCATION, TYPE_DECL, rname, type);
4158           DECL_ARTIFICIAL (rdecl) = 1;
4159           set_global_binding (rdecl);
4160           if (!decl)
4161             decl = rdecl;
4162         }
4163
4164   if (decl)
4165     {
4166       if (!TYPE_NAME (type))
4167         TYPE_NAME (type) = decl;
4168       debug_hooks->type_decl (decl, 0);
4169     }
4170 }
4171
4172 /* Push a type into the namespace so that the back ends ignore it.  */
4173
4174 static void
4175 record_unknown_type (tree type, const char* name)
4176 {
4177   tree decl = pushdecl (build_decl (UNKNOWN_LOCATION,
4178                                     TYPE_DECL, get_identifier (name), type));
4179   /* Make sure the "unknown type" typedecl gets ignored for debug info.  */
4180   DECL_IGNORED_P (decl) = 1;
4181   TYPE_DECL_SUPPRESS_DEBUG (decl) = 1;
4182   TYPE_SIZE (type) = TYPE_SIZE (void_type_node);
4183   SET_TYPE_ALIGN (type, 1);
4184   TYPE_USER_ALIGN (type) = 0;
4185   SET_TYPE_MODE (type, TYPE_MODE (void_type_node));
4186 }
4187
4188 /* Create all the predefined identifiers.  */
4189
4190 static void
4191 initialize_predefined_identifiers (void)
4192 {
4193   struct predefined_identifier
4194   {
4195     const char *name; /* Name.  */
4196     tree *node;  /* Node to store it in.  */
4197     cp_identifier_kind kind;  /* Kind of identifier.  */
4198   };
4199
4200   /* A table of identifiers to create at startup.  */
4201   static const predefined_identifier predefined_identifiers[] = {
4202     {"C++", &lang_name_cplusplus, cik_normal},
4203     {"C", &lang_name_c, cik_normal},
4204     /* Some of these names have a trailing space so that it is
4205        impossible for them to conflict with names written by users.  */
4206     {"__ct ", &ctor_identifier, cik_ctor},
4207     {"__ct_base ", &base_ctor_identifier, cik_ctor},
4208     {"__ct_comp ", &complete_ctor_identifier, cik_ctor},
4209     {"__dt ", &dtor_identifier, cik_dtor},
4210     {"__dt_base ", &base_dtor_identifier, cik_dtor},
4211     {"__dt_comp ", &complete_dtor_identifier, cik_dtor},
4212     {"__dt_del ", &deleting_dtor_identifier, cik_dtor},
4213     {"__conv_op ", &conv_op_identifier, cik_conv_op},
4214     {"__in_chrg", &in_charge_identifier, cik_normal},
4215     {"__as_base ", &as_base_identifier, cik_normal},
4216     {"this", &this_identifier, cik_normal},
4217     {"__delta", &delta_identifier, cik_normal},
4218     {"__pfn", &pfn_identifier, cik_normal},
4219     {"_vptr", &vptr_identifier, cik_normal},
4220     {"__vtt_parm", &vtt_parm_identifier, cik_normal},
4221     {"::", &global_identifier, cik_normal},
4222       /* The demangler expects anonymous namespaces to be called
4223          something starting with '_GLOBAL__N_'.  It no longer needs
4224          to be unique to the TU.  */
4225     {"_GLOBAL__N_1", &anon_identifier, cik_normal},
4226     {"auto", &auto_identifier, cik_normal},
4227     {"decltype(auto)", &decltype_auto_identifier, cik_normal},
4228     {"initializer_list", &init_list_identifier, cik_normal},
4229     {"__for_range ", &for_range__identifier, cik_normal},
4230     {"__for_begin ", &for_begin__identifier, cik_normal},
4231     {"__for_end ", &for_end__identifier, cik_normal},
4232     {"__for_range", &for_range_identifier, cik_normal},
4233     {"__for_begin", &for_begin_identifier, cik_normal},
4234     {"__for_end", &for_end_identifier, cik_normal},
4235     {"abi_tag", &abi_tag_identifier, cik_normal},
4236     {"aligned", &aligned_identifier, cik_normal},
4237     {"begin", &begin_identifier, cik_normal},
4238     {"end", &end_identifier, cik_normal},
4239     {"get", &get__identifier, cik_normal},
4240     {"gnu", &gnu_identifier, cik_normal},
4241     {"tuple_element", &tuple_element_identifier, cik_normal},
4242     {"tuple_size", &tuple_size_identifier, cik_normal},
4243     {"type", &type_identifier, cik_normal},
4244     {"value", &value_identifier, cik_normal},
4245     {"_FUN", &fun_identifier, cik_normal},
4246     {"__closure", &closure_identifier, cik_normal},
4247     {"heap uninit", &heap_uninit_identifier, cik_normal},
4248     {"heap ", &heap_identifier, cik_normal},
4249     {"heap deleted", &heap_deleted_identifier, cik_normal},
4250     {NULL, NULL, cik_normal}
4251   };
4252
4253   for (const predefined_identifier *pid = predefined_identifiers;
4254        pid->name; ++pid)
4255     {
4256       *pid->node = get_identifier (pid->name);
4257       /* Some of these identifiers already have a special kind.  */
4258       if (pid->kind != cik_normal)
4259         set_identifier_kind (*pid->node, pid->kind);
4260     }
4261 }
4262
4263 /* Create the predefined scalar types of C,
4264    and some nodes representing standard constants (0, 1, (void *)0).
4265    Initialize the global binding level.
4266    Make definitions for built-in primitive functions.  */
4267
4268 void
4269 cxx_init_decl_processing (void)
4270 {
4271   tree void_ftype;
4272   tree void_ftype_ptr;
4273
4274   /* Create all the identifiers we need.  */
4275   initialize_predefined_identifiers ();
4276
4277   /* Create the global variables.  */
4278   push_to_top_level ();
4279
4280   current_function_decl = NULL_TREE;
4281   current_binding_level = NULL;
4282   /* Enter the global namespace.  */
4283   gcc_assert (global_namespace == NULL_TREE);
4284   global_namespace = build_lang_decl (NAMESPACE_DECL, global_identifier,
4285                                       void_type_node);
4286   TREE_PUBLIC (global_namespace) = 1;
4287   DECL_CONTEXT (global_namespace)
4288     = build_translation_unit_decl (get_identifier (main_input_filename));
4289   /* Remember whether we want the empty class passing ABI change warning
4290      in this TU.  */
4291   TRANSLATION_UNIT_WARN_EMPTY_P (DECL_CONTEXT (global_namespace))
4292     = warn_abi && abi_version_crosses (12);
4293   debug_hooks->register_main_translation_unit
4294     (DECL_CONTEXT (global_namespace));
4295   begin_scope (sk_namespace, global_namespace);
4296   current_namespace = global_namespace;
4297
4298   if (flag_visibility_ms_compat)
4299     default_visibility = VISIBILITY_HIDDEN;
4300
4301   /* Initially, C.  */
4302   current_lang_name = lang_name_c;
4303
4304   /* Create the `std' namespace.  */
4305   push_namespace (get_identifier ("std"));
4306   std_node = current_namespace;
4307   pop_namespace ();
4308
4309   flag_noexcept_type = (cxx_dialect >= cxx17);
4310
4311   c_common_nodes_and_builtins ();
4312
4313   tree bool_ftype = build_function_type_list (boolean_type_node, NULL_TREE);
4314   tree decl
4315     = add_builtin_function ("__builtin_is_constant_evaluated",
4316                             bool_ftype, CP_BUILT_IN_IS_CONSTANT_EVALUATED,
4317                             BUILT_IN_FRONTEND, NULL, NULL_TREE);
4318   set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4319
4320   tree cptr_ftype = build_function_type_list (const_ptr_type_node, NULL_TREE);
4321   decl = add_builtin_function ("__builtin_source_location",
4322                                cptr_ftype, CP_BUILT_IN_SOURCE_LOCATION,
4323                                BUILT_IN_FRONTEND, NULL, NULL_TREE);
4324   set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4325
4326   integer_two_node = build_int_cst (NULL_TREE, 2);
4327
4328   /* Guess at the initial static decls size.  */
4329   vec_alloc (static_decls, 500);
4330
4331   /* ... and keyed classes.  */
4332   vec_alloc (keyed_classes, 100);
4333
4334   record_builtin_type (RID_BOOL, "bool", boolean_type_node);
4335   truthvalue_type_node = boolean_type_node;
4336   truthvalue_false_node = boolean_false_node;
4337   truthvalue_true_node = boolean_true_node;
4338
4339   empty_except_spec = build_tree_list (NULL_TREE, NULL_TREE);
4340   noexcept_true_spec = build_tree_list (boolean_true_node, NULL_TREE);
4341   noexcept_false_spec = build_tree_list (boolean_false_node, NULL_TREE);
4342   noexcept_deferred_spec = build_tree_list (make_node (DEFERRED_NOEXCEPT),
4343                                             NULL_TREE);
4344
4345 #if 0
4346   record_builtin_type (RID_MAX, NULL, string_type_node);
4347 #endif
4348
4349   delta_type_node = ptrdiff_type_node;
4350   vtable_index_type = ptrdiff_type_node;
4351
4352   vtt_parm_type = build_pointer_type (const_ptr_type_node);
4353   void_ftype = build_function_type_list (void_type_node, NULL_TREE);
4354   void_ftype_ptr = build_function_type_list (void_type_node,
4355                                              ptr_type_node, NULL_TREE);
4356   void_ftype_ptr
4357     = build_exception_variant (void_ftype_ptr, empty_except_spec);
4358
4359   /* Create the conversion operator marker.  This operator's DECL_NAME
4360      is in the identifier table, so we can use identifier equality to
4361      find it.  */
4362   conv_op_marker = build_lang_decl (FUNCTION_DECL, conv_op_identifier,
4363                                     void_ftype);
4364
4365   /* C++ extensions */
4366
4367   unknown_type_node = make_node (LANG_TYPE);
4368   record_unknown_type (unknown_type_node, "unknown type");
4369
4370   /* Indirecting an UNKNOWN_TYPE node yields an UNKNOWN_TYPE node.  */
4371   TREE_TYPE (unknown_type_node) = unknown_type_node;
4372
4373   /* Looking up TYPE_POINTER_TO and TYPE_REFERENCE_TO yield the same
4374      result.  */
4375   TYPE_POINTER_TO (unknown_type_node) = unknown_type_node;
4376   TYPE_REFERENCE_TO (unknown_type_node) = unknown_type_node;
4377
4378   init_list_type_node = make_node (LANG_TYPE);
4379   record_unknown_type (init_list_type_node, "init list");
4380
4381   {
4382     /* Make sure we get a unique function type, so we can give
4383        its pointer type a name.  (This wins for gdb.) */
4384     tree vfunc_type = make_node (FUNCTION_TYPE);
4385     TREE_TYPE (vfunc_type) = integer_type_node;
4386     TYPE_ARG_TYPES (vfunc_type) = NULL_TREE;
4387     layout_type (vfunc_type);
4388
4389     vtable_entry_type = build_pointer_type (vfunc_type);
4390   }
4391   record_builtin_type (RID_MAX, "__vtbl_ptr_type", vtable_entry_type);
4392
4393   vtbl_type_node
4394     = build_cplus_array_type (vtable_entry_type, NULL_TREE);
4395   layout_type (vtbl_type_node);
4396   vtbl_type_node = cp_build_qualified_type (vtbl_type_node, TYPE_QUAL_CONST);
4397   record_builtin_type (RID_MAX, NULL, vtbl_type_node);
4398   vtbl_ptr_type_node = build_pointer_type (vtable_entry_type);
4399   layout_type (vtbl_ptr_type_node);
4400   record_builtin_type (RID_MAX, NULL, vtbl_ptr_type_node);
4401
4402   push_namespace (get_identifier ("__cxxabiv1"));
4403   abi_node = current_namespace;
4404   pop_namespace ();
4405
4406   global_type_node = make_node (LANG_TYPE);
4407   record_unknown_type (global_type_node, "global type");
4408
4409   any_targ_node = make_node (LANG_TYPE);
4410   record_unknown_type (any_targ_node, "any type");
4411
4412   /* Now, C++.  */
4413   current_lang_name = lang_name_cplusplus;
4414
4415   if (aligned_new_threshold > 1
4416       && !pow2p_hwi (aligned_new_threshold))
4417     {
4418       error ("%<-faligned-new=%d%> is not a power of two",
4419              aligned_new_threshold);
4420       aligned_new_threshold = 1;
4421     }
4422   if (aligned_new_threshold == -1)
4423     aligned_new_threshold = (cxx_dialect >= cxx17) ? 1 : 0;
4424   if (aligned_new_threshold == 1)
4425     aligned_new_threshold = malloc_alignment () / BITS_PER_UNIT;
4426
4427   {
4428     tree newattrs, extvisattr;
4429     tree newtype, deltype;
4430     tree ptr_ftype_sizetype;
4431     tree new_eh_spec;
4432
4433     ptr_ftype_sizetype
4434       = build_function_type_list (ptr_type_node, size_type_node, NULL_TREE);
4435     if (cxx_dialect == cxx98)
4436       {
4437         tree bad_alloc_id;
4438         tree bad_alloc_type_node;
4439         tree bad_alloc_decl;
4440
4441         push_nested_namespace (std_node);
4442         bad_alloc_id = get_identifier ("bad_alloc");
4443         bad_alloc_type_node = make_class_type (RECORD_TYPE);
4444         TYPE_CONTEXT (bad_alloc_type_node) = current_namespace;
4445         bad_alloc_decl
4446           = create_implicit_typedef (bad_alloc_id, bad_alloc_type_node);
4447         DECL_CONTEXT (bad_alloc_decl) = current_namespace;
4448         pop_nested_namespace (std_node);
4449
4450         new_eh_spec
4451           = add_exception_specifier (NULL_TREE, bad_alloc_type_node, -1);
4452       }
4453     else
4454       new_eh_spec = noexcept_false_spec;
4455
4456     /* Ensure attribs.c is initialized.  */
4457     init_attributes ();
4458
4459     extvisattr = build_tree_list (get_identifier ("externally_visible"),
4460                                   NULL_TREE);
4461     newattrs = tree_cons (get_identifier ("alloc_size"),
4462                           build_tree_list (NULL_TREE, integer_one_node),
4463                           extvisattr);
4464     newtype = cp_build_type_attribute_variant (ptr_ftype_sizetype, newattrs);
4465     newtype = build_exception_variant (newtype, new_eh_spec);
4466     deltype = cp_build_type_attribute_variant (void_ftype_ptr, extvisattr);
4467     deltype = build_exception_variant (deltype, empty_except_spec);
4468     tree opnew = push_cp_library_fn (NEW_EXPR, newtype, 0);
4469     DECL_IS_MALLOC (opnew) = 1;
4470     DECL_SET_IS_OPERATOR_NEW (opnew, true);
4471     DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4472     opnew = push_cp_library_fn (VEC_NEW_EXPR, newtype, 0);
4473     DECL_IS_MALLOC (opnew) = 1;
4474     DECL_SET_IS_OPERATOR_NEW (opnew, true);
4475     DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4476     tree opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4477     DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4478     DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4479     opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4480     DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4481     DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4482     if (flag_sized_deallocation)
4483       {
4484         /* Also push the sized deallocation variants:
4485              void operator delete(void*, std::size_t) throw();
4486              void operator delete[](void*, std::size_t) throw();  */
4487         tree void_ftype_ptr_size
4488           = build_function_type_list (void_type_node, ptr_type_node,
4489                                       size_type_node, NULL_TREE);
4490         deltype = cp_build_type_attribute_variant (void_ftype_ptr_size,
4491                                                    extvisattr);
4492         deltype = build_exception_variant (deltype, empty_except_spec);
4493         opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4494         DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4495         DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4496         opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4497         DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4498         DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4499       }
4500
4501     if (aligned_new_threshold)
4502       {
4503         push_nested_namespace (std_node);
4504         tree align_id = get_identifier ("align_val_t");
4505         align_type_node = start_enum (align_id, NULL_TREE, size_type_node,
4506                                       NULL_TREE, /*scoped*/true, NULL);
4507         pop_nested_namespace (std_node);
4508
4509         /* operator new (size_t, align_val_t); */
4510         newtype = build_function_type_list (ptr_type_node, size_type_node,
4511                                             align_type_node, NULL_TREE);
4512         newtype = cp_build_type_attribute_variant (newtype, newattrs);
4513         newtype = build_exception_variant (newtype, new_eh_spec);
4514         opnew = push_cp_library_fn (NEW_EXPR, newtype, 0);
4515         DECL_IS_MALLOC (opnew) = 1;
4516         DECL_SET_IS_OPERATOR_NEW (opnew, true);
4517         DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4518         opnew = push_cp_library_fn (VEC_NEW_EXPR, newtype, 0);
4519         DECL_IS_MALLOC (opnew) = 1;
4520         DECL_SET_IS_OPERATOR_NEW (opnew, true);
4521         DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4522
4523         /* operator delete (void *, align_val_t); */
4524         deltype = build_function_type_list (void_type_node, ptr_type_node,
4525                                             align_type_node, NULL_TREE);
4526         deltype = cp_build_type_attribute_variant (deltype, extvisattr);
4527         deltype = build_exception_variant (deltype, empty_except_spec);
4528         opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4529         DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4530         DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4531         opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4532         DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4533         DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4534
4535         if (flag_sized_deallocation)
4536           {
4537             /* operator delete (void *, size_t, align_val_t); */
4538             deltype = build_function_type_list (void_type_node, ptr_type_node,
4539                                                 size_type_node, align_type_node,
4540                                                 NULL_TREE);
4541             deltype = cp_build_type_attribute_variant (deltype, extvisattr);
4542             deltype = build_exception_variant (deltype, empty_except_spec);
4543             opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4544             DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4545             DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4546             opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4547             DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4548             DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4549           }
4550       }
4551
4552     nullptr_type_node = make_node (NULLPTR_TYPE);
4553     TYPE_SIZE (nullptr_type_node) = bitsize_int (GET_MODE_BITSIZE (ptr_mode));
4554     TYPE_SIZE_UNIT (nullptr_type_node) = size_int (GET_MODE_SIZE (ptr_mode));
4555     TYPE_UNSIGNED (nullptr_type_node) = 1;
4556     TYPE_PRECISION (nullptr_type_node) = GET_MODE_BITSIZE (ptr_mode);
4557     if (abi_version_at_least (9))
4558       SET_TYPE_ALIGN (nullptr_type_node, GET_MODE_ALIGNMENT (ptr_mode));
4559     SET_TYPE_MODE (nullptr_type_node, ptr_mode);
4560     record_builtin_type (RID_MAX, "decltype(nullptr)", nullptr_type_node);
4561     nullptr_node = build_int_cst (nullptr_type_node, 0);
4562   }
4563
4564   abort_fndecl
4565     = build_library_fn_ptr ("__cxa_pure_virtual", void_ftype,
4566                             ECF_NORETURN | ECF_NOTHROW | ECF_COLD);
4567   if (flag_weak)
4568     /* If no definition is available, resolve references to NULL.  */
4569     declare_weak (abort_fndecl);
4570
4571   /* Perform other language dependent initializations.  */
4572   init_class_processing ();
4573   init_rtti_processing ();
4574   init_template_processing ();
4575
4576   if (flag_exceptions)
4577     init_exception_processing ();
4578
4579   if (! supports_one_only ())
4580     flag_weak = 0;
4581
4582   make_fname_decl = cp_make_fname_decl;
4583   start_fname_decls ();
4584
4585   /* Show we use EH for cleanups.  */
4586   if (flag_exceptions)
4587     using_eh_for_cleanups ();
4588 }
4589
4590 /* Create the VAR_DECL for __FUNCTION__ etc. ID is the name to give
4591    the decl, LOC is the location to give the decl, NAME is the
4592    initialization string and TYPE_DEP indicates whether NAME depended
4593    on the type of the function. We make use of that to detect
4594    __PRETTY_FUNCTION__ inside a template fn. This is being done lazily
4595    at the point of first use, so we mustn't push the decl now.  */
4596
4597 static tree
4598 cp_make_fname_decl (location_t loc, tree id, int type_dep)
4599 {
4600   tree domain = NULL_TREE;
4601   tree init = NULL_TREE;
4602
4603   if (!(type_dep && in_template_function ()))
4604     {
4605       const char *name = NULL;
4606       bool release_name = false;
4607
4608       if (current_function_decl == NULL_TREE)
4609         name = "top level";
4610       else if (type_dep == 0)
4611         {
4612           /* __FUNCTION__ */      
4613           name = fname_as_string (type_dep);
4614           release_name = true;
4615         }
4616       else
4617         {
4618           /* __PRETTY_FUNCTION__ */
4619           gcc_checking_assert (type_dep == 1);
4620           name = cxx_printable_name (current_function_decl, 2);
4621         }
4622
4623       size_t length = strlen (name);
4624       domain = build_index_type (size_int (length));
4625       init = build_string (length + 1, name);
4626       if (release_name)
4627         free (const_cast<char *> (name));
4628     }
4629
4630   tree type = cp_build_qualified_type (char_type_node, TYPE_QUAL_CONST);
4631   type = build_cplus_array_type (type, domain);
4632
4633   if (init)
4634     TREE_TYPE (init) = type;
4635   else
4636     init = error_mark_node;
4637
4638   tree decl = build_decl (loc, VAR_DECL, id, type);
4639
4640   TREE_READONLY (decl) = 1;
4641   DECL_ARTIFICIAL (decl) = 1;
4642   DECL_DECLARED_CONSTEXPR_P (decl) = 1;
4643   TREE_STATIC (decl) = 1;
4644
4645   TREE_USED (decl) = 1;
4646
4647   SET_DECL_VALUE_EXPR (decl, init);
4648   DECL_HAS_VALUE_EXPR_P (decl) = 1;
4649   /* For decl_constant_var_p.  */
4650   DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = 1;
4651
4652   if (current_function_decl)
4653     {
4654       DECL_CONTEXT (decl) = current_function_decl;
4655       decl = pushdecl_outermost_localscope (decl);
4656       if (decl != error_mark_node)
4657         add_decl_expr (decl);
4658     }
4659   else
4660     {
4661       DECL_THIS_STATIC (decl) = true;
4662       decl = pushdecl_top_level_and_finish (decl, NULL_TREE);
4663     }
4664
4665   return decl;
4666 }
4667
4668 /* Install DECL as a builtin function at current global scope.  Return
4669    the new decl (if we found an existing version).  Also installs it
4670    into ::std, if it's not '_*'.  */
4671
4672 tree
4673 cxx_builtin_function (tree decl)
4674 {
4675   retrofit_lang_decl (decl);
4676
4677   DECL_ARTIFICIAL (decl) = 1;
4678   SET_DECL_LANGUAGE (decl, lang_c);
4679   /* Runtime library routines are, by definition, available in an
4680      external shared object.  */
4681   DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
4682   DECL_VISIBILITY_SPECIFIED (decl) = 1;
4683
4684   tree id = DECL_NAME (decl);
4685   const char *name = IDENTIFIER_POINTER (id);
4686   bool hiding = false;
4687   if (name[0] != '_' || name[1] != '_')
4688     /* In the user's namespace, it must be declared before use.  */
4689     hiding = true;
4690   else if (IDENTIFIER_LENGTH (id) > strlen ("___chk")
4691            && 0 != strncmp (name + 2, "builtin_", strlen ("builtin_"))
4692            && 0 == memcmp (name + IDENTIFIER_LENGTH (id) - strlen ("_chk"),
4693                            "_chk", strlen ("_chk") + 1))
4694     /* Treat __*_chk fortification functions as anticipated as well,
4695        unless they are __builtin_*_chk.  */
4696     hiding = true;
4697
4698   /* All builtins that don't begin with an '_' should additionally
4699      go in the 'std' namespace.  */
4700   if (name[0] != '_')
4701     {
4702       tree std_decl = copy_decl (decl);
4703
4704       push_nested_namespace (std_node);
4705       DECL_CONTEXT (std_decl) = FROB_CONTEXT (std_node);
4706       pushdecl (std_decl, hiding);
4707       pop_nested_namespace (std_node);
4708     }
4709
4710   DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4711   decl = pushdecl (decl, hiding);
4712
4713   return decl;
4714 }
4715
4716 /* Like cxx_builtin_function, but guarantee the function is added to the global
4717    scope.  This is to allow function specific options to add new machine
4718    dependent builtins when the target ISA changes via attribute((target(...)))
4719    which saves space on program startup if the program does not use non-generic
4720    ISAs.  */
4721
4722 tree
4723 cxx_builtin_function_ext_scope (tree decl)
4724 {
4725   push_nested_namespace (global_namespace);
4726   decl = cxx_builtin_function (decl);
4727   pop_nested_namespace (global_namespace);
4728
4729   return decl;
4730 }
4731
4732 /* Implement LANG_HOOKS_SIMULATE_BUILTIN_FUNCTION_DECL.  */
4733
4734 tree
4735 cxx_simulate_builtin_function_decl (tree decl)
4736 {
4737   retrofit_lang_decl (decl);
4738
4739   DECL_ARTIFICIAL (decl) = 1;
4740   SET_DECL_LANGUAGE (decl, lang_cplusplus);
4741   DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4742   return pushdecl (decl);
4743 }
4744
4745 /* Generate a FUNCTION_DECL with the typical flags for a runtime library
4746    function.  Not called directly.  */
4747
4748 static tree
4749 build_library_fn (tree name, enum tree_code operator_code, tree type,
4750                   int ecf_flags)
4751 {
4752   tree fn = build_lang_decl (FUNCTION_DECL, name, type);
4753   DECL_EXTERNAL (fn) = 1;
4754   TREE_PUBLIC (fn) = 1;
4755   DECL_ARTIFICIAL (fn) = 1;
4756   DECL_OVERLOADED_OPERATOR_CODE_RAW (fn)
4757     = OVL_OP_INFO (false, operator_code)->ovl_op_code;
4758   SET_DECL_LANGUAGE (fn, lang_c);
4759   /* Runtime library routines are, by definition, available in an
4760      external shared object.  */
4761   DECL_VISIBILITY (fn) = VISIBILITY_DEFAULT;
4762   DECL_VISIBILITY_SPECIFIED (fn) = 1;
4763   set_call_expr_flags (fn, ecf_flags);
4764   return fn;
4765 }
4766
4767 /* Returns the _DECL for a library function with C++ linkage.  */
4768
4769 static tree
4770 build_cp_library_fn (tree name, enum tree_code operator_code, tree type,
4771                      int ecf_flags)
4772 {
4773   tree fn = build_library_fn (name, operator_code, type, ecf_flags);
4774   DECL_CONTEXT (fn) = FROB_CONTEXT (current_namespace);
4775   SET_DECL_LANGUAGE (fn, lang_cplusplus);
4776   return fn;
4777 }
4778
4779 /* Like build_library_fn, but takes a C string instead of an
4780    IDENTIFIER_NODE.  */
4781
4782 tree
4783 build_library_fn_ptr (const char* name, tree type, int ecf_flags)
4784 {
4785   return build_library_fn (get_identifier (name), ERROR_MARK, type, ecf_flags);
4786 }
4787
4788 /* Like build_cp_library_fn, but takes a C string instead of an
4789    IDENTIFIER_NODE.  */
4790
4791 tree
4792 build_cp_library_fn_ptr (const char* name, tree type, int ecf_flags)
4793 {
4794   return build_cp_library_fn (get_identifier (name), ERROR_MARK, type,
4795                               ecf_flags);
4796 }
4797
4798 /* Like build_library_fn, but also pushes the function so that we will
4799    be able to find it via get_global_binding.  Also, the function
4800    may throw exceptions listed in RAISES.  */
4801
4802 tree
4803 push_library_fn (tree name, tree type, tree raises, int ecf_flags)
4804 {
4805   if (raises)
4806     type = build_exception_variant (type, raises);
4807
4808   tree fn = build_library_fn (name, ERROR_MARK, type, ecf_flags);
4809   return pushdecl_top_level (fn);
4810 }
4811
4812 /* Like build_cp_library_fn, but also pushes the function so that it
4813    will be found by normal lookup.  */
4814
4815 static tree
4816 push_cp_library_fn (enum tree_code operator_code, tree type,
4817                     int ecf_flags)
4818 {
4819   tree fn = build_cp_library_fn (ovl_op_identifier (false, operator_code),
4820                                  operator_code, type, ecf_flags);
4821   pushdecl (fn);
4822   if (flag_tm)
4823     apply_tm_attr (fn, get_identifier ("transaction_safe"));
4824   return fn;
4825 }
4826
4827 /* Like push_library_fn, but takes a TREE_LIST of parm types rather than
4828    a FUNCTION_TYPE.  */
4829
4830 tree
4831 push_void_library_fn (tree name, tree parmtypes, int ecf_flags)
4832 {
4833   tree type = build_function_type (void_type_node, parmtypes);
4834   return push_library_fn (name, type, NULL_TREE, ecf_flags);
4835 }
4836
4837 /* Like push_library_fn, but also note that this function throws
4838    and does not return.  Used for __throw_foo and the like.  */
4839
4840 tree
4841 push_throw_library_fn (tree name, tree type)
4842 {
4843   tree fn = push_library_fn (name, type, NULL_TREE, ECF_NORETURN | ECF_COLD);
4844   return fn;
4845 }
4846 \f
4847 /* When we call finish_struct for an anonymous union, we create
4848    default copy constructors and such.  But, an anonymous union
4849    shouldn't have such things; this function undoes the damage to the
4850    anonymous union type T.
4851
4852    (The reason that we create the synthesized methods is that we don't
4853    distinguish `union { int i; }' from `typedef union { int i; } U'.
4854    The first is an anonymous union; the second is just an ordinary
4855    union type.)  */
4856
4857 void
4858 fixup_anonymous_aggr (tree t)
4859 {
4860   /* Wipe out memory of synthesized methods.  */
4861   TYPE_HAS_USER_CONSTRUCTOR (t) = 0;
4862   TYPE_HAS_DEFAULT_CONSTRUCTOR (t) = 0;
4863   TYPE_HAS_COPY_CTOR (t) = 0;
4864   TYPE_HAS_CONST_COPY_CTOR (t) = 0;
4865   TYPE_HAS_COPY_ASSIGN (t) = 0;
4866   TYPE_HAS_CONST_COPY_ASSIGN (t) = 0;
4867
4868   /* Splice the implicitly generated functions out of TYPE_FIELDS.  */
4869   for (tree probe, *prev_p = &TYPE_FIELDS (t); (probe = *prev_p);)
4870     if (TREE_CODE (probe) == FUNCTION_DECL && DECL_ARTIFICIAL (probe))
4871       *prev_p = DECL_CHAIN (probe);
4872     else
4873       prev_p = &DECL_CHAIN (probe);
4874
4875   /* Anonymous aggregates cannot have fields with ctors, dtors or complex
4876      assignment operators (because they cannot have these methods themselves).
4877      For anonymous unions this is already checked because they are not allowed
4878      in any union, otherwise we have to check it.  */
4879   if (TREE_CODE (t) != UNION_TYPE)
4880     {
4881       tree field, type;
4882
4883       for (field = TYPE_FIELDS (t); field; field = DECL_CHAIN (field))
4884         if (TREE_CODE (field) == FIELD_DECL)
4885           {
4886             type = TREE_TYPE (field);
4887             if (CLASS_TYPE_P (type))
4888               {
4889                 if (TYPE_NEEDS_CONSTRUCTING (type))
4890                   error ("member %q+#D with constructor not allowed "
4891                          "in anonymous aggregate", field);
4892                 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
4893                   error ("member %q+#D with destructor not allowed "
4894                          "in anonymous aggregate", field);
4895                 if (TYPE_HAS_COMPLEX_COPY_ASSIGN (type))
4896                   error ("member %q+#D with copy assignment operator "
4897                          "not allowed in anonymous aggregate", field);
4898               }
4899           }
4900     }
4901 }
4902
4903 /* Warn for an attribute located at LOCATION that appertains to the
4904    class type CLASS_TYPE that has not been properly placed after its
4905    class-key, in it class-specifier.  */
4906
4907 void
4908 warn_misplaced_attr_for_class_type (location_t location,
4909                                     tree class_type)
4910 {
4911   gcc_assert (OVERLOAD_TYPE_P (class_type));
4912
4913   auto_diagnostic_group d;
4914   if (warning_at (location, OPT_Wattributes,
4915                   "attribute ignored in declaration "
4916                   "of %q#T", class_type))
4917     inform (location,
4918             "attribute for %q#T must follow the %qs keyword",
4919             class_type, class_key_or_enum_as_string (class_type));
4920 }
4921
4922 /* Returns the cv-qualifiers that apply to the type specified
4923    by the DECLSPECS.  */
4924
4925 static int
4926 get_type_quals (const cp_decl_specifier_seq *declspecs)
4927 {
4928   int type_quals = TYPE_UNQUALIFIED;
4929
4930   if (decl_spec_seq_has_spec_p (declspecs, ds_const))
4931     type_quals |= TYPE_QUAL_CONST;
4932   if (decl_spec_seq_has_spec_p (declspecs, ds_volatile))
4933     type_quals |= TYPE_QUAL_VOLATILE;
4934   if (decl_spec_seq_has_spec_p (declspecs, ds_restrict))
4935     type_quals |= TYPE_QUAL_RESTRICT;
4936
4937   return type_quals;
4938 }
4939
4940 /* Make sure that a declaration with no declarator is well-formed, i.e.
4941    just declares a tagged type or anonymous union.
4942
4943    Returns the type declared; or NULL_TREE if none.  */
4944
4945 tree
4946 check_tag_decl (cp_decl_specifier_seq *declspecs,
4947                 bool explicit_type_instantiation_p)
4948 {
4949   int saw_friend = decl_spec_seq_has_spec_p (declspecs, ds_friend);
4950   int saw_typedef = decl_spec_seq_has_spec_p (declspecs, ds_typedef);
4951   /* If a class, struct, or enum type is declared by the DECLSPECS
4952      (i.e, if a class-specifier, enum-specifier, or non-typename
4953      elaborated-type-specifier appears in the DECLSPECS),
4954      DECLARED_TYPE is set to the corresponding type.  */
4955   tree declared_type = NULL_TREE;
4956   bool error_p = false;
4957
4958   if (declspecs->multiple_types_p)
4959     error_at (smallest_type_location (declspecs),
4960               "multiple types in one declaration");
4961   else if (declspecs->redefined_builtin_type)
4962     {
4963       location_t loc = declspecs->locations[ds_redefined_builtin_type_spec];
4964       if (!in_system_header_at (loc))
4965         permerror (loc, "redeclaration of C++ built-in type %qT",
4966                    declspecs->redefined_builtin_type);
4967       return NULL_TREE;
4968     }
4969
4970   if (declspecs->type
4971       && TYPE_P (declspecs->type)
4972       && ((TREE_CODE (declspecs->type) != TYPENAME_TYPE
4973            && MAYBE_CLASS_TYPE_P (declspecs->type))
4974           || TREE_CODE (declspecs->type) == ENUMERAL_TYPE))
4975     declared_type = declspecs->type;
4976   else if (declspecs->type == error_mark_node)
4977     error_p = true;
4978
4979   if (type_uses_auto (declared_type))
4980     {
4981       error_at (declspecs->locations[ds_type_spec],
4982                 "%<auto%> can only be specified for variables "
4983                 "or function declarations");
4984       return error_mark_node;
4985     }
4986
4987   if (declared_type && !OVERLOAD_TYPE_P (declared_type))
4988     declared_type = NULL_TREE;
4989
4990   if (!declared_type && !saw_friend && !error_p)
4991     permerror (input_location, "declaration does not declare anything");
4992   /* Check for an anonymous union.  */
4993   else if (declared_type && RECORD_OR_UNION_CODE_P (TREE_CODE (declared_type))
4994            && TYPE_UNNAMED_P (declared_type))
4995     {
4996       /* 7/3 In a simple-declaration, the optional init-declarator-list
4997          can be omitted only when declaring a class (clause 9) or
4998          enumeration (7.2), that is, when the decl-specifier-seq contains
4999          either a class-specifier, an elaborated-type-specifier with
5000          a class-key (9.1), or an enum-specifier.  In these cases and
5001          whenever a class-specifier or enum-specifier is present in the
5002          decl-specifier-seq, the identifiers in these specifiers are among
5003          the names being declared by the declaration (as class-name,
5004          enum-names, or enumerators, depending on the syntax).  In such
5005          cases, and except for the declaration of an unnamed bit-field (9.6),
5006          the decl-specifier-seq shall introduce one or more names into the
5007          program, or shall redeclare a name introduced by a previous
5008          declaration.  [Example:
5009              enum { };                  // ill-formed
5010              typedef class { };         // ill-formed
5011          --end example]  */
5012       if (saw_typedef)
5013         {
5014           error_at (declspecs->locations[ds_typedef],
5015                     "missing type-name in typedef-declaration");
5016           return NULL_TREE;
5017         }
5018       /* Anonymous unions are objects, so they can have specifiers.  */;
5019       SET_ANON_AGGR_TYPE_P (declared_type);
5020
5021       if (TREE_CODE (declared_type) != UNION_TYPE)
5022         pedwarn (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (declared_type)),
5023                  OPT_Wpedantic, "ISO C++ prohibits anonymous structs");
5024     }
5025
5026   else
5027     {
5028       if (decl_spec_seq_has_spec_p (declspecs, ds_inline))
5029         error_at (declspecs->locations[ds_inline],
5030                   "%<inline%> can only be specified for functions");
5031       else if (decl_spec_seq_has_spec_p (declspecs, ds_virtual))
5032         error_at (declspecs->locations[ds_virtual],
5033                   "%<virtual%> can only be specified for functions");
5034       else if (saw_friend
5035                && (!current_class_type
5036                    || current_scope () != current_class_type))
5037         error_at (declspecs->locations[ds_friend],
5038                   "%<friend%> can only be specified inside a class");
5039       else if (decl_spec_seq_has_spec_p (declspecs, ds_explicit))
5040         error_at (declspecs->locations[ds_explicit],
5041                   "%<explicit%> can only be specified for constructors");
5042       else if (declspecs->storage_class)
5043         error_at (declspecs->locations[ds_storage_class],
5044                   "a storage class can only be specified for objects "
5045                   "and functions");
5046       else if (decl_spec_seq_has_spec_p (declspecs, ds_const))
5047         error_at (declspecs->locations[ds_const],
5048                   "%<const%> can only be specified for objects and "
5049                   "functions");
5050       else if (decl_spec_seq_has_spec_p (declspecs, ds_volatile))
5051         error_at (declspecs->locations[ds_volatile],
5052                   "%<volatile%> can only be specified for objects and "
5053                   "functions");
5054       else if (decl_spec_seq_has_spec_p (declspecs, ds_restrict))
5055         error_at (declspecs->locations[ds_restrict],
5056                   "%<__restrict%> can only be specified for objects and "
5057                   "functions");
5058       else if (decl_spec_seq_has_spec_p (declspecs, ds_thread))
5059         error_at (declspecs->locations[ds_thread],
5060                   "%<__thread%> can only be specified for objects "
5061                   "and functions");
5062       else if (saw_typedef)
5063         warning_at (declspecs->locations[ds_typedef], 0,
5064                     "%<typedef%> was ignored in this declaration");
5065       else if (decl_spec_seq_has_spec_p (declspecs, ds_constexpr))
5066         error_at (declspecs->locations[ds_constexpr],
5067                   "%qs cannot be used for type declarations", "constexpr");
5068       else if (decl_spec_seq_has_spec_p (declspecs, ds_constinit))
5069         error_at (declspecs->locations[ds_constinit],
5070                   "%qs cannot be used for type declarations", "constinit");
5071       else if (decl_spec_seq_has_spec_p (declspecs, ds_consteval))
5072         error_at (declspecs->locations[ds_consteval],
5073                   "%qs cannot be used for type declarations", "consteval");
5074     }
5075
5076   if (declspecs->attributes && warn_attributes && declared_type)
5077     {
5078       location_t loc;
5079       if (!CLASS_TYPE_P (declared_type)
5080           || !CLASSTYPE_TEMPLATE_INSTANTIATION (declared_type))
5081         /* For a non-template class, use the name location.  */
5082         loc = location_of (declared_type);
5083       else
5084         /* For a template class (an explicit instantiation), use the
5085            current location.  */
5086         loc = input_location;
5087
5088       if (explicit_type_instantiation_p)
5089         /* [dcl.attr.grammar]/4:
5090
5091                No attribute-specifier-seq shall appertain to an explicit
5092                instantiation.  */
5093         {
5094           if (warning_at (loc, OPT_Wattributes,
5095                           "attribute ignored in explicit instantiation %q#T",
5096                           declared_type))
5097             inform (loc,
5098                     "no attribute can be applied to "
5099                     "an explicit instantiation");
5100         }
5101       else
5102         warn_misplaced_attr_for_class_type (loc, declared_type);
5103     }
5104
5105   return declared_type;
5106 }
5107
5108 /* Called when a declaration is seen that contains no names to declare.
5109    If its type is a reference to a structure, union or enum inherited
5110    from a containing scope, shadow that tag name for the current scope
5111    with a forward reference.
5112    If its type defines a new named structure or union
5113    or defines an enum, it is valid but we need not do anything here.
5114    Otherwise, it is an error.
5115
5116    C++: may have to grok the declspecs to learn about static,
5117    complain for anonymous unions.
5118
5119    Returns the TYPE declared -- or NULL_TREE if none.  */
5120
5121 tree
5122 shadow_tag (cp_decl_specifier_seq *declspecs)
5123 {
5124   tree t = check_tag_decl (declspecs,
5125                            /*explicit_type_instantiation_p=*/false);
5126
5127   if (!t)
5128     return NULL_TREE;
5129
5130   if (maybe_process_partial_specialization (t) == error_mark_node)
5131     return NULL_TREE;
5132
5133   /* This is where the variables in an anonymous union are
5134      declared.  An anonymous union declaration looks like:
5135      union { ... } ;
5136      because there is no declarator after the union, the parser
5137      sends that declaration here.  */
5138   if (ANON_AGGR_TYPE_P (t))
5139     {
5140       fixup_anonymous_aggr (t);
5141
5142       if (TYPE_FIELDS (t))
5143         {
5144           tree decl = grokdeclarator (/*declarator=*/NULL,
5145                                       declspecs, NORMAL, 0, NULL);
5146           finish_anon_union (decl);
5147         }
5148     }
5149
5150   return t;
5151 }
5152 \f
5153 /* Decode a "typename", such as "int **", returning a ..._TYPE node.  */
5154
5155 tree
5156 groktypename (cp_decl_specifier_seq *type_specifiers,
5157               const cp_declarator *declarator,
5158               bool is_template_arg)
5159 {
5160   tree attrs;
5161   tree type;
5162   enum decl_context context
5163     = is_template_arg ? TEMPLATE_TYPE_ARG : TYPENAME;
5164   attrs = type_specifiers->attributes;
5165   type_specifiers->attributes = NULL_TREE;
5166   type = grokdeclarator (declarator, type_specifiers, context, 0, &attrs);
5167   if (attrs && type != error_mark_node)
5168     {
5169       if (CLASS_TYPE_P (type))
5170         warning (OPT_Wattributes, "ignoring attributes applied to class type %qT "
5171                  "outside of definition", type);
5172       else if (MAYBE_CLASS_TYPE_P (type))
5173         /* A template type parameter or other dependent type.  */
5174         warning (OPT_Wattributes, "ignoring attributes applied to dependent "
5175                  "type %qT without an associated declaration", type);
5176       else
5177         cplus_decl_attributes (&type, attrs, 0);
5178     }
5179   return type;
5180 }
5181
5182 /* Process a DECLARATOR for a function-scope or namespace-scope
5183    variable or function declaration.
5184    (Function definitions go through start_function; class member
5185    declarations appearing in the body of the class go through
5186    grokfield.)  The DECL corresponding to the DECLARATOR is returned.
5187    If an error occurs, the error_mark_node is returned instead.
5188
5189    DECLSPECS are the decl-specifiers for the declaration.  INITIALIZED is
5190    SD_INITIALIZED if an explicit initializer is present, or SD_DEFAULTED
5191    for an explicitly defaulted function, or SD_DELETED for an explicitly
5192    deleted function, but 0 (SD_UNINITIALIZED) if this is a variable
5193    implicitly initialized via a default constructor.  It can also be
5194    SD_DECOMPOSITION which behaves much like SD_INITIALIZED, but we also
5195    mark the new decl as DECL_DECOMPOSITION_P.
5196
5197    ATTRIBUTES and PREFIX_ATTRIBUTES are GNU attributes associated with this
5198    declaration.
5199
5200    The scope represented by the context of the returned DECL is pushed
5201    (if it is not the global namespace) and is assigned to
5202    *PUSHED_SCOPE_P.  The caller is then responsible for calling
5203    pop_scope on *PUSHED_SCOPE_P if it is set.  */
5204
5205 tree
5206 start_decl (const cp_declarator *declarator,
5207             cp_decl_specifier_seq *declspecs,
5208             int initialized,
5209             tree attributes,
5210             tree prefix_attributes,
5211             tree *pushed_scope_p)
5212 {
5213   tree decl;
5214   tree context;
5215   bool was_public;
5216   int flags;
5217   bool alias;
5218
5219   *pushed_scope_p = NULL_TREE;
5220
5221   attributes = chainon (attributes, prefix_attributes);
5222
5223   decl = grokdeclarator (declarator, declspecs, NORMAL, initialized,
5224                          &attributes);
5225
5226   if (decl == NULL_TREE || VOID_TYPE_P (decl)
5227       || decl == error_mark_node)
5228     return error_mark_node;
5229
5230   context = CP_DECL_CONTEXT (decl);
5231   if (context != global_namespace)
5232     *pushed_scope_p = push_scope (context);
5233
5234   if (initialized && TREE_CODE (decl) == TYPE_DECL)
5235     {
5236       error_at (DECL_SOURCE_LOCATION (decl),
5237                 "typedef %qD is initialized (use %qs instead)",
5238                 decl, "decltype");
5239       return error_mark_node;
5240     }
5241
5242   if (initialized)
5243     {
5244       if (! toplevel_bindings_p ()
5245           && DECL_EXTERNAL (decl))
5246         warning (0, "declaration of %q#D has %<extern%> and is initialized",
5247                  decl);
5248       DECL_EXTERNAL (decl) = 0;
5249       if (toplevel_bindings_p ())
5250         TREE_STATIC (decl) = 1;
5251     }
5252   alias = lookup_attribute ("alias", DECL_ATTRIBUTES (decl)) != 0;
5253   
5254   if (alias && TREE_CODE (decl) == FUNCTION_DECL)
5255     record_key_method_defined (decl);
5256
5257   /* If this is a typedef that names the class for linkage purposes
5258      (7.1.3p8), apply any attributes directly to the type.  */
5259   if (TREE_CODE (decl) == TYPE_DECL
5260       && OVERLOAD_TYPE_P (TREE_TYPE (decl))
5261       && decl == TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (decl))))
5262     flags = ATTR_FLAG_TYPE_IN_PLACE;
5263   else
5264     flags = 0;
5265
5266   /* Set attributes here so if duplicate decl, will have proper attributes.  */
5267   cplus_decl_attributes (&decl, attributes, flags);
5268
5269   /* Dllimported symbols cannot be defined.  Static data members (which
5270      can be initialized in-class and dllimported) go through grokfield,
5271      not here, so we don't need to exclude those decls when checking for
5272      a definition.  */
5273   if (initialized && DECL_DLLIMPORT_P (decl))
5274     {
5275       error_at (DECL_SOURCE_LOCATION (decl),
5276                 "definition of %q#D is marked %<dllimport%>", decl);
5277       DECL_DLLIMPORT_P (decl) = 0;
5278     }
5279
5280   /* If #pragma weak was used, mark the decl weak now.  */
5281   if (!processing_template_decl && !DECL_DECOMPOSITION_P (decl))
5282     maybe_apply_pragma_weak (decl);
5283
5284   if (TREE_CODE (decl) == FUNCTION_DECL
5285       && DECL_DECLARED_INLINE_P (decl)
5286       && DECL_UNINLINABLE (decl)
5287       && lookup_attribute ("noinline", DECL_ATTRIBUTES (decl)))
5288     warning_at (DECL_SOURCE_LOCATION (decl), 0,
5289                 "inline function %qD given attribute %qs", decl, "noinline");
5290
5291   if (TYPE_P (context) && COMPLETE_TYPE_P (complete_type (context)))
5292     {
5293       bool this_tmpl = (processing_template_decl
5294                         > template_class_depth (context));
5295       if (VAR_P (decl))
5296         {
5297           tree field = lookup_field (context, DECL_NAME (decl), 0, false);
5298           if (field == NULL_TREE
5299               || !(VAR_P (field) || variable_template_p (field)))
5300             error ("%q+#D is not a static data member of %q#T", decl, context);
5301           else if (variable_template_p (field)
5302                    && (DECL_LANG_SPECIFIC (decl)
5303                        && DECL_TEMPLATE_SPECIALIZATION (decl)))
5304             /* OK, specialization was already checked.  */;
5305           else if (variable_template_p (field) && !this_tmpl)
5306             {
5307               error_at (DECL_SOURCE_LOCATION (decl),
5308                         "non-member-template declaration of %qD", decl);
5309               inform (DECL_SOURCE_LOCATION (field), "does not match "
5310                       "member template declaration here");
5311               return error_mark_node;
5312             }
5313           else
5314             {
5315               if (variable_template_p (field))
5316                 field = DECL_TEMPLATE_RESULT (field);
5317
5318               if (DECL_CONTEXT (field) != context)
5319                 {
5320                   if (!same_type_p (DECL_CONTEXT (field), context))
5321                     permerror (input_location, "ISO C++ does not permit %<%T::%D%> "
5322                                "to be defined as %<%T::%D%>",
5323                                DECL_CONTEXT (field), DECL_NAME (decl),
5324                                context, DECL_NAME (decl));
5325                   DECL_CONTEXT (decl) = DECL_CONTEXT (field);
5326                 }
5327               /* Static data member are tricky; an in-class initialization
5328                  still doesn't provide a definition, so the in-class
5329                  declaration will have DECL_EXTERNAL set, but will have an
5330                  initialization.  Thus, duplicate_decls won't warn
5331                  about this situation, and so we check here.  */
5332               if (initialized && DECL_INITIALIZED_IN_CLASS_P (field))
5333                 error ("duplicate initialization of %qD", decl);
5334               field = duplicate_decls (decl, field);
5335               if (field == error_mark_node)
5336                 return error_mark_node;
5337               else if (field)
5338                 decl = field;
5339             }
5340         }
5341       else
5342         {
5343           tree field = check_classfn (context, decl,
5344                                       this_tmpl
5345                                       ? current_template_parms
5346                                       : NULL_TREE);
5347           if (field && field != error_mark_node
5348               && duplicate_decls (decl, field))
5349             decl = field;
5350         }
5351
5352       /* cp_finish_decl sets DECL_EXTERNAL if DECL_IN_AGGR_P is set.  */
5353       DECL_IN_AGGR_P (decl) = 0;
5354       /* Do not mark DECL as an explicit specialization if it was not
5355          already marked as an instantiation; a declaration should
5356          never be marked as a specialization unless we know what
5357          template is being specialized.  */
5358       if (DECL_LANG_SPECIFIC (decl) && DECL_USE_TEMPLATE (decl))
5359         {
5360           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
5361           if (TREE_CODE (decl) == FUNCTION_DECL)
5362             DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
5363                                   && DECL_DECLARED_INLINE_P (decl));
5364           else
5365             DECL_COMDAT (decl) = false;
5366
5367           /* [temp.expl.spec] An explicit specialization of a static data
5368              member of a template is a definition if the declaration
5369              includes an initializer; otherwise, it is a declaration.
5370
5371              We check for processing_specialization so this only applies
5372              to the new specialization syntax.  */
5373           if (!initialized && processing_specialization)
5374             DECL_EXTERNAL (decl) = 1;
5375         }
5376
5377       if (DECL_EXTERNAL (decl) && ! DECL_TEMPLATE_SPECIALIZATION (decl)
5378           /* Aliases are definitions. */
5379           && !alias)
5380         permerror (declarator->id_loc,
5381                    "declaration of %q#D outside of class is not definition",
5382                    decl);
5383     }
5384
5385   /* Create a DECL_LANG_SPECIFIC so that DECL_DECOMPOSITION_P works.  */
5386   if (initialized == SD_DECOMPOSITION)
5387     fit_decomposition_lang_decl (decl, NULL_TREE);
5388
5389   was_public = TREE_PUBLIC (decl);
5390
5391   if ((DECL_EXTERNAL (decl) || TREE_CODE (decl) == FUNCTION_DECL)
5392       && current_function_decl)
5393     /* A function-scope decl of some namespace-scope decl.  */
5394     DECL_LOCAL_DECL_P (decl) = true;
5395
5396   /* Enter this declaration into the symbol table.  Don't push the plain
5397      VAR_DECL for a variable template.  */
5398   if (!template_parm_scope_p ()
5399       || !VAR_P (decl))
5400     decl = maybe_push_decl (decl);
5401
5402   if (processing_template_decl)
5403     decl = push_template_decl (decl);
5404
5405   if (decl == error_mark_node)
5406     return error_mark_node;
5407
5408   if (VAR_P (decl)
5409       && DECL_NAMESPACE_SCOPE_P (decl) && !TREE_PUBLIC (decl) && !was_public
5410       && !DECL_THIS_STATIC (decl) && !DECL_ARTIFICIAL (decl))
5411     {
5412       /* This is a const variable with implicit 'static'.  Set
5413          DECL_THIS_STATIC so we can tell it from variables that are
5414          !TREE_PUBLIC because of the anonymous namespace.  */
5415       gcc_assert (CP_TYPE_CONST_P (TREE_TYPE (decl)) || errorcount);
5416       DECL_THIS_STATIC (decl) = 1;
5417     }
5418
5419   if (current_function_decl && VAR_P (decl)
5420       && DECL_DECLARED_CONSTEXPR_P (current_function_decl))
5421     {
5422       bool ok = false;
5423       if (CP_DECL_THREAD_LOCAL_P (decl))
5424         error_at (DECL_SOURCE_LOCATION (decl),
5425                   "%qD declared %<thread_local%> in %qs function", decl,
5426                   DECL_IMMEDIATE_FUNCTION_P (current_function_decl)
5427                   ? "consteval" : "constexpr");
5428       else if (TREE_STATIC (decl))
5429         error_at (DECL_SOURCE_LOCATION (decl),
5430                   "%qD declared %<static%> in %qs function", decl,
5431                   DECL_IMMEDIATE_FUNCTION_P (current_function_decl)
5432                   ? "consteval" : "constexpr");
5433       else
5434         ok = true;
5435       if (!ok)
5436         cp_function_chain->invalid_constexpr = true;
5437     }
5438
5439   if (!processing_template_decl && VAR_P (decl))
5440     start_decl_1 (decl, initialized);
5441
5442   return decl;
5443 }
5444
5445 /* Process the declaration of a variable DECL.  INITIALIZED is true
5446    iff DECL is explicitly initialized.  (INITIALIZED is false if the
5447    variable is initialized via an implicitly-called constructor.)
5448    This function must be called for ordinary variables (including, for
5449    example, implicit instantiations of templates), but must not be
5450    called for template declarations.  */
5451
5452 void
5453 start_decl_1 (tree decl, bool initialized)
5454 {
5455   tree type;
5456   bool complete_p;
5457   bool aggregate_definition_p;
5458
5459   gcc_assert (!processing_template_decl);
5460
5461   if (error_operand_p (decl))
5462     return;
5463
5464   gcc_assert (VAR_P (decl));
5465
5466   type = TREE_TYPE (decl);
5467   complete_p = COMPLETE_TYPE_P (type);
5468   aggregate_definition_p = MAYBE_CLASS_TYPE_P (type) && !DECL_EXTERNAL (decl);
5469
5470   /* If an explicit initializer is present, or if this is a definition
5471      of an aggregate, then we need a complete type at this point.
5472      (Scalars are always complete types, so there is nothing to
5473      check.)  This code just sets COMPLETE_P; errors (if necessary)
5474      are issued below.  */
5475   if ((initialized || aggregate_definition_p) 
5476       && !complete_p
5477       && COMPLETE_TYPE_P (complete_type (type)))
5478     {
5479       complete_p = true;
5480       /* We will not yet have set TREE_READONLY on DECL if the type
5481          was "const", but incomplete, before this point.  But, now, we
5482          have a complete type, so we can try again.  */
5483       cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
5484     }
5485
5486   if (is_global_var (decl))
5487     {
5488       type_context_kind context = (DECL_THREAD_LOCAL_P (decl)
5489                                    ? TCTX_THREAD_STORAGE
5490                                    : TCTX_STATIC_STORAGE);
5491       verify_type_context (input_location, context, TREE_TYPE (decl));
5492     }
5493   if (initialized)
5494     /* Is it valid for this decl to have an initializer at all?  */
5495     {
5496       /* Don't allow initializations for incomplete types except for
5497          arrays which might be completed by the initialization.  */
5498       if (complete_p)
5499         ;                       /* A complete type is ok.  */
5500       else if (type_uses_auto (type))
5501         ;                       /* An auto type is ok.  */
5502       else if (TREE_CODE (type) != ARRAY_TYPE)
5503         {
5504           error ("variable %q#D has initializer but incomplete type", decl);
5505           type = TREE_TYPE (decl) = error_mark_node;
5506         }
5507       else if (!COMPLETE_TYPE_P (complete_type (TREE_TYPE (type))))
5508         {
5509           if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
5510             error ("elements of array %q#D have incomplete type", decl);
5511           /* else we already gave an error in start_decl.  */
5512         }
5513     }
5514   else if (aggregate_definition_p && !complete_p)
5515     {
5516       if (type_uses_auto (type))
5517         gcc_assert (CLASS_PLACEHOLDER_TEMPLATE (type));
5518       else
5519         {
5520           error ("aggregate %q#D has incomplete type and cannot be defined",
5521                  decl);
5522           /* Change the type so that assemble_variable will give
5523              DECL an rtl we can live with: (mem (const_int 0)).  */
5524           type = TREE_TYPE (decl) = error_mark_node;
5525         }
5526     }
5527
5528   /* Create a new scope to hold this declaration if necessary.
5529      Whether or not a new scope is necessary cannot be determined
5530      until after the type has been completed; if the type is a
5531      specialization of a class template it is not until after
5532      instantiation has occurred that TYPE_HAS_NONTRIVIAL_DESTRUCTOR
5533      will be set correctly.  */
5534   maybe_push_cleanup_level (type);
5535 }
5536
5537 /* Given a parenthesized list of values INIT, create a CONSTRUCTOR to handle
5538    C++20 P0960.  TYPE is the type of the object we're initializing.  */
5539
5540 tree
5541 do_aggregate_paren_init (tree init, tree type)
5542 {
5543   tree val = TREE_VALUE (init);
5544
5545   if (TREE_CHAIN (init) == NULL_TREE)
5546     {
5547       /* If the list has a single element and it's a string literal,
5548          then it's the initializer for the array as a whole.  */
5549       if (TREE_CODE (type) == ARRAY_TYPE
5550           && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type)))
5551           && TREE_CODE (tree_strip_any_location_wrapper (val))
5552              == STRING_CST)
5553         return val;
5554       /* Handle non-standard extensions like compound literals.  This also
5555          prevents triggering aggregate parenthesized-initialization in
5556          compiler-generated code for =default.  */
5557       else if (same_type_ignoring_top_level_qualifiers_p (type,
5558                                                           TREE_TYPE (val)))
5559         return val;
5560     }
5561
5562   init = build_constructor_from_list (init_list_type_node, init);
5563   CONSTRUCTOR_IS_DIRECT_INIT (init) = true;
5564   CONSTRUCTOR_IS_PAREN_INIT (init) = true;
5565   return init;
5566 }
5567
5568 /* Handle initialization of references.  DECL, TYPE, and INIT have the
5569    same meaning as in cp_finish_decl.  *CLEANUP must be NULL on entry,
5570    but will be set to a new CLEANUP_STMT if a temporary is created
5571    that must be destroyed subsequently.
5572
5573    Returns an initializer expression to use to initialize DECL, or
5574    NULL if the initialization can be performed statically.
5575
5576    Quotes on semantics can be found in ARM 8.4.3.  */
5577
5578 static tree
5579 grok_reference_init (tree decl, tree type, tree init, int flags)
5580 {
5581   if (init == NULL_TREE)
5582     {
5583       if ((DECL_LANG_SPECIFIC (decl) == 0
5584            || DECL_IN_AGGR_P (decl) == 0)
5585           && ! DECL_THIS_EXTERN (decl))
5586         error_at (DECL_SOURCE_LOCATION (decl),
5587                   "%qD declared as reference but not initialized", decl);
5588       return NULL_TREE;
5589     }
5590
5591   tree ttype = TREE_TYPE (type);
5592   if (TREE_CODE (init) == TREE_LIST)
5593     {
5594       /* This handles (C++20 only) code like
5595
5596            const A& r(1, 2, 3);
5597
5598          where we treat the parenthesized list as a CONSTRUCTOR.  */
5599       if (TREE_TYPE (init) == NULL_TREE
5600           && CP_AGGREGATE_TYPE_P (ttype)
5601           && !DECL_DECOMPOSITION_P (decl)
5602           && (cxx_dialect >= cxx20))
5603         {
5604           /* We don't know yet if we should treat const A& r(1) as
5605              const A& r{1}.  */
5606           if (list_length (init) == 1)
5607             {
5608               flags |= LOOKUP_AGGREGATE_PAREN_INIT;
5609               init = build_x_compound_expr_from_list (init, ELK_INIT,
5610                                                       tf_warning_or_error);
5611             }
5612           /* If the list had more than one element, the code is ill-formed
5613              pre-C++20, so we can build a constructor right away.  */
5614           else
5615             init = do_aggregate_paren_init (init, ttype);
5616         }
5617       else
5618         init = build_x_compound_expr_from_list (init, ELK_INIT,
5619                                                 tf_warning_or_error);
5620     }
5621
5622   if (TREE_CODE (ttype) != ARRAY_TYPE
5623       && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
5624     /* Note: default conversion is only called in very special cases.  */
5625     init = decay_conversion (init, tf_warning_or_error);
5626
5627   /* check_initializer handles this for non-reference variables, but for
5628      references we need to do it here or the initializer will get the
5629      incomplete array type and confuse later calls to
5630      cp_complete_array_type.  */
5631   if (TREE_CODE (ttype) == ARRAY_TYPE
5632       && TYPE_DOMAIN (ttype) == NULL_TREE
5633       && (BRACE_ENCLOSED_INITIALIZER_P (init)
5634           || TREE_CODE (init) == STRING_CST))
5635     {
5636       cp_complete_array_type (&ttype, init, false);
5637       if (ttype != TREE_TYPE (type))
5638         type = cp_build_reference_type (ttype, TYPE_REF_IS_RVALUE (type));
5639     }
5640
5641   /* Convert INIT to the reference type TYPE.  This may involve the
5642      creation of a temporary, whose lifetime must be the same as that
5643      of the reference.  If so, a DECL_EXPR for the temporary will be
5644      added just after the DECL_EXPR for DECL.  That's why we don't set
5645      DECL_INITIAL for local references (instead assigning to them
5646      explicitly); we need to allow the temporary to be initialized
5647      first.  */
5648   return initialize_reference (type, init, flags,
5649                                tf_warning_or_error);
5650 }
5651
5652 /* Designated initializers in arrays are not supported in GNU C++.
5653    The parser cannot detect this error since it does not know whether
5654    a given brace-enclosed initializer is for a class type or for an
5655    array.  This function checks that CE does not use a designated
5656    initializer.  If it does, an error is issued.  Returns true if CE
5657    is valid, i.e., does not have a designated initializer.  */
5658
5659 bool
5660 check_array_designated_initializer (constructor_elt *ce,
5661                                     unsigned HOST_WIDE_INT index)
5662 {
5663   /* Designated initializers for array elements are not supported.  */
5664   if (ce->index)
5665     {
5666       /* The parser only allows identifiers as designated
5667          initializers.  */
5668       if (ce->index == error_mark_node)
5669         {
5670           error ("name used in a GNU-style designated "
5671                  "initializer for an array");
5672           return false;
5673         }
5674       else if (identifier_p (ce->index))
5675         {
5676           error ("name %qD used in a GNU-style designated "
5677                  "initializer for an array", ce->index);
5678           return false;
5679         }
5680
5681       tree ce_index = build_expr_type_conversion (WANT_INT | WANT_ENUM,
5682                                                   ce->index, true);
5683       if (ce_index
5684           && INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (ce_index))
5685           && (TREE_CODE (ce_index = fold_non_dependent_expr (ce_index))
5686               == INTEGER_CST))
5687         {
5688           /* A C99 designator is OK if it matches the current index.  */
5689           if (wi::to_wide (ce_index) == index)
5690             {
5691               ce->index = ce_index;
5692               return true;
5693             }
5694           else
5695             sorry ("non-trivial designated initializers not supported");
5696         }
5697       else
5698         error_at (cp_expr_loc_or_input_loc (ce->index),
5699                   "C99 designator %qE is not an integral constant-expression",
5700                   ce->index);
5701
5702       return false;
5703     }
5704
5705   return true;
5706 }
5707
5708 /* When parsing `int a[] = {1, 2};' we don't know the size of the
5709    array until we finish parsing the initializer.  If that's the
5710    situation we're in, update DECL accordingly.  */
5711
5712 static void
5713 maybe_deduce_size_from_array_init (tree decl, tree init)
5714 {
5715   tree type = TREE_TYPE (decl);
5716
5717   if (TREE_CODE (type) == ARRAY_TYPE
5718       && TYPE_DOMAIN (type) == NULL_TREE
5719       && TREE_CODE (decl) != TYPE_DECL)
5720     {
5721       /* do_default is really a C-ism to deal with tentative definitions.
5722          But let's leave it here to ease the eventual merge.  */
5723       int do_default = !DECL_EXTERNAL (decl);
5724       tree initializer = init ? init : DECL_INITIAL (decl);
5725       int failure = 0;
5726
5727       /* Check that there are no designated initializers in INIT, as
5728          those are not supported in GNU C++, and as the middle-end
5729          will crash if presented with a non-numeric designated
5730          initializer.  */
5731       if (initializer && BRACE_ENCLOSED_INITIALIZER_P (initializer))
5732         {
5733           vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (initializer);
5734           constructor_elt *ce;
5735           HOST_WIDE_INT i;
5736           FOR_EACH_VEC_SAFE_ELT (v, i, ce)
5737             {
5738               if (instantiation_dependent_expression_p (ce->index))
5739                 return;
5740               if (!check_array_designated_initializer (ce, i))
5741                 failure = 1;
5742             }
5743         }
5744
5745       if (failure)
5746         TREE_TYPE (decl) = error_mark_node;
5747       else
5748         {
5749           failure = cp_complete_array_type (&TREE_TYPE (decl), initializer,
5750                                             do_default);
5751           if (failure == 1)
5752             {
5753               error_at (cp_expr_loc_or_loc (initializer,
5754                                          DECL_SOURCE_LOCATION (decl)),
5755                         "initializer fails to determine size of %qD", decl);
5756             }
5757           else if (failure == 2)
5758             {
5759               if (do_default)
5760                 {
5761                   error_at (DECL_SOURCE_LOCATION (decl),
5762                             "array size missing in %qD", decl);
5763                 }
5764               /* If a `static' var's size isn't known, make it extern as
5765                  well as static, so it does not get allocated.  If it's not
5766                  `static', then don't mark it extern; finish_incomplete_decl
5767                  will give it a default size and it will get allocated.  */
5768               else if (!pedantic && TREE_STATIC (decl) && !TREE_PUBLIC (decl))
5769                 DECL_EXTERNAL (decl) = 1;
5770             }
5771           else if (failure == 3)
5772             {
5773               error_at (DECL_SOURCE_LOCATION (decl),
5774                         "zero-size array %qD", decl);
5775             }
5776         }
5777
5778       cp_apply_type_quals_to_decl (cp_type_quals (TREE_TYPE (decl)), decl);
5779
5780       relayout_decl (decl);
5781     }
5782 }
5783
5784 /* Set DECL_SIZE, DECL_ALIGN, etc. for DECL (a VAR_DECL), and issue
5785    any appropriate error messages regarding the layout.  */
5786
5787 static void
5788 layout_var_decl (tree decl)
5789 {
5790   tree type;
5791
5792   type = TREE_TYPE (decl);
5793   if (type == error_mark_node)
5794     return;
5795
5796   /* If we haven't already laid out this declaration, do so now.
5797      Note that we must not call complete type for an external object
5798      because it's type might involve templates that we are not
5799      supposed to instantiate yet.  (And it's perfectly valid to say
5800      `extern X x' for some incomplete type `X'.)  */
5801   if (!DECL_EXTERNAL (decl))
5802     complete_type (type);
5803   if (!DECL_SIZE (decl)
5804       && TREE_TYPE (decl) != error_mark_node
5805       && complete_or_array_type_p (type))
5806     layout_decl (decl, 0);
5807
5808   if (!DECL_EXTERNAL (decl) && DECL_SIZE (decl) == NULL_TREE)
5809     {
5810       /* An automatic variable with an incomplete type: that is an error.
5811          Don't talk about array types here, since we took care of that
5812          message in grokdeclarator.  */
5813       error_at (DECL_SOURCE_LOCATION (decl),
5814                 "storage size of %qD isn%'t known", decl);
5815       TREE_TYPE (decl) = error_mark_node;
5816     }
5817 #if 0
5818   /* Keep this code around in case we later want to control debug info
5819      based on whether a type is "used".  (jason 1999-11-11) */
5820
5821   else if (!DECL_EXTERNAL (decl) && MAYBE_CLASS_TYPE_P (ttype))
5822     /* Let debugger know it should output info for this type.  */
5823     note_debug_info_needed (ttype);
5824
5825   if (TREE_STATIC (decl) && DECL_CLASS_SCOPE_P (decl))
5826     note_debug_info_needed (DECL_CONTEXT (decl));
5827 #endif
5828
5829   if ((DECL_EXTERNAL (decl) || TREE_STATIC (decl))
5830       && DECL_SIZE (decl) != NULL_TREE
5831       && ! TREE_CONSTANT (DECL_SIZE (decl)))
5832     {
5833       if (TREE_CODE (DECL_SIZE (decl)) == INTEGER_CST)
5834         constant_expression_warning (DECL_SIZE (decl));
5835       else
5836         {
5837           error_at (DECL_SOURCE_LOCATION (decl),
5838                     "storage size of %qD isn%'t constant", decl);
5839           TREE_TYPE (decl) = error_mark_node;
5840         }
5841     }
5842 }
5843
5844 /* If a local static variable is declared in an inline function, or if
5845    we have a weak definition, we must endeavor to create only one
5846    instance of the variable at link-time.  */
5847
5848 void
5849 maybe_commonize_var (tree decl)
5850 {
5851   /* Don't mess with __FUNCTION__ and similar.  */
5852   if (DECL_ARTIFICIAL (decl))
5853     return;
5854
5855   /* Static data in a function with comdat linkage also has comdat
5856      linkage.  */
5857   if ((TREE_STATIC (decl)
5858        && DECL_FUNCTION_SCOPE_P (decl)
5859        && vague_linkage_p (DECL_CONTEXT (decl)))
5860       || (TREE_PUBLIC (decl) && DECL_INLINE_VAR_P (decl)))
5861     {
5862       if (flag_weak)
5863         {
5864           /* With weak symbols, we simply make the variable COMDAT;
5865              that will cause copies in multiple translations units to
5866              be merged.  */
5867           comdat_linkage (decl);
5868         }
5869       else
5870         {
5871           if (DECL_INITIAL (decl) == NULL_TREE
5872               || DECL_INITIAL (decl) == error_mark_node)
5873             {
5874               /* Without weak symbols, we can use COMMON to merge
5875                  uninitialized variables.  */
5876               TREE_PUBLIC (decl) = 1;
5877               DECL_COMMON (decl) = 1;
5878             }
5879           else
5880             {
5881               /* While for initialized variables, we must use internal
5882                  linkage -- which means that multiple copies will not
5883                  be merged.  */
5884               TREE_PUBLIC (decl) = 0;
5885               DECL_COMMON (decl) = 0;
5886               DECL_INTERFACE_KNOWN (decl) = 1;
5887               const char *msg;
5888               if (DECL_INLINE_VAR_P (decl))
5889                 msg = G_("sorry: semantics of inline variable "
5890                          "%q#D are wrong (you%'ll wind up with "
5891                          "multiple copies)");
5892               else
5893                 msg = G_("sorry: semantics of inline function "
5894                          "static data %q#D are wrong (you%'ll wind "
5895                          "up with multiple copies)");
5896               if (warning_at (DECL_SOURCE_LOCATION (decl), 0,
5897                               msg, decl))
5898                 inform (DECL_SOURCE_LOCATION (decl),
5899                         "you can work around this by removing the initializer");
5900             }
5901         }
5902     }
5903 }
5904
5905 /* Issue an error message if DECL is an uninitialized const variable.
5906    CONSTEXPR_CONTEXT_P is true when the function is called in a constexpr
5907    context from potential_constant_expression.  Returns true if all is well,
5908    false otherwise.  */
5909
5910 bool
5911 check_for_uninitialized_const_var (tree decl, bool constexpr_context_p,
5912                                    tsubst_flags_t complain)
5913 {
5914   tree type = strip_array_types (TREE_TYPE (decl));
5915
5916   /* ``Unless explicitly declared extern, a const object does not have
5917      external linkage and must be initialized. ($8.4; $12.1)'' ARM
5918      7.1.6 */
5919   if (VAR_P (decl)
5920       && !TYPE_REF_P (type)
5921       && (CP_TYPE_CONST_P (type)
5922           /* C++20 permits trivial default initialization in constexpr
5923              context (P1331R2).  */
5924           || (cxx_dialect < cxx20
5925               && (constexpr_context_p
5926                   || var_in_constexpr_fn (decl))))
5927       && !DECL_NONTRIVIALLY_INITIALIZED_P (decl))
5928     {
5929       tree field = default_init_uninitialized_part (type);
5930       if (!field)
5931         return true;
5932
5933       bool show_notes = true;
5934
5935       if (!constexpr_context_p || cxx_dialect >= cxx20)
5936         {
5937           if (CP_TYPE_CONST_P (type))
5938             {
5939               if (complain & tf_error)
5940                 show_notes = permerror (DECL_SOURCE_LOCATION (decl),
5941                                         "uninitialized %<const %D%>", decl);
5942             }
5943           else
5944             {
5945               if (!is_instantiation_of_constexpr (current_function_decl)
5946                   && (complain & tf_error))
5947                 error_at (DECL_SOURCE_LOCATION (decl),
5948                           "uninitialized variable %qD in %<constexpr%> "
5949                           "function", decl);
5950               else
5951                 show_notes = false;
5952               cp_function_chain->invalid_constexpr = true;
5953             }
5954         }
5955       else if (complain & tf_error)
5956         error_at (DECL_SOURCE_LOCATION (decl),
5957                   "uninitialized variable %qD in %<constexpr%> context",
5958                   decl);
5959
5960       if (show_notes && CLASS_TYPE_P (type) && (complain & tf_error))
5961         {
5962           tree defaulted_ctor;
5963
5964           inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)),
5965                   "%q#T has no user-provided default constructor", type);
5966           defaulted_ctor = in_class_defaulted_default_constructor (type);
5967           if (defaulted_ctor)
5968             inform (DECL_SOURCE_LOCATION (defaulted_ctor),
5969                     "constructor is not user-provided because it is "
5970                     "explicitly defaulted in the class body");
5971           inform (DECL_SOURCE_LOCATION (field),
5972                   "and the implicitly-defined constructor does not "
5973                   "initialize %q#D", field);
5974         }
5975
5976       return false;
5977     }
5978
5979   return true;
5980 }
5981 \f
5982 /* Structure holding the current initializer being processed by reshape_init.
5983    CUR is a pointer to the current element being processed, END is a pointer
5984    after the last element present in the initializer.  */
5985 struct reshape_iter
5986 {
5987   constructor_elt *cur;
5988   constructor_elt *end;
5989 };
5990
5991 static tree reshape_init_r (tree, reshape_iter *, tree, tsubst_flags_t);
5992
5993 /* FIELD is a FIELD_DECL or NULL.  In the former case, the value
5994    returned is the next FIELD_DECL (possibly FIELD itself) that can be
5995    initialized.  If there are no more such fields, the return value
5996    will be NULL.  */
5997
5998 tree
5999 next_initializable_field (tree field)
6000 {
6001   while (field
6002          && (TREE_CODE (field) != FIELD_DECL
6003              || DECL_UNNAMED_BIT_FIELD (field)
6004              || (DECL_ARTIFICIAL (field)
6005                  /* In C++17, don't skip base class fields.  */
6006                  && !(cxx_dialect >= cxx17 && DECL_FIELD_IS_BASE (field))
6007                  /* Don't skip vptr fields.  We might see them when we're
6008                     called from reduced_constant_expression_p.  */
6009                  && !DECL_VIRTUAL_P (field))))
6010     field = DECL_CHAIN (field);
6011
6012   return field;
6013 }
6014
6015 /* Return true for [dcl.init.list] direct-list-initialization from
6016    single element of enumeration with a fixed underlying type.  */
6017
6018 bool
6019 is_direct_enum_init (tree type, tree init)
6020 {
6021   if (cxx_dialect >= cxx17
6022       && TREE_CODE (type) == ENUMERAL_TYPE
6023       && ENUM_FIXED_UNDERLYING_TYPE_P (type)
6024       && TREE_CODE (init) == CONSTRUCTOR
6025       && CONSTRUCTOR_IS_DIRECT_INIT (init)
6026       && CONSTRUCTOR_NELTS (init) == 1)
6027     return true;
6028   return false;
6029 }
6030
6031 /* Subroutine of reshape_init_array and reshape_init_vector, which does
6032    the actual work. ELT_TYPE is the element type of the array. MAX_INDEX is an
6033    INTEGER_CST representing the size of the array minus one (the maximum index),
6034    or NULL_TREE if the array was declared without specifying the size. D is
6035    the iterator within the constructor.  */
6036
6037 static tree
6038 reshape_init_array_1 (tree elt_type, tree max_index, reshape_iter *d,
6039                       tree first_initializer_p, tsubst_flags_t complain)
6040 {
6041   tree new_init;
6042   bool sized_array_p = (max_index && TREE_CONSTANT (max_index));
6043   unsigned HOST_WIDE_INT max_index_cst = 0;
6044   unsigned HOST_WIDE_INT index;
6045
6046   /* The initializer for an array is always a CONSTRUCTOR.  If this is the
6047      outermost CONSTRUCTOR and the element type is non-aggregate, we don't need
6048      to build a new one.  But don't reuse if not complaining; if this is
6049      tentative, we might also reshape to another type (95319).  */
6050   bool reuse = (first_initializer_p
6051                 && (complain & tf_error)
6052                 && !CP_AGGREGATE_TYPE_P (elt_type)
6053                 && !TREE_SIDE_EFFECTS (first_initializer_p));
6054   if (reuse)
6055     new_init = first_initializer_p;
6056   else
6057     new_init = build_constructor (init_list_type_node, NULL);
6058
6059   if (sized_array_p)
6060     {
6061       /* Minus 1 is used for zero sized arrays.  */
6062       if (integer_all_onesp (max_index))
6063         return new_init;
6064
6065       if (tree_fits_uhwi_p (max_index))
6066         max_index_cst = tree_to_uhwi (max_index);
6067       /* sizetype is sign extended, not zero extended.  */
6068       else
6069         max_index_cst = tree_to_uhwi (fold_convert (size_type_node, max_index));
6070     }
6071
6072   /* Loop until there are no more initializers.  */
6073   for (index = 0;
6074        d->cur != d->end && (!sized_array_p || index <= max_index_cst);
6075        ++index)
6076     {
6077       tree elt_init;
6078       constructor_elt *old_cur = d->cur;
6079
6080       check_array_designated_initializer (d->cur, index);
6081       elt_init = reshape_init_r (elt_type, d,
6082                                  /*first_initializer_p=*/NULL_TREE,
6083                                  complain);
6084       if (elt_init == error_mark_node)
6085         return error_mark_node;
6086       tree idx = size_int (index);
6087       if (reuse)
6088         {
6089           old_cur->index = idx;
6090           old_cur->value = elt_init;
6091         }
6092       else
6093         CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init),
6094                                 idx, elt_init);
6095       if (!TREE_CONSTANT (elt_init))
6096         TREE_CONSTANT (new_init) = false;
6097
6098       /* This can happen with an invalid initializer (c++/54501).  */
6099       if (d->cur == old_cur && !sized_array_p)
6100         break;
6101     }
6102
6103   return new_init;
6104 }
6105
6106 /* Subroutine of reshape_init_r, processes the initializers for arrays.
6107    Parameters are the same of reshape_init_r.  */
6108
6109 static tree
6110 reshape_init_array (tree type, reshape_iter *d, tree first_initializer_p,
6111                     tsubst_flags_t complain)
6112 {
6113   tree max_index = NULL_TREE;
6114
6115   gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
6116
6117   if (TYPE_DOMAIN (type))
6118     max_index = array_type_nelts (type);
6119
6120   return reshape_init_array_1 (TREE_TYPE (type), max_index, d,
6121                                first_initializer_p, complain);
6122 }
6123
6124 /* Subroutine of reshape_init_r, processes the initializers for vectors.
6125    Parameters are the same of reshape_init_r.  */
6126
6127 static tree
6128 reshape_init_vector (tree type, reshape_iter *d, tsubst_flags_t complain)
6129 {
6130   tree max_index = NULL_TREE;
6131
6132   gcc_assert (VECTOR_TYPE_P (type));
6133
6134   if (COMPOUND_LITERAL_P (d->cur->value))
6135     {
6136       tree value = d->cur->value;
6137       if (!same_type_p (TREE_TYPE (value), type))
6138         {
6139           if (complain & tf_error)
6140             error ("invalid type %qT as initializer for a vector of type %qT",
6141                    TREE_TYPE (d->cur->value), type);
6142           value = error_mark_node;
6143         }
6144       ++d->cur;
6145       return value;
6146     }
6147
6148   /* For a vector, we initialize it as an array of the appropriate size.  */
6149   if (VECTOR_TYPE_P (type))
6150     max_index = size_int (TYPE_VECTOR_SUBPARTS (type) - 1);
6151
6152   return reshape_init_array_1 (TREE_TYPE (type), max_index, d,
6153                                NULL_TREE, complain);
6154 }
6155
6156 /* Subroutine of reshape_init_r, processes the initializers for classes
6157    or union. Parameters are the same of reshape_init_r.  */
6158
6159 static tree
6160 reshape_init_class (tree type, reshape_iter *d, bool first_initializer_p,
6161                     tsubst_flags_t complain)
6162 {
6163   tree field;
6164   tree new_init;
6165
6166   gcc_assert (CLASS_TYPE_P (type));
6167
6168   /* The initializer for a class is always a CONSTRUCTOR.  */
6169   new_init = build_constructor (init_list_type_node, NULL);
6170
6171   int binfo_idx = -1;
6172   tree binfo = TYPE_BINFO (type);
6173   tree base_binfo = NULL_TREE;
6174   if (cxx_dialect >= cxx17 && uses_template_parms (type))
6175     {
6176       /* We get here from maybe_aggr_guide for C++20 class template argument
6177          deduction.  In this case we need to look through the binfo because a
6178          template doesn't have base fields.  */
6179       binfo_idx = 0;
6180       BINFO_BASE_ITERATE (binfo, binfo_idx, base_binfo);
6181     }
6182   if (base_binfo)
6183     field = base_binfo;
6184   else
6185     field = next_initializable_field (TYPE_FIELDS (type));
6186
6187   if (!field)
6188     {
6189       /* [dcl.init.aggr]
6190
6191         An initializer for an aggregate member that is an
6192         empty class shall have the form of an empty
6193         initializer-list {}.  */
6194       if (!first_initializer_p)
6195         {
6196           if (complain & tf_error)
6197             error ("initializer for %qT must be brace-enclosed", type);
6198           return error_mark_node;
6199         }
6200       return new_init;
6201     }
6202
6203   /* For C++20 CTAD, handle pack expansions in the base list.  */
6204   tree last_was_pack_expansion = NULL_TREE;
6205
6206   /* Loop through the initializable fields, gathering initializers.  */
6207   while (d->cur != d->end)
6208     {
6209       tree field_init;
6210       constructor_elt *old_cur = d->cur;
6211
6212       /* Handle designated initializers, as an extension.  */
6213       if (d->cur->index)
6214         {
6215           if (d->cur->index == error_mark_node)
6216             return error_mark_node;
6217
6218           if (TREE_CODE (d->cur->index) == FIELD_DECL)
6219             {
6220               /* We already reshaped this.  */
6221               if (field != d->cur->index)
6222                 {
6223                   tree id = DECL_NAME (d->cur->index);
6224                   gcc_assert (id);
6225                   gcc_checking_assert (d->cur->index
6226                                        == get_class_binding (type, id));
6227                   field = d->cur->index;
6228                 }
6229             }
6230           else if (TREE_CODE (d->cur->index) == IDENTIFIER_NODE)
6231             field = get_class_binding (type, d->cur->index);
6232           else
6233             {
6234               if (complain & tf_error)
6235                 error ("%<[%E] =%> used in a GNU-style designated initializer"
6236                        " for class %qT", d->cur->index, type);
6237               return error_mark_node;
6238             }
6239
6240           if (!field || TREE_CODE (field) != FIELD_DECL)
6241             {
6242               if (complain & tf_error)
6243                 error ("%qT has no non-static data member named %qD", type,
6244                        d->cur->index);
6245               return error_mark_node;
6246             }
6247         }
6248
6249       /* If we processed all the member of the class, we are done.  */
6250       if (!field)
6251         break;
6252
6253       last_was_pack_expansion = (PACK_EXPANSION_P (TREE_TYPE (field))
6254                                  ? field : NULL_TREE);
6255       if (last_was_pack_expansion)
6256         /* Each non-trailing aggregate element that is a pack expansion is
6257            assumed to correspond to no elements of the initializer list.  */
6258         goto continue_;
6259
6260       field_init = reshape_init_r (TREE_TYPE (field), d,
6261                                    /*first_initializer_p=*/NULL_TREE,
6262                                    complain);
6263       if (field_init == error_mark_node)
6264         return error_mark_node;
6265
6266       if (d->cur == old_cur && d->cur->index)
6267         {
6268           /* This can happen with an invalid initializer for a flexible
6269              array member (c++/54441).  */
6270           if (complain & tf_error)
6271             error ("invalid initializer for %q#D", field);
6272           return error_mark_node;
6273         }
6274
6275       CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init), field, field_init);
6276
6277       /* [dcl.init.aggr]
6278
6279         When a union  is  initialized with a brace-enclosed
6280         initializer, the braces shall only contain an
6281         initializer for the first member of the union.  */
6282       if (TREE_CODE (type) == UNION_TYPE)
6283         break;
6284
6285     continue_:
6286       if (base_binfo)
6287         {
6288           BINFO_BASE_ITERATE (binfo, ++binfo_idx, base_binfo);
6289           if (base_binfo)
6290             field = base_binfo;
6291           else
6292             field = next_initializable_field (TYPE_FIELDS (type));
6293         }
6294       else
6295         field = next_initializable_field (DECL_CHAIN (field));
6296     }
6297
6298   /* A trailing aggregate element that is a pack expansion is assumed to
6299      correspond to all remaining elements of the initializer list (if any).  */
6300   if (last_was_pack_expansion)
6301     {
6302       CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init),
6303                               last_was_pack_expansion, d->cur->value);
6304       while (d->cur != d->end)
6305         d->cur++;
6306     }
6307
6308   return new_init;
6309 }
6310
6311 /* Subroutine of reshape_init_r.  We're in a context where C99 initializer
6312    designators are not valid; either complain or return true to indicate
6313    that reshape_init_r should return error_mark_node.  */
6314
6315 static bool
6316 has_designator_problem (reshape_iter *d, tsubst_flags_t complain)
6317 {
6318   if (d->cur->index)
6319     {
6320       if (complain & tf_error)
6321         error_at (cp_expr_loc_or_input_loc (d->cur->index),
6322                   "C99 designator %qE outside aggregate initializer",
6323                   d->cur->index);
6324       else
6325         return true;
6326     }
6327   return false;
6328 }
6329
6330 /* Subroutine of reshape_init, which processes a single initializer (part of
6331    a CONSTRUCTOR). TYPE is the type of the variable being initialized, D is the
6332    iterator within the CONSTRUCTOR which points to the initializer to process.
6333    If this is the first initializer of the outermost CONSTRUCTOR node,
6334    FIRST_INITIALIZER_P is that CONSTRUCTOR; otherwise, it is NULL_TREE.  */
6335
6336 static tree
6337 reshape_init_r (tree type, reshape_iter *d, tree first_initializer_p,
6338                 tsubst_flags_t complain)
6339 {
6340   tree init = d->cur->value;
6341
6342   if (error_operand_p (init))
6343     return error_mark_node;
6344
6345   if (first_initializer_p && !CP_AGGREGATE_TYPE_P (type)
6346       && has_designator_problem (d, complain))
6347     return error_mark_node;
6348
6349   tree stripped_init = tree_strip_any_location_wrapper (init);
6350
6351   if (TREE_CODE (type) == COMPLEX_TYPE)
6352     {
6353       /* A complex type can be initialized from one or two initializers,
6354          but braces are not elided.  */
6355       d->cur++;
6356       if (BRACE_ENCLOSED_INITIALIZER_P (stripped_init))
6357         {
6358           if (CONSTRUCTOR_NELTS (stripped_init) > 2)
6359             {
6360               if (complain & tf_error)
6361                 error ("too many initializers for %qT", type);
6362               else
6363                 return error_mark_node;
6364             }
6365         }
6366       else if (first_initializer_p && d->cur != d->end)
6367         {
6368           vec<constructor_elt, va_gc> *v = 0;
6369           CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, init);
6370           CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, d->cur->value);
6371           if (has_designator_problem (d, complain))
6372             return error_mark_node;
6373           d->cur++;
6374           init = build_constructor (init_list_type_node, v);
6375         }
6376       return init;
6377     }
6378
6379   /* A non-aggregate type is always initialized with a single
6380      initializer.  */
6381   if (!CP_AGGREGATE_TYPE_P (type)
6382       /* As is an array with dependent bound.  */
6383       || (cxx_dialect >= cxx20
6384           && TREE_CODE (type) == ARRAY_TYPE
6385           && uses_template_parms (TYPE_DOMAIN (type))))
6386     {
6387       /* It is invalid to initialize a non-aggregate type with a
6388          brace-enclosed initializer before C++0x.
6389          We need to check for BRACE_ENCLOSED_INITIALIZER_P here because
6390          of g++.old-deja/g++.mike/p7626.C: a pointer-to-member constant is
6391          a CONSTRUCTOR (with a record type).  */
6392       if (TREE_CODE (stripped_init) == CONSTRUCTOR
6393           /* Don't complain about a capture-init.  */
6394           && !CONSTRUCTOR_IS_DIRECT_INIT (stripped_init)
6395           && BRACE_ENCLOSED_INITIALIZER_P (stripped_init))  /* p7626.C */
6396         {
6397           if (SCALAR_TYPE_P (type))
6398             {
6399               if (cxx_dialect < cxx11)
6400                 {
6401                   if (complain & tf_error)
6402                     error ("braces around scalar initializer for type %qT",
6403                            type);
6404                   init = error_mark_node;
6405                 }
6406               else if (first_initializer_p
6407                        || (CONSTRUCTOR_NELTS (stripped_init) > 0
6408                            && (BRACE_ENCLOSED_INITIALIZER_P
6409                                (CONSTRUCTOR_ELT (stripped_init,0)->value))))
6410                 {
6411                   if (complain & tf_error)
6412                     error ("too many braces around scalar initializer "
6413                            "for type %qT", type);
6414                   init = error_mark_node;
6415                 }
6416             }
6417           else
6418             maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
6419         }
6420
6421       d->cur++;
6422       return init;
6423     }
6424
6425   /* "If T is a class type and the initializer list has a single element of
6426      type cv U, where U is T or a class derived from T, the object is
6427      initialized from that element."  Even if T is an aggregate.  */
6428   if (cxx_dialect >= cxx11 && (CLASS_TYPE_P (type) || VECTOR_TYPE_P (type))
6429       && first_initializer_p
6430       && d->end - d->cur == 1
6431       && reference_related_p (type, TREE_TYPE (init)))
6432     {
6433       d->cur++;
6434       return init;
6435     }
6436
6437   /* [dcl.init.aggr]
6438
6439      All implicit type conversions (clause _conv_) are considered when
6440      initializing the aggregate member with an initializer from an
6441      initializer-list.  If the initializer can initialize a member,
6442      the member is initialized.  Otherwise, if the member is itself a
6443      non-empty subaggregate, brace elision is assumed and the
6444      initializer is considered for the initialization of the first
6445      member of the subaggregate.  */
6446   if ((TREE_CODE (init) != CONSTRUCTOR || COMPOUND_LITERAL_P (init))
6447       /* But don't try this for the first initializer, since that would be
6448          looking through the outermost braces; A a2 = { a1 }; is not a
6449          valid aggregate initialization.  */
6450       && !first_initializer_p
6451       && (same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (init))
6452           || can_convert_arg (type, TREE_TYPE (init), init, LOOKUP_NORMAL,
6453                               complain)))
6454     {
6455       d->cur++;
6456       return init;
6457     }
6458
6459   /* [dcl.init.string]
6460
6461       A char array (whether plain char, signed char, or unsigned char)
6462       can be initialized by a string-literal (optionally enclosed in
6463       braces); a wchar_t array can be initialized by a wide
6464       string-literal (optionally enclosed in braces).  */
6465   if (TREE_CODE (type) == ARRAY_TYPE
6466       && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type))))
6467     {
6468       tree str_init = init;
6469       tree stripped_str_init = stripped_init;
6470
6471       /* Strip one level of braces if and only if they enclose a single
6472          element (as allowed by [dcl.init.string]).  */
6473       if (!first_initializer_p
6474           && TREE_CODE (stripped_str_init) == CONSTRUCTOR
6475           && CONSTRUCTOR_NELTS (stripped_str_init) == 1)
6476         {
6477           str_init = (*CONSTRUCTOR_ELTS (stripped_str_init))[0].value;
6478           stripped_str_init = tree_strip_any_location_wrapper (str_init);
6479         }
6480
6481       /* If it's a string literal, then it's the initializer for the array
6482          as a whole. Otherwise, continue with normal initialization for
6483          array types (one value per array element).  */
6484       if (TREE_CODE (stripped_str_init) == STRING_CST)
6485         {
6486           if (has_designator_problem (d, complain))
6487             return error_mark_node;
6488           d->cur++;
6489           return str_init;
6490         }
6491     }
6492
6493   /* The following cases are about aggregates. If we are not within a full
6494      initializer already, and there is not a CONSTRUCTOR, it means that there
6495      is a missing set of braces (that is, we are processing the case for
6496      which reshape_init exists).  */
6497   if (!first_initializer_p)
6498     {
6499       if (TREE_CODE (stripped_init) == CONSTRUCTOR)
6500         {
6501           tree init_type = TREE_TYPE (init);
6502           if (init_type && TYPE_PTRMEMFUNC_P (init_type))
6503             /* There is no need to call reshape_init for pointer-to-member
6504                function initializers, as they are always constructed correctly
6505                by the front end.  Here we have e.g. {.__pfn=0B, .__delta=0},
6506                which is missing outermost braces.  We should warn below, and
6507                one of the routines below will wrap it in additional { }.  */;
6508           /* For a nested compound literal, proceed to specialized routines,
6509              to handle initialization of arrays and similar.  */
6510           else if (COMPOUND_LITERAL_P (stripped_init))
6511             gcc_assert (!BRACE_ENCLOSED_INITIALIZER_P (stripped_init));
6512           /* A CONSTRUCTOR of the target's type is a previously
6513              digested initializer.  */
6514           else if (same_type_ignoring_top_level_qualifiers_p (type, init_type))
6515             {
6516               ++d->cur;
6517               return init;
6518             }
6519           else
6520             {
6521               /* Something that hasn't been reshaped yet.  */
6522               ++d->cur;
6523               gcc_assert (BRACE_ENCLOSED_INITIALIZER_P (stripped_init));
6524               return reshape_init (type, init, complain);
6525             }
6526         }
6527
6528       if (complain & tf_warning)
6529         warning (OPT_Wmissing_braces,
6530                  "missing braces around initializer for %qT",
6531                  type);
6532     }
6533
6534   /* Dispatch to specialized routines.  */
6535   if (CLASS_TYPE_P (type))
6536     return reshape_init_class (type, d, first_initializer_p, complain);
6537   else if (TREE_CODE (type) == ARRAY_TYPE)
6538     return reshape_init_array (type, d, first_initializer_p, complain);
6539   else if (VECTOR_TYPE_P (type))
6540     return reshape_init_vector (type, d, complain);
6541   else
6542     gcc_unreachable();
6543 }
6544
6545 /* Undo the brace-elision allowed by [dcl.init.aggr] in a
6546    brace-enclosed aggregate initializer.
6547
6548    INIT is the CONSTRUCTOR containing the list of initializers describing
6549    a brace-enclosed initializer for an entity of the indicated aggregate TYPE.
6550    It may not presently match the shape of the TYPE; for example:
6551
6552      struct S { int a; int b; };
6553      struct S a[] = { 1, 2, 3, 4 };
6554
6555    Here INIT will hold a vector of four elements, rather than a
6556    vector of two elements, each itself a vector of two elements.  This
6557    routine transforms INIT from the former form into the latter.  The
6558    revised CONSTRUCTOR node is returned.  */
6559
6560 tree
6561 reshape_init (tree type, tree init, tsubst_flags_t complain)
6562 {
6563   vec<constructor_elt, va_gc> *v;
6564   reshape_iter d;
6565   tree new_init;
6566
6567   gcc_assert (BRACE_ENCLOSED_INITIALIZER_P (init));
6568
6569   v = CONSTRUCTOR_ELTS (init);
6570
6571   /* An empty constructor does not need reshaping, and it is always a valid
6572      initializer.  */
6573   if (vec_safe_is_empty (v))
6574     return init;
6575
6576   /* Brace elision is not performed for a CONSTRUCTOR representing
6577      parenthesized aggregate initialization.  */
6578   if (CONSTRUCTOR_IS_PAREN_INIT (init))
6579     {
6580       tree elt = (*v)[0].value;
6581       /* If we're initializing a char array from a string-literal that is
6582          enclosed in braces, unwrap it here.  */
6583       if (TREE_CODE (type) == ARRAY_TYPE
6584           && vec_safe_length (v) == 1
6585           && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type)))
6586           && TREE_CODE (tree_strip_any_location_wrapper (elt)) == STRING_CST)
6587         return elt;
6588       return init;
6589     }
6590
6591   /* Handle [dcl.init.list] direct-list-initialization from
6592      single element of enumeration with a fixed underlying type.  */
6593   if (is_direct_enum_init (type, init))
6594     {
6595       tree elt = CONSTRUCTOR_ELT (init, 0)->value;
6596       type = cv_unqualified (type);
6597       if (check_narrowing (ENUM_UNDERLYING_TYPE (type), elt, complain))
6598         {
6599           warning_sentinel w (warn_useless_cast);
6600           warning_sentinel w2 (warn_ignored_qualifiers);
6601           return cp_build_c_cast (input_location, type, elt,
6602                                   tf_warning_or_error);
6603         }
6604       else
6605         return error_mark_node;
6606     }
6607
6608   /* Recurse on this CONSTRUCTOR.  */
6609   d.cur = &(*v)[0];
6610   d.end = d.cur + v->length ();
6611
6612   new_init = reshape_init_r (type, &d, init, complain);
6613   if (new_init == error_mark_node)
6614     return error_mark_node;
6615
6616   /* Make sure all the element of the constructor were used. Otherwise,
6617      issue an error about exceeding initializers.  */
6618   if (d.cur != d.end)
6619     {
6620       if (complain & tf_error)
6621         error ("too many initializers for %qT", type);
6622       return error_mark_node;
6623     }
6624
6625   if (CONSTRUCTOR_IS_DIRECT_INIT (init)
6626       && BRACE_ENCLOSED_INITIALIZER_P (new_init))
6627     CONSTRUCTOR_IS_DIRECT_INIT (new_init) = true;
6628   if (CONSTRUCTOR_IS_DESIGNATED_INIT (init)
6629       && BRACE_ENCLOSED_INITIALIZER_P (new_init))
6630     CONSTRUCTOR_IS_DESIGNATED_INIT (new_init) = true;
6631
6632   return new_init;
6633 }
6634
6635 /* Verify array initializer.  Returns true if errors have been reported.  */
6636
6637 bool
6638 check_array_initializer (tree decl, tree type, tree init)
6639 {
6640   tree element_type = TREE_TYPE (type);
6641
6642   /* The array type itself need not be complete, because the
6643      initializer may tell us how many elements are in the array.
6644      But, the elements of the array must be complete.  */
6645   if (!COMPLETE_TYPE_P (complete_type (element_type)))
6646     {
6647       if (decl)
6648         error_at (DECL_SOURCE_LOCATION (decl),
6649                   "elements of array %q#D have incomplete type", decl);
6650       else
6651         error ("elements of array %q#T have incomplete type", type);
6652       return true;
6653     }
6654
6655   location_t loc = (decl ? location_of (decl) : input_location);
6656   if (!verify_type_context (loc, TCTX_ARRAY_ELEMENT, element_type))
6657     return true;
6658
6659   /* A compound literal can't have variable size.  */
6660   if (init && !decl
6661       && ((COMPLETE_TYPE_P (type) && !TREE_CONSTANT (TYPE_SIZE (type)))
6662           || !TREE_CONSTANT (TYPE_SIZE (element_type))))
6663     {
6664       error ("variable-sized compound literal");
6665       return true;
6666     }
6667   return false;
6668 }
6669
6670 /* Subroutine of check_initializer; args are passed down from that function.
6671    Set stmts_are_full_exprs_p to 1 across a call to build_aggr_init.  */
6672
6673 static tree
6674 build_aggr_init_full_exprs (tree decl, tree init, int flags)
6675      
6676 {
6677   gcc_assert (stmts_are_full_exprs_p ());
6678   return build_aggr_init (decl, init, flags, tf_warning_or_error);
6679 }
6680
6681 /* Verify INIT (the initializer for DECL), and record the
6682    initialization in DECL_INITIAL, if appropriate.  CLEANUP is as for
6683    grok_reference_init.
6684
6685    If the return value is non-NULL, it is an expression that must be
6686    evaluated dynamically to initialize DECL.  */
6687
6688 static tree
6689 check_initializer (tree decl, tree init, int flags, vec<tree, va_gc> **cleanups)
6690 {
6691   tree type;
6692   tree init_code = NULL;
6693   tree core_type;
6694
6695   /* Things that are going to be initialized need to have complete
6696      type.  */
6697   TREE_TYPE (decl) = type = complete_type (TREE_TYPE (decl));
6698
6699   if (DECL_HAS_VALUE_EXPR_P (decl))
6700     {
6701       /* A variable with DECL_HAS_VALUE_EXPR_P set is just a placeholder,
6702          it doesn't have storage to be initialized.  */
6703       gcc_assert (init == NULL_TREE);
6704       return NULL_TREE;
6705     }
6706
6707   if (type == error_mark_node)
6708     /* We will have already complained.  */
6709     return NULL_TREE;
6710
6711   if (TREE_CODE (type) == ARRAY_TYPE)
6712     {
6713       if (check_array_initializer (decl, type, init))
6714         return NULL_TREE;
6715     }
6716   else if (!COMPLETE_TYPE_P (type))
6717     {
6718       error_at (DECL_SOURCE_LOCATION (decl),
6719                 "%q#D has incomplete type", decl);
6720       TREE_TYPE (decl) = error_mark_node;
6721       return NULL_TREE;
6722     }
6723   else
6724     /* There is no way to make a variable-sized class type in GNU C++.  */
6725     gcc_assert (TREE_CONSTANT (TYPE_SIZE (type)));
6726
6727   if (init && BRACE_ENCLOSED_INITIALIZER_P (init))
6728     {
6729       int init_len = CONSTRUCTOR_NELTS (init);
6730       if (SCALAR_TYPE_P (type))
6731         {
6732           if (init_len == 0)
6733             {
6734               maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
6735               init = build_zero_init (type, NULL_TREE, false);
6736             }
6737           else if (init_len != 1 && TREE_CODE (type) != COMPLEX_TYPE)
6738             {
6739               error_at (cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (decl)),
6740                         "scalar object %qD requires one element in "
6741                         "initializer", decl);
6742               TREE_TYPE (decl) = error_mark_node;
6743               return NULL_TREE;
6744             }
6745         }
6746     }
6747
6748   if (TREE_CODE (decl) == CONST_DECL)
6749     {
6750       gcc_assert (!TYPE_REF_P (type));
6751
6752       DECL_INITIAL (decl) = init;
6753
6754       gcc_assert (init != NULL_TREE);
6755       init = NULL_TREE;
6756     }
6757   else if (!init && DECL_REALLY_EXTERN (decl))
6758     ;
6759   else if (init || type_build_ctor_call (type)
6760            || TYPE_REF_P (type))
6761     {
6762       if (TYPE_REF_P (type))
6763         {
6764           init = grok_reference_init (decl, type, init, flags);
6765           flags |= LOOKUP_ALREADY_DIGESTED;
6766         }
6767       else if (!init)
6768         check_for_uninitialized_const_var (decl, /*constexpr_context_p=*/false,
6769                                            tf_warning_or_error);
6770       /* Do not reshape constructors of vectors (they don't need to be
6771          reshaped.  */
6772       else if (BRACE_ENCLOSED_INITIALIZER_P (init))
6773         {
6774           if (is_std_init_list (type))
6775             {
6776               init = perform_implicit_conversion (type, init,
6777                                                   tf_warning_or_error);
6778               flags |= LOOKUP_ALREADY_DIGESTED;
6779             }
6780           else if (TYPE_NON_AGGREGATE_CLASS (type))
6781             {
6782               /* Don't reshape if the class has constructors.  */
6783               if (cxx_dialect == cxx98)
6784                 error_at (cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (decl)),
6785                           "in C++98 %qD must be initialized by "
6786                           "constructor, not by %<{...}%>",
6787                           decl);
6788             }
6789           else if (VECTOR_TYPE_P (type) && TYPE_VECTOR_OPAQUE (type))
6790             {
6791               error ("opaque vector types cannot be initialized");
6792               init = error_mark_node;
6793             }
6794           else
6795             {
6796               init = reshape_init (type, init, tf_warning_or_error);
6797               flags |= LOOKUP_NO_NARROWING;
6798             }
6799         }
6800       /* [dcl.init] "Otherwise, if the destination type is an array, the object
6801          is initialized as follows..."  So handle things like
6802
6803           int a[](1, 2, 3);
6804
6805          which is permitted in C++20 by P0960.  */
6806       else if (TREE_CODE (init) == TREE_LIST
6807                && TREE_TYPE (init) == NULL_TREE
6808                && TREE_CODE (type) == ARRAY_TYPE
6809                && !DECL_DECOMPOSITION_P (decl)
6810                && (cxx_dialect >= cxx20))
6811         init = do_aggregate_paren_init (init, type);
6812       else if (TREE_CODE (init) == TREE_LIST
6813                && TREE_TYPE (init) != unknown_type_node
6814                && !MAYBE_CLASS_TYPE_P (type))
6815         {
6816           gcc_assert (TREE_CODE (decl) != RESULT_DECL);
6817
6818           /* We get here with code like `int a (2);' */
6819           init = build_x_compound_expr_from_list (init, ELK_INIT,
6820                                                   tf_warning_or_error);
6821         }
6822
6823       /* If DECL has an array type without a specific bound, deduce the
6824          array size from the initializer.  */
6825       maybe_deduce_size_from_array_init (decl, init);
6826       type = TREE_TYPE (decl);
6827       if (type == error_mark_node)
6828         return NULL_TREE;
6829
6830       if (((type_build_ctor_call (type) || CLASS_TYPE_P (type))
6831            && !(flags & LOOKUP_ALREADY_DIGESTED)
6832            && !(init && BRACE_ENCLOSED_INITIALIZER_P (init)
6833                 && CP_AGGREGATE_TYPE_P (type)
6834                 && (CLASS_TYPE_P (type)
6835                     || !TYPE_NEEDS_CONSTRUCTING (type)
6836                     || type_has_extended_temps (type))))
6837           || (DECL_DECOMPOSITION_P (decl) && TREE_CODE (type) == ARRAY_TYPE))
6838         {
6839           init_code = build_aggr_init_full_exprs (decl, init, flags);
6840
6841           /* A constructor call is a non-trivial initializer even if
6842              it isn't explicitly written.  */
6843           if (TREE_SIDE_EFFECTS (init_code))
6844             DECL_NONTRIVIALLY_INITIALIZED_P (decl) = true;
6845
6846           /* If this is a constexpr initializer, expand_default_init will
6847              have returned an INIT_EXPR rather than a CALL_EXPR.  In that
6848              case, pull the initializer back out and pass it down into
6849              store_init_value.  */
6850           while (TREE_CODE (init_code) == EXPR_STMT
6851                  || TREE_CODE (init_code) == CONVERT_EXPR)
6852             init_code = TREE_OPERAND (init_code, 0);
6853           if (TREE_CODE (init_code) == INIT_EXPR)
6854             {
6855               /* In C++20, the call to build_aggr_init could have created
6856                  an INIT_EXPR with a CONSTRUCTOR as the RHS to handle
6857                  A(1, 2).  */
6858               init = TREE_OPERAND (init_code, 1);
6859               init_code = NULL_TREE;
6860               /* Don't call digest_init; it's unnecessary and will complain
6861                  about aggregate initialization of non-aggregate classes.  */
6862               flags |= LOOKUP_ALREADY_DIGESTED;
6863             }
6864           else if (DECL_DECLARED_CONSTEXPR_P (decl)
6865                    || DECL_DECLARED_CONSTINIT_P (decl))
6866             {
6867               /* Declared constexpr or constinit, but no suitable initializer;
6868                  massage init appropriately so we can pass it into
6869                  store_init_value for the error.  */
6870               if (CLASS_TYPE_P (type)
6871                   && (!init || TREE_CODE (init) == TREE_LIST))
6872                 {
6873                   init = build_functional_cast (input_location, type,
6874                                                 init, tf_none);
6875                   if (TREE_CODE (init) == TARGET_EXPR)
6876                     TARGET_EXPR_DIRECT_INIT_P (init) = true;
6877                 }
6878               init_code = NULL_TREE;
6879             }
6880           else
6881             init = NULL_TREE;
6882         }
6883
6884       if (init && TREE_CODE (init) != TREE_VEC)
6885         {
6886           /* In aggregate initialization of a variable, each element
6887              initialization is a full-expression because there is no
6888              enclosing expression.  */
6889           gcc_assert (stmts_are_full_exprs_p ());
6890
6891           init_code = store_init_value (decl, init, cleanups, flags);
6892
6893           if (DECL_INITIAL (decl)
6894               && TREE_CODE (DECL_INITIAL (decl)) == CONSTRUCTOR
6895               && !vec_safe_is_empty (CONSTRUCTOR_ELTS (DECL_INITIAL (decl))))
6896             {
6897               tree elt = CONSTRUCTOR_ELTS (DECL_INITIAL (decl))->last ().value;
6898               if (TREE_CODE (TREE_TYPE (elt)) == ARRAY_TYPE
6899                   && TYPE_SIZE (TREE_TYPE (elt)) == NULL_TREE)
6900                 cp_complete_array_type (&TREE_TYPE (elt), elt, false);
6901             }
6902
6903           if (pedantic && TREE_CODE (type) == ARRAY_TYPE
6904               && DECL_INITIAL (decl)
6905               && TREE_CODE (DECL_INITIAL (decl)) == STRING_CST
6906               && PAREN_STRING_LITERAL_P (DECL_INITIAL (decl)))
6907             warning_at (cp_expr_loc_or_loc (DECL_INITIAL (decl),
6908                                          DECL_SOURCE_LOCATION (decl)),
6909                         0, "array %qD initialized by parenthesized "
6910                         "string literal %qE",
6911                         decl, DECL_INITIAL (decl));
6912           init = NULL_TREE;
6913         }
6914     }
6915   else
6916     {
6917       if (CLASS_TYPE_P (core_type = strip_array_types (type))
6918           && (CLASSTYPE_READONLY_FIELDS_NEED_INIT (core_type)
6919               || CLASSTYPE_REF_FIELDS_NEED_INIT (core_type)))
6920         diagnose_uninitialized_cst_or_ref_member (core_type, /*using_new=*/false,
6921                                                   /*complain=*/true);
6922
6923       check_for_uninitialized_const_var (decl, /*constexpr_context_p=*/false,
6924                                          tf_warning_or_error);
6925     }
6926
6927   if (init && init != error_mark_node)
6928     init_code = build2 (INIT_EXPR, type, decl, init);
6929
6930   if (init_code)
6931     {
6932       /* We might have set these in cp_finish_decl.  */
6933       DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = false;
6934       TREE_CONSTANT (decl) = false;
6935     }
6936
6937   if (init_code
6938       && DECL_IN_AGGR_P (decl)
6939       && DECL_INITIALIZED_IN_CLASS_P (decl))
6940     {
6941       static int explained = 0;
6942
6943       if (cxx_dialect < cxx11)
6944         error ("initializer invalid for static member with constructor");
6945       else if (cxx_dialect < cxx17)
6946         error ("non-constant in-class initialization invalid for static "
6947                "member %qD", decl);
6948       else
6949         error ("non-constant in-class initialization invalid for non-inline "
6950                "static member %qD", decl);
6951       if (!explained)
6952         {
6953           inform (input_location,
6954                   "(an out of class initialization is required)");
6955           explained = 1;
6956         }
6957       return NULL_TREE;
6958     }
6959
6960   return init_code;
6961 }
6962
6963 /* If DECL is not a local variable, give it RTL.  */
6964
6965 static void
6966 make_rtl_for_nonlocal_decl (tree decl, tree init, const char* asmspec)
6967 {
6968   int toplev = toplevel_bindings_p ();
6969   int defer_p;
6970
6971   /* Set the DECL_ASSEMBLER_NAME for the object.  */
6972   if (asmspec)
6973     {
6974       /* The `register' keyword, when used together with an
6975          asm-specification, indicates that the variable should be
6976          placed in a particular register.  */
6977       if (VAR_P (decl) && DECL_REGISTER (decl))
6978         {
6979           set_user_assembler_name (decl, asmspec);
6980           DECL_HARD_REGISTER (decl) = 1;
6981         }
6982       else
6983         {
6984           if (TREE_CODE (decl) == FUNCTION_DECL
6985               && fndecl_built_in_p (decl, BUILT_IN_NORMAL))
6986             set_builtin_user_assembler_name (decl, asmspec);
6987           set_user_assembler_name (decl, asmspec);
6988         }
6989     }
6990
6991   /* Handle non-variables up front.  */
6992   if (!VAR_P (decl))
6993     {
6994       rest_of_decl_compilation (decl, toplev, at_eof);
6995       return;
6996     }
6997
6998   /* If we see a class member here, it should be a static data
6999      member.  */
7000   if (DECL_LANG_SPECIFIC (decl) && DECL_IN_AGGR_P (decl))
7001     {
7002       gcc_assert (TREE_STATIC (decl));
7003       /* An in-class declaration of a static data member should be
7004          external; it is only a declaration, and not a definition.  */
7005       if (init == NULL_TREE)
7006         gcc_assert (DECL_EXTERNAL (decl)
7007                     || !TREE_PUBLIC (decl));
7008     }
7009
7010   /* We don't create any RTL for local variables.  */
7011   if (DECL_FUNCTION_SCOPE_P (decl) && !TREE_STATIC (decl))
7012     return;
7013
7014   /* We defer emission of local statics until the corresponding
7015      DECL_EXPR is expanded.  But with constexpr its function might never
7016      be expanded, so go ahead and tell cgraph about the variable now.  */
7017   defer_p = ((DECL_FUNCTION_SCOPE_P (decl)
7018               && !var_in_maybe_constexpr_fn (decl))
7019              || DECL_VIRTUAL_P (decl));
7020
7021   /* Defer template instantiations.  */
7022   if (DECL_LANG_SPECIFIC (decl)
7023       && DECL_IMPLICIT_INSTANTIATION (decl))
7024     defer_p = 1;
7025
7026   /* If we're not deferring, go ahead and assemble the variable.  */
7027   if (!defer_p)
7028     rest_of_decl_compilation (decl, toplev, at_eof);
7029 }
7030
7031 /* walk_tree helper for wrap_temporary_cleanups, below.  */
7032
7033 static tree
7034 wrap_cleanups_r (tree *stmt_p, int *walk_subtrees, void *data)
7035 {
7036   /* Stop at types or full-expression boundaries.  */
7037   if (TYPE_P (*stmt_p)
7038       || TREE_CODE (*stmt_p) == CLEANUP_POINT_EXPR)
7039     {
7040       *walk_subtrees = 0;
7041       return NULL_TREE;
7042     }
7043
7044   if (TREE_CODE (*stmt_p) == TARGET_EXPR)
7045     {
7046       tree guard = (tree)data;
7047       tree tcleanup = TARGET_EXPR_CLEANUP (*stmt_p);
7048
7049       tcleanup = build2 (TRY_CATCH_EXPR, void_type_node, tcleanup, guard);
7050       /* Tell honor_protect_cleanup_actions to handle this as a separate
7051          cleanup.  */
7052       TRY_CATCH_IS_CLEANUP (tcleanup) = 1;
7053  
7054       TARGET_EXPR_CLEANUP (*stmt_p) = tcleanup;
7055     }
7056
7057   return NULL_TREE;
7058 }
7059
7060 /* We're initializing a local variable which has a cleanup GUARD.  If there
7061    are any temporaries used in the initializer INIT of this variable, we
7062    need to wrap their cleanups with TRY_CATCH_EXPR (, GUARD) so that the
7063    variable will be cleaned up properly if one of them throws.
7064
7065    Unfortunately, there's no way to express this properly in terms of
7066    nesting, as the regions for the temporaries overlap the region for the
7067    variable itself; if there are two temporaries, the variable needs to be
7068    the first thing destroyed if either of them throws.  However, we only
7069    want to run the variable's cleanup if it actually got constructed.  So
7070    we need to guard the temporary cleanups with the variable's cleanup if
7071    they are run on the normal path, but not if they are run on the
7072    exceptional path.  We implement this by telling
7073    honor_protect_cleanup_actions to strip the variable cleanup from the
7074    exceptional path.  */
7075
7076 static void
7077 wrap_temporary_cleanups (tree init, tree guard)
7078 {
7079   cp_walk_tree_without_duplicates (&init, wrap_cleanups_r, (void *)guard);
7080 }
7081
7082 /* Generate code to initialize DECL (a local variable).  */
7083
7084 static void
7085 initialize_local_var (tree decl, tree init)
7086 {
7087   tree type = TREE_TYPE (decl);
7088   tree cleanup;
7089   int already_used;
7090
7091   gcc_assert (VAR_P (decl)
7092               || TREE_CODE (decl) == RESULT_DECL);
7093   gcc_assert (!TREE_STATIC (decl));
7094
7095   if (DECL_SIZE (decl) == NULL_TREE)
7096     {
7097       /* If we used it already as memory, it must stay in memory.  */
7098       DECL_INITIAL (decl) = NULL_TREE;
7099       TREE_ADDRESSABLE (decl) = TREE_USED (decl);
7100       return;
7101     }
7102
7103   if (type == error_mark_node)
7104     return;
7105
7106   /* Compute and store the initial value.  */
7107   already_used = TREE_USED (decl) || TREE_USED (type);
7108   if (TREE_USED (type))
7109     DECL_READ_P (decl) = 1;
7110
7111   /* Generate a cleanup, if necessary.  */
7112   cleanup = cxx_maybe_build_cleanup (decl, tf_warning_or_error);
7113
7114   /* Perform the initialization.  */
7115   if (init)
7116     {
7117       tree rinit = (TREE_CODE (init) == INIT_EXPR
7118                     ? TREE_OPERAND (init, 1) : NULL_TREE);
7119       if (rinit && !TREE_SIDE_EFFECTS (rinit))
7120         {
7121           /* Stick simple initializers in DECL_INITIAL so that
7122              -Wno-init-self works (c++/34772).  */
7123           gcc_assert (TREE_OPERAND (init, 0) == decl);
7124           DECL_INITIAL (decl) = rinit;
7125
7126           if (warn_init_self && TYPE_REF_P (type))
7127             {
7128               STRIP_NOPS (rinit);
7129               if (rinit == decl)
7130                 warning_at (DECL_SOURCE_LOCATION (decl),
7131                             OPT_Winit_self,
7132                             "reference %qD is initialized with itself", decl);
7133             }
7134         }
7135       else
7136         {
7137           int saved_stmts_are_full_exprs_p;
7138
7139           /* If we're only initializing a single object, guard the
7140              destructors of any temporaries used in its initializer with
7141              its destructor.  This isn't right for arrays because each
7142              element initialization is a full-expression.  */
7143           if (cleanup && TREE_CODE (type) != ARRAY_TYPE)
7144             wrap_temporary_cleanups (init, cleanup);
7145
7146           gcc_assert (building_stmt_list_p ());
7147           saved_stmts_are_full_exprs_p = stmts_are_full_exprs_p ();
7148           current_stmt_tree ()->stmts_are_full_exprs_p = 1;
7149           finish_expr_stmt (init);
7150           current_stmt_tree ()->stmts_are_full_exprs_p =
7151             saved_stmts_are_full_exprs_p;
7152         }
7153     }
7154
7155   /* Set this to 0 so we can tell whether an aggregate which was
7156      initialized was ever used.  Don't do this if it has a
7157      destructor, so we don't complain about the 'resource
7158      allocation is initialization' idiom.  Now set
7159      attribute((unused)) on types so decls of that type will be
7160      marked used. (see TREE_USED, above.)  */
7161   if (TYPE_NEEDS_CONSTRUCTING (type)
7162       && ! already_used
7163       && TYPE_HAS_TRIVIAL_DESTRUCTOR (type)
7164       && DECL_NAME (decl))
7165     TREE_USED (decl) = 0;
7166   else if (already_used)
7167     TREE_USED (decl) = 1;
7168
7169   if (cleanup)
7170     finish_decl_cleanup (decl, cleanup);
7171 }
7172
7173 /* DECL is a VAR_DECL for a compiler-generated variable with static
7174    storage duration (like a virtual table) whose initializer is a
7175    compile-time constant.  Initialize the variable and provide it to the
7176    back end.  */
7177
7178 void
7179 initialize_artificial_var (tree decl, vec<constructor_elt, va_gc> *v)
7180 {
7181   tree init;
7182   gcc_assert (DECL_ARTIFICIAL (decl));
7183   init = build_constructor (TREE_TYPE (decl), v);
7184   gcc_assert (TREE_CODE (init) == CONSTRUCTOR);
7185   DECL_INITIAL (decl) = init;
7186   DECL_INITIALIZED_P (decl) = 1;
7187   /* Mark the decl as constexpr so that we can access its content
7188      at compile time.  */
7189   DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = true;
7190   DECL_DECLARED_CONSTEXPR_P (decl) = true;
7191   determine_visibility (decl);
7192   layout_var_decl (decl);
7193   maybe_commonize_var (decl);
7194   make_rtl_for_nonlocal_decl (decl, init, /*asmspec=*/NULL);
7195 }
7196
7197 /* INIT is the initializer for a variable, as represented by the
7198    parser.  Returns true iff INIT is value-dependent.  */
7199
7200 static bool
7201 value_dependent_init_p (tree init)
7202 {
7203   if (TREE_CODE (init) == TREE_LIST)
7204     /* A parenthesized initializer, e.g.: int i (3, 2); ? */
7205     return any_value_dependent_elements_p (init);
7206   else if (TREE_CODE (init) == CONSTRUCTOR)
7207   /* A brace-enclosed initializer, e.g.: int i = { 3 }; ? */
7208     {
7209       if (dependent_type_p (TREE_TYPE (init)))
7210         return true;
7211
7212       vec<constructor_elt, va_gc> *elts;
7213       size_t nelts;
7214       size_t i;
7215
7216       elts = CONSTRUCTOR_ELTS (init);
7217       nelts = vec_safe_length (elts);
7218       for (i = 0; i < nelts; ++i)
7219         if (value_dependent_init_p ((*elts)[i].value))
7220           return true;
7221     }
7222   else
7223     /* It must be a simple expression, e.g., int i = 3;  */
7224     return value_dependent_expression_p (init);
7225   
7226   return false;
7227 }
7228
7229 // Returns true if a DECL is VAR_DECL with the concept specifier.
7230 static inline bool
7231 is_concept_var (tree decl)
7232 {
7233   return (VAR_P (decl)
7234           // Not all variables have DECL_LANG_SPECIFIC.
7235           && DECL_LANG_SPECIFIC (decl)
7236           && DECL_DECLARED_CONCEPT_P (decl));
7237 }
7238
7239 /* A helper function to be called via walk_tree.  If any label exists
7240    under *TP, it is (going to be) forced.  Set has_forced_label_in_static.  */
7241
7242 static tree
7243 notice_forced_label_r (tree *tp, int *walk_subtrees, void *)
7244 {
7245   if (TYPE_P (*tp))
7246     *walk_subtrees = 0;
7247   if (TREE_CODE (*tp) == LABEL_DECL)
7248     cfun->has_forced_label_in_static = 1;
7249   return NULL_TREE;
7250 }
7251
7252 /* Return true if DECL has either a trivial destructor, or for C++20
7253    is constexpr and has a constexpr destructor.  */
7254
7255 static bool
7256 decl_maybe_constant_destruction (tree decl, tree type)
7257 {
7258   return (TYPE_HAS_TRIVIAL_DESTRUCTOR (type)
7259           || (cxx_dialect >= cxx20
7260               && VAR_P (decl)
7261               && DECL_DECLARED_CONSTEXPR_P (decl)
7262               && type_has_constexpr_destructor (strip_array_types (type))));
7263 }
7264
7265 static tree declare_simd_adjust_this (tree *, int *, void *);
7266
7267 /* Helper function of omp_declare_variant_finalize.  Finalize one
7268    "omp declare variant base" attribute.  Return true if it should be
7269    removed.  */
7270
7271 static bool
7272 omp_declare_variant_finalize_one (tree decl, tree attr)
7273 {
7274   if (TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
7275     {
7276       walk_tree (&TREE_VALUE (TREE_VALUE (attr)), declare_simd_adjust_this,
7277                  DECL_ARGUMENTS (decl), NULL);
7278       walk_tree (&TREE_PURPOSE (TREE_VALUE (attr)), declare_simd_adjust_this,
7279                  DECL_ARGUMENTS (decl), NULL);
7280     }
7281
7282   tree ctx = TREE_VALUE (TREE_VALUE (attr));
7283   tree simd = omp_get_context_selector (ctx, "construct", "simd");
7284   if (simd)
7285     {
7286       TREE_VALUE (simd)
7287         = c_omp_declare_simd_clauses_to_numbers (DECL_ARGUMENTS (decl),
7288                                                  TREE_VALUE (simd));
7289       /* FIXME, adjusting simd args unimplemented.  */
7290       return true;
7291     }
7292
7293   tree chain = TREE_CHAIN (TREE_VALUE (attr));
7294   location_t varid_loc
7295     = cp_expr_loc_or_input_loc (TREE_PURPOSE (TREE_CHAIN (chain)));
7296   location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
7297   cp_id_kind idk = (cp_id_kind) tree_to_uhwi (TREE_VALUE (chain));
7298   tree variant = TREE_PURPOSE (TREE_VALUE (attr));
7299
7300   location_t save_loc = input_location;
7301   input_location = varid_loc;
7302
7303   releasing_vec args;
7304   tree parm = DECL_ARGUMENTS (decl);
7305   if (TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
7306     parm = DECL_CHAIN (parm);
7307   for (; parm; parm = DECL_CHAIN (parm))
7308     if (type_dependent_expression_p (parm))
7309       vec_safe_push (args, build_constructor (TREE_TYPE (parm), NULL));
7310     else if (MAYBE_CLASS_TYPE_P (TREE_TYPE (parm)))
7311       vec_safe_push (args, build_local_temp (TREE_TYPE (parm)));
7312     else
7313       vec_safe_push (args, build_zero_cst (TREE_TYPE (parm)));
7314
7315   bool koenig_p = false;
7316   if (idk == CP_ID_KIND_UNQUALIFIED || idk == CP_ID_KIND_TEMPLATE_ID)
7317     {
7318       if (identifier_p (variant)
7319           /* In C++20, we may need to perform ADL for a template
7320              name.  */
7321           || (TREE_CODE (variant) == TEMPLATE_ID_EXPR
7322               && identifier_p (TREE_OPERAND (variant, 0))))
7323         {
7324           if (!args->is_empty ())
7325             {
7326               koenig_p = true;
7327               if (!any_type_dependent_arguments_p (args))
7328                 variant = perform_koenig_lookup (variant, args,
7329                                                  tf_warning_or_error);
7330             }
7331           else
7332             variant = unqualified_fn_lookup_error (variant);
7333         }
7334       else if (!args->is_empty () && is_overloaded_fn (variant))
7335         {
7336           tree fn = get_first_fn (variant);
7337           fn = STRIP_TEMPLATE (fn);
7338           if (!((TREE_CODE (fn) == USING_DECL && DECL_DEPENDENT_P (fn))
7339                  || DECL_FUNCTION_MEMBER_P (fn)
7340                  || DECL_LOCAL_DECL_P (fn)))
7341             {
7342               koenig_p = true;
7343               if (!any_type_dependent_arguments_p (args))
7344                 variant = perform_koenig_lookup (variant, args,
7345                                                  tf_warning_or_error);
7346             }
7347         }
7348     }
7349
7350   if (idk == CP_ID_KIND_QUALIFIED)
7351     variant = finish_call_expr (variant, &args, /*disallow_virtual=*/true,
7352                                 koenig_p, tf_warning_or_error);
7353   else
7354     variant = finish_call_expr (variant, &args, /*disallow_virtual=*/false,
7355                                 koenig_p, tf_warning_or_error);
7356   if (variant == error_mark_node && !processing_template_decl)
7357     return true;
7358
7359   variant = cp_get_callee_fndecl_nofold (variant);
7360   input_location = save_loc;
7361
7362   if (variant)
7363     {
7364       const char *varname = IDENTIFIER_POINTER (DECL_NAME (variant));
7365       if (!comptypes (TREE_TYPE (decl), TREE_TYPE (variant), 0))
7366         {
7367           error_at (varid_loc, "variant %qD and base %qD have incompatible "
7368                                "types", variant, decl);
7369           return true;
7370         }
7371       if (fndecl_built_in_p (variant)
7372           && (strncmp (varname, "__builtin_", strlen ("__builtin_")) == 0
7373               || strncmp (varname, "__sync_", strlen ("__sync_")) == 0
7374               || strncmp (varname, "__atomic_", strlen ("__atomic_")) == 0))
7375         {
7376           error_at (varid_loc, "variant %qD is a built-in", variant);
7377           return true;
7378         }
7379       else
7380         {
7381           tree construct = omp_get_context_selector (ctx, "construct", NULL);
7382           c_omp_mark_declare_variant (match_loc, variant, construct);
7383           if (!omp_context_selector_matches (ctx))
7384             return true;
7385           TREE_PURPOSE (TREE_VALUE (attr)) = variant;
7386         }
7387     }
7388   else if (!processing_template_decl)
7389     {
7390       error_at (varid_loc, "could not find variant declaration");
7391       return true;
7392     }
7393
7394   return false;
7395 }
7396
7397 /* Helper function, finish up "omp declare variant base" attribute
7398    now that there is a DECL.  ATTR is the first "omp declare variant base"
7399    attribute.  */
7400
7401 void
7402 omp_declare_variant_finalize (tree decl, tree attr)
7403 {
7404   size_t attr_len = strlen ("omp declare variant base");
7405   tree *list = &DECL_ATTRIBUTES (decl);
7406   bool remove_all = false;
7407   location_t match_loc = DECL_SOURCE_LOCATION (decl);
7408   if (TREE_CHAIN (TREE_VALUE (attr))
7409       && TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr)))
7410       && EXPR_HAS_LOCATION (TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr)))))
7411     match_loc = EXPR_LOCATION (TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr))));
7412   if (DECL_CONSTRUCTOR_P (decl))
7413     {
7414       error_at (match_loc, "%<declare variant%> on constructor %qD", decl);
7415       remove_all = true;
7416     }
7417   else if (DECL_DESTRUCTOR_P (decl))
7418     {
7419       error_at (match_loc, "%<declare variant%> on destructor %qD", decl);
7420       remove_all = true;
7421     }
7422   else if (DECL_DEFAULTED_FN (decl))
7423     {
7424       error_at (match_loc, "%<declare variant%> on defaulted %qD", decl);
7425       remove_all = true;
7426     }
7427   else if (DECL_DELETED_FN (decl))
7428     {
7429       error_at (match_loc, "%<declare variant%> on deleted %qD", decl);
7430       remove_all = true;
7431     }
7432   else if (DECL_VIRTUAL_P (decl))
7433     {
7434       error_at (match_loc, "%<declare variant%> on virtual %qD", decl);
7435       remove_all = true;
7436     }
7437   /* This loop is like private_lookup_attribute, except that it works
7438      with tree * rather than tree, as we might want to remove the
7439      attributes that are diagnosed as errorneous.  */
7440   while (*list)
7441     {
7442       tree attr = get_attribute_name (*list);
7443       size_t ident_len = IDENTIFIER_LENGTH (attr);
7444       if (cmp_attribs ("omp declare variant base", attr_len,
7445                        IDENTIFIER_POINTER (attr), ident_len))
7446         {
7447           if (remove_all || omp_declare_variant_finalize_one (decl, *list))
7448             {
7449               *list = TREE_CHAIN (*list);
7450               continue;
7451             }
7452         }
7453       list = &TREE_CHAIN (*list);
7454     }
7455 }
7456
7457 /* Finish processing of a declaration;
7458    install its line number and initial value.
7459    If the length of an array type is not known before,
7460    it must be determined now, from the initial value, or it is an error.
7461
7462    INIT is the initializer (if any) for DECL.  If INIT_CONST_EXPR_P is
7463    true, then INIT is an integral constant expression.
7464
7465    FLAGS is LOOKUP_ONLYCONVERTING if the = init syntax was used, else 0
7466    if the (init) syntax was used.  */
7467
7468 void
7469 cp_finish_decl (tree decl, tree init, bool init_const_expr_p,
7470                 tree asmspec_tree, int flags)
7471 {
7472   tree type;
7473   vec<tree, va_gc> *cleanups = NULL;
7474   const char *asmspec = NULL;
7475   int was_readonly = 0;
7476   bool var_definition_p = false;
7477   tree auto_node;
7478
7479   if (decl == error_mark_node)
7480     return;
7481   else if (! decl)
7482     {
7483       if (init)
7484         error ("assignment (not initialization) in declaration");
7485       return;
7486     }
7487
7488   gcc_assert (TREE_CODE (decl) != RESULT_DECL);
7489   /* Parameters are handled by store_parm_decls, not cp_finish_decl.  */
7490   gcc_assert (TREE_CODE (decl) != PARM_DECL);
7491
7492   type = TREE_TYPE (decl);
7493   if (type == error_mark_node)
7494     return;
7495
7496   /* Warn about register storage specifiers except when in GNU global
7497      or local register variable extension.  */
7498   if (VAR_P (decl) && DECL_REGISTER (decl) && asmspec_tree == NULL_TREE)
7499     {
7500       if (cxx_dialect >= cxx17)
7501         pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
7502                  "ISO C++17 does not allow %<register%> storage "
7503                  "class specifier");
7504       else
7505         warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
7506                     "%<register%> storage class specifier used");
7507     }
7508
7509   /* If a name was specified, get the string.  */
7510   if (at_namespace_scope_p ())
7511     asmspec_tree = maybe_apply_renaming_pragma (decl, asmspec_tree);
7512   if (asmspec_tree && asmspec_tree != error_mark_node)
7513     asmspec = TREE_STRING_POINTER (asmspec_tree);
7514
7515   if (current_class_type
7516       && CP_DECL_CONTEXT (decl) == current_class_type
7517       && TYPE_BEING_DEFINED (current_class_type)
7518       && !CLASSTYPE_TEMPLATE_INSTANTIATION (current_class_type)
7519       && (DECL_INITIAL (decl) || init))
7520     DECL_INITIALIZED_IN_CLASS_P (decl) = 1;
7521
7522   if (TREE_CODE (decl) != FUNCTION_DECL
7523       && (auto_node = type_uses_auto (type)))
7524     {
7525       tree d_init;
7526       if (init == NULL_TREE)
7527         {
7528           if (DECL_LANG_SPECIFIC (decl)
7529               && DECL_TEMPLATE_INSTANTIATION (decl)
7530               && !DECL_TEMPLATE_INSTANTIATED (decl))
7531             {
7532               /* init is null because we're deferring instantiating the
7533                  initializer until we need it.  Well, we need it now.  */
7534               instantiate_decl (decl, /*defer_ok*/true, /*expl*/false);
7535               return;
7536             }
7537
7538           gcc_assert (CLASS_PLACEHOLDER_TEMPLATE (auto_node));
7539         }
7540       d_init = init;
7541       if (d_init)
7542         {
7543           if (TREE_CODE (d_init) == TREE_LIST
7544               && !CLASS_PLACEHOLDER_TEMPLATE (auto_node))
7545             d_init = build_x_compound_expr_from_list (d_init, ELK_INIT,
7546                                                       tf_warning_or_error);
7547           d_init = resolve_nondeduced_context (d_init, tf_warning_or_error);
7548         }
7549       enum auto_deduction_context adc = adc_variable_type;
7550       if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
7551         adc = adc_decomp_type;
7552       type = TREE_TYPE (decl) = do_auto_deduction (type, d_init, auto_node,
7553                                                    tf_warning_or_error, adc,
7554                                                    NULL_TREE, flags);
7555       if (type == error_mark_node)
7556         return;
7557       if (TREE_CODE (type) == FUNCTION_TYPE)
7558         {
7559           error ("initializer for %<decltype(auto) %D%> has function type; "
7560                  "did you forget the %<()%>?", decl);
7561           TREE_TYPE (decl) = error_mark_node;
7562           return;
7563         }
7564       cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
7565     }
7566
7567   if (ensure_literal_type_for_constexpr_object (decl) == error_mark_node)
7568     {
7569       DECL_DECLARED_CONSTEXPR_P (decl) = 0;
7570       if (VAR_P (decl) && DECL_CLASS_SCOPE_P (decl))
7571         {
7572           init = NULL_TREE;
7573           DECL_EXTERNAL (decl) = 1;
7574         }
7575     }
7576
7577   if (VAR_P (decl)
7578       && DECL_CLASS_SCOPE_P (decl)
7579       && verify_type_context (DECL_SOURCE_LOCATION (decl),
7580                               TCTX_STATIC_STORAGE, type)
7581       && DECL_INITIALIZED_IN_CLASS_P (decl))
7582     check_static_variable_definition (decl, type);
7583
7584   if (init && TREE_CODE (decl) == FUNCTION_DECL)
7585     {
7586       tree clone;
7587       if (init == ridpointers[(int)RID_DELETE])
7588         {
7589           /* FIXME check this is 1st decl.  */
7590           DECL_DELETED_FN (decl) = 1;
7591           DECL_DECLARED_INLINE_P (decl) = 1;
7592           DECL_INITIAL (decl) = error_mark_node;
7593           FOR_EACH_CLONE (clone, decl)
7594             {
7595               DECL_DELETED_FN (clone) = 1;
7596               DECL_DECLARED_INLINE_P (clone) = 1;
7597               DECL_INITIAL (clone) = error_mark_node;
7598             }
7599           init = NULL_TREE;
7600         }
7601       else if (init == ridpointers[(int)RID_DEFAULT])
7602         {
7603           if (defaultable_fn_check (decl))
7604             DECL_DEFAULTED_FN (decl) = 1;
7605           else
7606             DECL_INITIAL (decl) = NULL_TREE;
7607         }
7608     }
7609
7610   if (init && VAR_P (decl))
7611     {
7612       DECL_NONTRIVIALLY_INITIALIZED_P (decl) = 1;
7613       /* If DECL is a reference, then we want to know whether init is a
7614          reference constant; init_const_expr_p as passed tells us whether
7615          it's an rvalue constant.  */
7616       if (TYPE_REF_P (type))
7617         init_const_expr_p = potential_constant_expression (init);
7618       if (init_const_expr_p)
7619         {
7620           /* Set these flags now for templates.  We'll update the flags in
7621              store_init_value for instantiations.  */
7622           DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = 1;
7623           if (decl_maybe_constant_var_p (decl)
7624               /* FIXME setting TREE_CONSTANT on refs breaks the back end.  */
7625               && !TYPE_REF_P (type))
7626             TREE_CONSTANT (decl) = 1;
7627         }
7628     }
7629
7630   if (flag_openmp
7631       && TREE_CODE (decl) == FUNCTION_DECL
7632       /* #pragma omp declare variant on methods handled in finish_struct
7633          instead.  */
7634       && (!DECL_NONSTATIC_MEMBER_FUNCTION_P (decl)
7635           || COMPLETE_TYPE_P (DECL_CONTEXT (decl))))
7636     if (tree attr = lookup_attribute ("omp declare variant base",
7637                                       DECL_ATTRIBUTES (decl)))
7638       omp_declare_variant_finalize (decl, attr);
7639
7640   if (processing_template_decl)
7641     {
7642       bool type_dependent_p;
7643
7644       /* Add this declaration to the statement-tree.  */
7645       if (at_function_scope_p ())
7646         add_decl_expr (decl);
7647
7648       type_dependent_p = dependent_type_p (type);
7649
7650       if (check_for_bare_parameter_packs (init))
7651         {
7652           init = NULL_TREE;
7653           DECL_INITIAL (decl) = NULL_TREE;
7654         }
7655
7656       /* Generally, initializers in templates are expanded when the
7657          template is instantiated.  But, if DECL is a variable constant
7658          then it can be used in future constant expressions, so its value
7659          must be available. */
7660
7661       bool dep_init = false;
7662
7663       if (!VAR_P (decl) || type_dependent_p)
7664         /* We can't do anything if the decl has dependent type.  */;
7665       else if (!init && is_concept_var (decl))
7666         {
7667           error ("variable concept has no initializer");
7668           init = boolean_true_node;
7669         }
7670       else if (init
7671                && (init_const_expr_p || DECL_DECLARED_CONSTEXPR_P (decl))
7672                && !TYPE_REF_P (type)
7673                && decl_maybe_constant_var_p (decl)
7674                && !(dep_init = value_dependent_init_p (init)))
7675         {
7676           /* This variable seems to be a non-dependent constant, so process
7677              its initializer.  If check_initializer returns non-null the
7678              initialization wasn't constant after all.  */
7679           tree init_code;
7680           cleanups = make_tree_vector ();
7681           init_code = check_initializer (decl, init, flags, &cleanups);
7682           if (init_code == NULL_TREE)
7683             init = NULL_TREE;
7684           release_tree_vector (cleanups);
7685         }
7686       else
7687         {
7688           gcc_assert (!DECL_PRETTY_FUNCTION_P (decl));
7689           /* Deduce array size even if the initializer is dependent.  */
7690           maybe_deduce_size_from_array_init (decl, init);
7691           /* And complain about multiple initializers.  */
7692           if (init && TREE_CODE (init) == TREE_LIST && TREE_CHAIN (init)
7693               && !MAYBE_CLASS_TYPE_P (type))
7694             init = build_x_compound_expr_from_list (init, ELK_INIT,
7695                                                     tf_warning_or_error);
7696         }
7697
7698       if (init)
7699         DECL_INITIAL (decl) = init;
7700
7701       if (dep_init)
7702         {
7703           retrofit_lang_decl (decl);
7704           SET_DECL_DEPENDENT_INIT_P (decl, true);
7705         }
7706       return;
7707     }
7708
7709   /* Just store non-static data member initializers for later.  */
7710   if (init && TREE_CODE (decl) == FIELD_DECL)
7711     DECL_INITIAL (decl) = init;
7712
7713   /* Take care of TYPE_DECLs up front.  */
7714   if (TREE_CODE (decl) == TYPE_DECL)
7715     {
7716       if (type != error_mark_node
7717           && MAYBE_CLASS_TYPE_P (type) && DECL_NAME (decl))
7718         {
7719           if (TREE_TYPE (DECL_NAME (decl)) && TREE_TYPE (decl) != type)
7720             warning (0, "shadowing previous type declaration of %q#D", decl);
7721           set_identifier_type_value (DECL_NAME (decl), decl);
7722         }
7723
7724       /* If we have installed this as the canonical typedef for this
7725          type, and that type has not been defined yet, delay emitting
7726          the debug information for it, as we will emit it later.  */
7727       if (TYPE_MAIN_DECL (TREE_TYPE (decl)) == decl
7728           && !COMPLETE_TYPE_P (TREE_TYPE (decl)))
7729         TYPE_DECL_SUPPRESS_DEBUG (decl) = 1;
7730
7731       rest_of_decl_compilation (decl, DECL_FILE_SCOPE_P (decl),
7732                                 at_eof);
7733       return;
7734     }
7735
7736   /* A reference will be modified here, as it is initialized.  */
7737   if (! DECL_EXTERNAL (decl)
7738       && TREE_READONLY (decl)
7739       && TYPE_REF_P (type))
7740     {
7741       was_readonly = 1;
7742       TREE_READONLY (decl) = 0;
7743     }
7744
7745   /* This needs to happen before extend_ref_init_temps.  */
7746   if (VAR_OR_FUNCTION_DECL_P (decl))
7747     {
7748       if (VAR_P (decl))
7749         maybe_commonize_var (decl);
7750       determine_visibility (decl);
7751     }
7752
7753   if (VAR_P (decl))
7754     {
7755       duration_kind dk = decl_storage_duration (decl);
7756       /* [dcl.constinit]/1 "The constinit specifier shall be applied
7757          only to a declaration of a variable with static or thread storage
7758          duration."  */
7759       if (DECL_DECLARED_CONSTINIT_P (decl)
7760           && !(dk == dk_thread || dk == dk_static))
7761         {
7762           error_at (DECL_SOURCE_LOCATION (decl),
7763                     "%<constinit%> can only be applied to a variable with "
7764                     "static or thread storage duration");
7765           return;
7766         }
7767
7768       /* If this is a local variable that will need a mangled name,
7769          register it now.  We must do this before processing the
7770          initializer for the variable, since the initialization might
7771          require a guard variable, and since the mangled name of the
7772          guard variable will depend on the mangled name of this
7773          variable.  */
7774       if (DECL_FUNCTION_SCOPE_P (decl)
7775           && TREE_STATIC (decl)
7776           && !DECL_ARTIFICIAL (decl))
7777         {
7778           /* The variable holding an anonymous union will have had its
7779              discriminator set in finish_anon_union, after which it's
7780              NAME will have been cleared.  */
7781           if (DECL_NAME (decl))
7782             determine_local_discriminator (decl);
7783           /* Normally has_forced_label_in_static is set during GIMPLE
7784              lowering, but [cd]tors are never actually compiled directly.
7785              We need to set this early so we can deal with the label
7786              address extension.  */
7787           if ((DECL_CONSTRUCTOR_P (current_function_decl)
7788                || DECL_DESTRUCTOR_P (current_function_decl))
7789               && init)
7790             {
7791               walk_tree (&init, notice_forced_label_r, NULL, NULL);
7792               add_local_decl (cfun, decl);
7793             }
7794           /* And make sure it's in the symbol table for
7795              c_parse_final_cleanups to find.  */
7796           varpool_node::get_create (decl);
7797         }
7798
7799       /* Convert the initializer to the type of DECL, if we have not
7800          already initialized DECL.  */
7801       if (!DECL_INITIALIZED_P (decl)
7802           /* If !DECL_EXTERNAL then DECL is being defined.  In the
7803              case of a static data member initialized inside the
7804              class-specifier, there can be an initializer even if DECL
7805              is *not* defined.  */
7806           && (!DECL_EXTERNAL (decl) || init))
7807         {
7808           cleanups = make_tree_vector ();
7809           init = check_initializer (decl, init, flags, &cleanups);
7810
7811           /* Handle:
7812
7813              [dcl.init]
7814
7815              The memory occupied by any object of static storage
7816              duration is zero-initialized at program startup before
7817              any other initialization takes place.
7818
7819              We cannot create an appropriate initializer until after
7820              the type of DECL is finalized.  If DECL_INITIAL is set,
7821              then the DECL is statically initialized, and any
7822              necessary zero-initialization has already been performed.  */
7823           if (TREE_STATIC (decl) && !DECL_INITIAL (decl))
7824             DECL_INITIAL (decl) = build_zero_init (TREE_TYPE (decl),
7825                                                    /*nelts=*/NULL_TREE,
7826                                                    /*static_storage_p=*/true);
7827           /* Remember that the initialization for this variable has
7828              taken place.  */
7829           DECL_INITIALIZED_P (decl) = 1;
7830           /* This declaration is the definition of this variable,
7831              unless we are initializing a static data member within
7832              the class specifier.  */
7833           if (!DECL_EXTERNAL (decl))
7834             var_definition_p = true;
7835         }
7836       /* If the variable has an array type, lay out the type, even if
7837          there is no initializer.  It is valid to index through the
7838          array, and we must get TYPE_ALIGN set correctly on the array
7839          type.  */
7840       else if (TREE_CODE (type) == ARRAY_TYPE)
7841         layout_type (type);
7842
7843       if (TREE_STATIC (decl)
7844           && !at_function_scope_p ()
7845           && current_function_decl == NULL)
7846         /* So decl is a global variable or a static member of a
7847            non local class. Record the types it uses
7848            so that we can decide later to emit debug info for them.  */
7849         record_types_used_by_current_var_decl (decl);
7850     }
7851
7852   /* Add this declaration to the statement-tree.  This needs to happen
7853      after the call to check_initializer so that the DECL_EXPR for a
7854      reference temp is added before the DECL_EXPR for the reference itself.  */
7855   if (DECL_FUNCTION_SCOPE_P (decl))
7856     {
7857       /* If we're building a variable sized type, and we might be
7858          reachable other than via the top of the current binding
7859          level, then create a new BIND_EXPR so that we deallocate
7860          the object at the right time.  */
7861       if (VAR_P (decl)
7862           && DECL_SIZE (decl)
7863           && !TREE_CONSTANT (DECL_SIZE (decl))
7864           && STATEMENT_LIST_HAS_LABEL (cur_stmt_list))
7865         {
7866           tree bind;
7867           bind = build3 (BIND_EXPR, void_type_node, NULL, NULL, NULL);
7868           TREE_SIDE_EFFECTS (bind) = 1;
7869           add_stmt (bind);
7870           BIND_EXPR_BODY (bind) = push_stmt_list ();
7871         }
7872       add_decl_expr (decl);
7873     }
7874
7875   /* Let the middle end know about variables and functions -- but not
7876      static data members in uninstantiated class templates.  */
7877   if (VAR_OR_FUNCTION_DECL_P (decl))
7878     {
7879       if (VAR_P (decl))
7880         {
7881           layout_var_decl (decl);
7882           if (!flag_weak)
7883             /* Check again now that we have an initializer.  */
7884             maybe_commonize_var (decl);
7885         }
7886
7887       if (var_definition_p
7888           /* With -fmerge-all-constants, gimplify_init_constructor
7889              might add TREE_STATIC to the variable.  */
7890           && (TREE_STATIC (decl) || flag_merge_constants >= 2))
7891         {
7892           /* If a TREE_READONLY variable needs initialization
7893              at runtime, it is no longer readonly and we need to
7894              avoid MEM_READONLY_P being set on RTL created for it.  */
7895           if (init)
7896             {
7897               if (TREE_READONLY (decl))
7898                 TREE_READONLY (decl) = 0;
7899               was_readonly = 0;
7900             }
7901           else if (was_readonly)
7902             TREE_READONLY (decl) = 1;
7903
7904           /* Likewise if it needs destruction.  */
7905           if (!decl_maybe_constant_destruction (decl, type))
7906             TREE_READONLY (decl) = 0;
7907         }
7908
7909       make_rtl_for_nonlocal_decl (decl, init, asmspec);
7910
7911       /* Check for abstractness of the type. Notice that there is no
7912          need to strip array types here since the check for those types
7913          is already done within create_array_type_for_decl.  */
7914       abstract_virtuals_error (decl, type);
7915
7916       if (TREE_TYPE (decl) == error_mark_node)
7917         /* No initialization required.  */
7918         ;
7919       else if (TREE_CODE (decl) == FUNCTION_DECL)
7920         {
7921           if (init)
7922             {
7923               if (init == ridpointers[(int)RID_DEFAULT])
7924                 {
7925                   /* An out-of-class default definition is defined at
7926                      the point where it is explicitly defaulted.  */
7927                   if (DECL_DELETED_FN (decl))
7928                     maybe_explain_implicit_delete (decl);
7929                   else if (DECL_INITIAL (decl) == error_mark_node)
7930                     synthesize_method (decl);
7931                 }
7932               else
7933                 error_at (cp_expr_loc_or_loc (init,
7934                                               DECL_SOURCE_LOCATION (decl)),
7935                           "function %q#D is initialized like a variable",
7936                           decl);
7937             }
7938           /* else no initialization required.  */
7939         }
7940       else if (DECL_EXTERNAL (decl)
7941                && ! (DECL_LANG_SPECIFIC (decl)
7942                      && DECL_NOT_REALLY_EXTERN (decl)))
7943         {
7944           /* check_initializer will have done any constant initialization.  */
7945         }
7946       /* A variable definition.  */
7947       else if (DECL_FUNCTION_SCOPE_P (decl) && !TREE_STATIC (decl))
7948         /* Initialize the local variable.  */
7949         initialize_local_var (decl, init);
7950
7951       /* If a variable is defined, and then a subsequent
7952          definition with external linkage is encountered, we will
7953          get here twice for the same variable.  We want to avoid
7954          calling expand_static_init more than once.  For variables
7955          that are not static data members, we can call
7956          expand_static_init only when we actually process the
7957          initializer.  It is not legal to redeclare a static data
7958          member, so this issue does not arise in that case.  */
7959       else if (var_definition_p && TREE_STATIC (decl))
7960         expand_static_init (decl, init);
7961     }
7962
7963   /* If a CLEANUP_STMT was created to destroy a temporary bound to a
7964      reference, insert it in the statement-tree now.  */
7965   if (cleanups)
7966     {
7967       unsigned i; tree t;
7968       FOR_EACH_VEC_ELT (*cleanups, i, t)
7969         push_cleanup (decl, t, false);
7970       release_tree_vector (cleanups);
7971     }
7972
7973   if (was_readonly)
7974     TREE_READONLY (decl) = 1;
7975
7976   if (flag_openmp
7977       && VAR_P (decl)
7978       && lookup_attribute ("omp declare target implicit",
7979                            DECL_ATTRIBUTES (decl)))
7980     {
7981       DECL_ATTRIBUTES (decl)
7982         = remove_attribute ("omp declare target implicit",
7983                             DECL_ATTRIBUTES (decl));
7984       complete_type (TREE_TYPE (decl));
7985       if (!cp_omp_mappable_type (TREE_TYPE (decl)))
7986         {
7987           error ("%q+D in declare target directive does not have mappable"
7988                  " type", decl);
7989           cp_omp_emit_unmappable_type_notes (TREE_TYPE (decl));
7990         }
7991       else if (!lookup_attribute ("omp declare target",
7992                                   DECL_ATTRIBUTES (decl))
7993                && !lookup_attribute ("omp declare target link",
7994                                      DECL_ATTRIBUTES (decl)))
7995         DECL_ATTRIBUTES (decl)
7996           = tree_cons (get_identifier ("omp declare target"),
7997                        NULL_TREE, DECL_ATTRIBUTES (decl));
7998     }
7999
8000   /* This is the last point we can lower alignment so give the target the
8001      chance to do so.  */
8002   if (VAR_P (decl)
8003       && !is_global_var (decl)
8004       && !DECL_HARD_REGISTER (decl))
8005     targetm.lower_local_decl_alignment (decl);
8006
8007   invoke_plugin_callbacks (PLUGIN_FINISH_DECL, decl);
8008 }
8009
8010 /* For class TYPE return itself or some its bases that contain
8011    any direct non-static data members.  Return error_mark_node if an
8012    error has been diagnosed.  */
8013
8014 static tree
8015 find_decomp_class_base (location_t loc, tree type, tree ret)
8016 {
8017   bool member_seen = false;
8018   for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
8019     if (TREE_CODE (field) != FIELD_DECL
8020         || DECL_ARTIFICIAL (field)
8021         || DECL_UNNAMED_BIT_FIELD (field))
8022       continue;
8023     else if (ret)
8024       return type;
8025     else if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
8026       {
8027         if (TREE_CODE (TREE_TYPE (field)) == RECORD_TYPE)
8028           error_at (loc, "cannot decompose class type %qT because it has an "
8029                          "anonymous struct member", type);
8030         else
8031           error_at (loc, "cannot decompose class type %qT because it has an "
8032                          "anonymous union member", type);
8033         inform (DECL_SOURCE_LOCATION (field), "declared here");
8034         return error_mark_node;
8035       }
8036     else if (!accessible_p (type, field, true))
8037       {
8038         error_at (loc, "cannot decompose inaccessible member %qD of %qT",
8039                   field, type);
8040         inform (DECL_SOURCE_LOCATION (field),
8041                 TREE_PRIVATE (field)
8042                 ? G_("declared private here")
8043                 : G_("declared protected here"));
8044         return error_mark_node;
8045       }
8046     else
8047       member_seen = true;
8048
8049   tree base_binfo, binfo;
8050   tree orig_ret = ret;
8051   int i;
8052   if (member_seen)
8053     ret = type;
8054   for (binfo = TYPE_BINFO (type), i = 0;
8055        BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
8056     {
8057       tree t = find_decomp_class_base (loc, TREE_TYPE (base_binfo), ret);
8058       if (t == error_mark_node)
8059         return error_mark_node;
8060       if (t != NULL_TREE && t != ret)
8061         {
8062           if (ret == type)
8063             {
8064               error_at (loc, "cannot decompose class type %qT: both it and "
8065                              "its base class %qT have non-static data members",
8066                         type, t);
8067               return error_mark_node;
8068             }
8069           else if (orig_ret != NULL_TREE)
8070             return t;
8071           else if (ret != NULL_TREE)
8072             {
8073               error_at (loc, "cannot decompose class type %qT: its base "
8074                              "classes %qT and %qT have non-static data "
8075                              "members", type, ret, t);
8076               return error_mark_node;
8077             }
8078           else
8079             ret = t;
8080         }
8081     }
8082   return ret;
8083 }
8084
8085 /* Return std::tuple_size<TYPE>::value.  */
8086
8087 static tree
8088 get_tuple_size (tree type)
8089 {
8090   tree args = make_tree_vec (1);
8091   TREE_VEC_ELT (args, 0) = type;
8092   tree inst = lookup_template_class (tuple_size_identifier, args,
8093                                      /*in_decl*/NULL_TREE,
8094                                      /*context*/std_node,
8095                                      /*entering_scope*/false, tf_none);
8096   inst = complete_type (inst);
8097   if (inst == error_mark_node || !COMPLETE_TYPE_P (inst))
8098     return NULL_TREE;
8099   tree val = lookup_qualified_name (inst, value_identifier,
8100                                     LOOK_want::NORMAL, /*complain*/false);
8101   if (TREE_CODE (val) == VAR_DECL || TREE_CODE (val) == CONST_DECL)
8102     val = maybe_constant_value (val);
8103   if (TREE_CODE (val) == INTEGER_CST)
8104     return val;
8105   else
8106     return error_mark_node;
8107 }
8108
8109 /* Return std::tuple_element<I,TYPE>::type.  */
8110
8111 static tree
8112 get_tuple_element_type (tree type, unsigned i)
8113 {
8114   tree args = make_tree_vec (2);
8115   TREE_VEC_ELT (args, 0) = build_int_cst (integer_type_node, i);
8116   TREE_VEC_ELT (args, 1) = type;
8117   tree inst = lookup_template_class (tuple_element_identifier, args,
8118                                      /*in_decl*/NULL_TREE,
8119                                      /*context*/std_node,
8120                                      /*entering_scope*/false,
8121                                      tf_warning_or_error);
8122   return make_typename_type (inst, type_identifier,
8123                              none_type, tf_warning_or_error);
8124 }
8125
8126 /* Return e.get<i>() or get<i>(e).  */
8127
8128 static tree
8129 get_tuple_decomp_init (tree decl, unsigned i)
8130 {
8131   tree targs = make_tree_vec (1);
8132   TREE_VEC_ELT (targs, 0) = build_int_cst (integer_type_node, i);
8133
8134   tree etype = TREE_TYPE (decl);
8135   tree e = convert_from_reference (decl);
8136
8137   /* [The id-expression] e is an lvalue if the type of the entity e is an
8138      lvalue reference and an xvalue otherwise.  */
8139   if (!TYPE_REF_P (etype)
8140       || TYPE_REF_IS_RVALUE (etype))
8141     e = move (e);
8142
8143   tree fns = lookup_qualified_name (TREE_TYPE (e), get__identifier,
8144                                     LOOK_want::NORMAL, /*complain*/false);
8145   bool use_member_get = false;
8146
8147   /* To use a member get, member lookup must find at least one
8148      declaration that is a function template
8149      whose first template parameter is a non-type parameter.  */
8150   for (lkp_iterator iter (MAYBE_BASELINK_FUNCTIONS (fns)); iter; ++iter)
8151     {
8152       tree fn = *iter;
8153       if (TREE_CODE (fn) == TEMPLATE_DECL)
8154         {
8155           tree tparms = DECL_TEMPLATE_PARMS (fn);
8156           tree parm = TREE_VEC_ELT (INNERMOST_TEMPLATE_PARMS (tparms), 0);
8157           if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
8158             {
8159               use_member_get = true;
8160               break;
8161             }
8162         }
8163     }
8164
8165   if (use_member_get)
8166     {
8167       fns = lookup_template_function (fns, targs);
8168       return build_new_method_call (e, fns, /*args*/NULL,
8169                                     /*path*/NULL_TREE, LOOKUP_NORMAL,
8170                                     /*fn_p*/NULL, tf_warning_or_error);
8171     }
8172   else
8173     {
8174       releasing_vec args (make_tree_vector_single (e));
8175       fns = lookup_template_function (get__identifier, targs);
8176       fns = perform_koenig_lookup (fns, args, tf_warning_or_error);
8177       return finish_call_expr (fns, &args, /*novirt*/false,
8178                                /*koenig*/true, tf_warning_or_error);
8179     }
8180 }
8181
8182 /* It's impossible to recover the decltype of a tuple decomposition variable
8183    based on the actual type of the variable, so store it in a hash table.  */
8184
8185 static GTY((cache)) decl_tree_cache_map *decomp_type_table;
8186
8187 tree
8188 lookup_decomp_type (tree v)
8189 {
8190   return *decomp_type_table->get (v);
8191 }
8192
8193 /* Mangle a decomposition declaration if needed.  Arguments like
8194    in cp_finish_decomp.  */
8195
8196 void
8197 cp_maybe_mangle_decomp (tree decl, tree first, unsigned int count)
8198 {
8199   if (!processing_template_decl
8200       && !error_operand_p (decl)
8201       && TREE_STATIC (decl))
8202     {
8203       auto_vec<tree, 16> v;
8204       v.safe_grow (count, true);
8205       tree d = first;
8206       for (unsigned int i = 0; i < count; i++, d = DECL_CHAIN (d))
8207         v[count - i - 1] = d;
8208       SET_DECL_ASSEMBLER_NAME (decl, mangle_decomp (decl, v));
8209       maybe_apply_pragma_weak (decl);
8210     }
8211 }
8212
8213 /* Finish a decomposition declaration.  DECL is the underlying declaration
8214    "e", FIRST is the head of a chain of decls for the individual identifiers
8215    chained through DECL_CHAIN in reverse order and COUNT is the number of
8216    those decls.  */
8217
8218 void
8219 cp_finish_decomp (tree decl, tree first, unsigned int count)
8220 {
8221   if (error_operand_p (decl))
8222     {
8223      error_out:
8224       while (count--)
8225         {
8226           TREE_TYPE (first) = error_mark_node;
8227           if (DECL_HAS_VALUE_EXPR_P (first))
8228             {
8229               SET_DECL_VALUE_EXPR (first, NULL_TREE);
8230               DECL_HAS_VALUE_EXPR_P (first) = 0;
8231             }
8232           first = DECL_CHAIN (first);
8233         }
8234       if (DECL_P (decl) && DECL_NAMESPACE_SCOPE_P (decl))
8235         SET_DECL_ASSEMBLER_NAME (decl, get_identifier ("<decomp>"));
8236       return;
8237     }
8238
8239   location_t loc = DECL_SOURCE_LOCATION (decl);
8240   if (type_dependent_expression_p (decl)
8241       /* This happens for range for when not in templates.
8242          Still add the DECL_VALUE_EXPRs for later processing.  */
8243       || (!processing_template_decl
8244           && type_uses_auto (TREE_TYPE (decl))))
8245     {
8246       for (unsigned int i = 0; i < count; i++)
8247         {
8248           if (!DECL_HAS_VALUE_EXPR_P (first))
8249             {
8250               tree v = build_nt (ARRAY_REF, decl,
8251                                  size_int (count - i - 1),
8252                                  NULL_TREE, NULL_TREE);
8253               SET_DECL_VALUE_EXPR (first, v);
8254               DECL_HAS_VALUE_EXPR_P (first) = 1;
8255             }
8256           if (processing_template_decl)
8257             fit_decomposition_lang_decl (first, decl);
8258           first = DECL_CHAIN (first);
8259         }
8260       return;
8261     }
8262
8263   auto_vec<tree, 16> v;
8264   v.safe_grow (count, true);
8265   tree d = first;
8266   for (unsigned int i = 0; i < count; i++, d = DECL_CHAIN (d))
8267     {
8268       v[count - i - 1] = d;
8269       fit_decomposition_lang_decl (d, decl);
8270     }
8271
8272   tree type = TREE_TYPE (decl);
8273   tree dexp = decl;
8274
8275   if (TYPE_REF_P (type))
8276     {
8277       dexp = convert_from_reference (dexp);
8278       type = complete_type (TREE_TYPE (type));
8279       if (type == error_mark_node)
8280         goto error_out;
8281       if (!COMPLETE_TYPE_P (type))
8282         {
8283           error_at (loc, "structured binding refers to incomplete type %qT",
8284                     type);
8285           goto error_out;
8286         }
8287     }
8288
8289   tree eltype = NULL_TREE;
8290   unsigned HOST_WIDE_INT eltscnt = 0;
8291   if (TREE_CODE (type) == ARRAY_TYPE)
8292     {
8293       tree nelts;
8294       nelts = array_type_nelts_top (type);
8295       if (nelts == error_mark_node)
8296         goto error_out;
8297       if (!tree_fits_uhwi_p (nelts))
8298         {
8299           error_at (loc, "cannot decompose variable length array %qT", type);
8300           goto error_out;
8301         }
8302       eltscnt = tree_to_uhwi (nelts);
8303       if (count != eltscnt)
8304         {
8305        cnt_mismatch:
8306           if (count > eltscnt)
8307             error_n (loc, count,
8308                      "%u name provided for structured binding",
8309                      "%u names provided for structured binding", count);
8310           else
8311             error_n (loc, count,
8312                      "only %u name provided for structured binding",
8313                      "only %u names provided for structured binding", count);
8314           inform_n (loc, eltscnt,
8315                     "while %qT decomposes into %wu element",
8316                     "while %qT decomposes into %wu elements",
8317                     type, eltscnt);
8318           goto error_out;
8319         }
8320       eltype = TREE_TYPE (type);
8321       for (unsigned int i = 0; i < count; i++)
8322         {
8323           TREE_TYPE (v[i]) = eltype;
8324           layout_decl (v[i], 0);
8325           if (processing_template_decl)
8326             continue;
8327           tree t = unshare_expr (dexp);
8328           t = build4_loc (DECL_SOURCE_LOCATION (v[i]), ARRAY_REF,
8329                           eltype, t, size_int (i), NULL_TREE,
8330                           NULL_TREE);
8331           SET_DECL_VALUE_EXPR (v[i], t);
8332           DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
8333         }
8334     }
8335   /* 2 GNU extensions.  */
8336   else if (TREE_CODE (type) == COMPLEX_TYPE)
8337     {
8338       eltscnt = 2;
8339       if (count != eltscnt)
8340         goto cnt_mismatch;
8341       eltype = cp_build_qualified_type (TREE_TYPE (type), TYPE_QUALS (type));
8342       for (unsigned int i = 0; i < count; i++)
8343         {
8344           TREE_TYPE (v[i]) = eltype;
8345           layout_decl (v[i], 0);
8346           if (processing_template_decl)
8347             continue;
8348           tree t = unshare_expr (dexp);
8349           t = build1_loc (DECL_SOURCE_LOCATION (v[i]),
8350                           i ? IMAGPART_EXPR : REALPART_EXPR, eltype,
8351                           t);
8352           SET_DECL_VALUE_EXPR (v[i], t);
8353           DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
8354         }
8355     }
8356   else if (TREE_CODE (type) == VECTOR_TYPE)
8357     {
8358       if (!TYPE_VECTOR_SUBPARTS (type).is_constant (&eltscnt))
8359         {
8360           error_at (loc, "cannot decompose variable length vector %qT", type);
8361           goto error_out;
8362         }
8363       if (count != eltscnt)
8364         goto cnt_mismatch;
8365       eltype = cp_build_qualified_type (TREE_TYPE (type), TYPE_QUALS (type));
8366       for (unsigned int i = 0; i < count; i++)
8367         {
8368           TREE_TYPE (v[i]) = eltype;
8369           layout_decl (v[i], 0);
8370           if (processing_template_decl)
8371             continue;
8372           tree t = unshare_expr (dexp);
8373           convert_vector_to_array_for_subscript (DECL_SOURCE_LOCATION (v[i]),
8374                                                  &t, size_int (i));
8375           t = build4_loc (DECL_SOURCE_LOCATION (v[i]), ARRAY_REF,
8376                           eltype, t, size_int (i), NULL_TREE,
8377                           NULL_TREE);
8378           SET_DECL_VALUE_EXPR (v[i], t);
8379           DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
8380         }
8381     }
8382   else if (tree tsize = get_tuple_size (type))
8383     {
8384       if (tsize == error_mark_node)
8385         {
8386           error_at (loc, "%<std::tuple_size<%T>::value%> is not an integral "
8387                          "constant expression", type);
8388           goto error_out;
8389         }
8390       if (!tree_fits_uhwi_p (tsize))
8391         {
8392           error_n (loc, count,
8393                    "%u name provided for structured binding",
8394                    "%u names provided for structured binding", count);
8395           inform (loc, "while %qT decomposes into %E elements",
8396                   type, tsize);
8397           goto error_out;
8398         }
8399       eltscnt = tree_to_uhwi (tsize);
8400       if (count != eltscnt)
8401         goto cnt_mismatch;
8402       int save_read = DECL_READ_P (decl);       
8403       for (unsigned i = 0; i < count; ++i)
8404         {
8405           location_t sloc = input_location;
8406           location_t dloc = DECL_SOURCE_LOCATION (v[i]);
8407
8408           input_location = dloc;
8409           tree init = get_tuple_decomp_init (decl, i);
8410           tree eltype = (init == error_mark_node ? error_mark_node
8411                          : get_tuple_element_type (type, i));
8412           input_location = sloc;
8413
8414           if (init == error_mark_node || eltype == error_mark_node)
8415             {
8416               inform (dloc, "in initialization of structured binding "
8417                       "variable %qD", v[i]);
8418               goto error_out;
8419             }
8420           /* Save the decltype away before reference collapse.  */
8421           hash_map_safe_put<hm_ggc> (decomp_type_table, v[i], eltype);
8422           eltype = cp_build_reference_type (eltype, !lvalue_p (init));
8423           TREE_TYPE (v[i]) = eltype;
8424           layout_decl (v[i], 0);
8425           if (DECL_HAS_VALUE_EXPR_P (v[i]))
8426             {
8427               /* In this case the names are variables, not just proxies.  */
8428               SET_DECL_VALUE_EXPR (v[i], NULL_TREE);
8429               DECL_HAS_VALUE_EXPR_P (v[i]) = 0;
8430             }
8431           if (!processing_template_decl)
8432             {
8433               copy_linkage (v[i], decl);
8434               cp_finish_decl (v[i], init, /*constexpr*/false,
8435                               /*asm*/NULL_TREE, LOOKUP_NORMAL);
8436             }
8437         }
8438       /* Ignore reads from the underlying decl performed during initialization
8439          of the individual variables.  If those will be read, we'll mark
8440          the underlying decl as read at that point.  */
8441       DECL_READ_P (decl) = save_read;
8442     }
8443   else if (TREE_CODE (type) == UNION_TYPE)
8444     {
8445       error_at (loc, "cannot decompose union type %qT", type);
8446       goto error_out;
8447     }
8448   else if (!CLASS_TYPE_P (type))
8449     {
8450       error_at (loc, "cannot decompose non-array non-class type %qT", type);
8451       goto error_out;
8452     }
8453   else if (LAMBDA_TYPE_P (type))
8454     {
8455       error_at (loc, "cannot decompose lambda closure type %qT", type);
8456       goto error_out;
8457     }
8458   else if (processing_template_decl && complete_type (type) == error_mark_node)
8459     goto error_out;
8460   else if (processing_template_decl && !COMPLETE_TYPE_P (type))
8461     pedwarn (loc, 0, "structured binding refers to incomplete class type %qT",
8462              type);
8463   else
8464     {
8465       tree btype = find_decomp_class_base (loc, type, NULL_TREE);
8466       if (btype == error_mark_node)
8467         goto error_out;
8468       else if (btype == NULL_TREE)
8469         {
8470           error_at (loc, "cannot decompose class type %qT without non-static "
8471                          "data members", type);
8472           goto error_out;
8473         }
8474       for (tree field = TYPE_FIELDS (btype); field; field = TREE_CHAIN (field))
8475         if (TREE_CODE (field) != FIELD_DECL
8476             || DECL_ARTIFICIAL (field)
8477             || DECL_UNNAMED_BIT_FIELD (field))
8478           continue;
8479         else
8480           eltscnt++;
8481       if (count != eltscnt)
8482         goto cnt_mismatch;
8483       tree t = dexp;
8484       if (type != btype)
8485         {
8486           t = convert_to_base (t, btype, /*check_access*/true,
8487                                /*nonnull*/false, tf_warning_or_error);
8488           type = btype;
8489         }
8490       unsigned int i = 0;
8491       for (tree field = TYPE_FIELDS (btype); field; field = TREE_CHAIN (field))
8492         if (TREE_CODE (field) != FIELD_DECL
8493             || DECL_ARTIFICIAL (field)
8494             || DECL_UNNAMED_BIT_FIELD (field))
8495           continue;
8496         else
8497           {
8498             tree tt = finish_non_static_data_member (field, unshare_expr (t),
8499                                                      NULL_TREE);
8500             if (REFERENCE_REF_P (tt))
8501               tt = TREE_OPERAND (tt, 0);
8502             TREE_TYPE (v[i]) = TREE_TYPE (tt);
8503             layout_decl (v[i], 0);
8504             if (!processing_template_decl)
8505               {
8506                 SET_DECL_VALUE_EXPR (v[i], tt);
8507                 DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
8508               }
8509             i++;
8510           }
8511     }
8512   if (processing_template_decl)
8513     {
8514       for (unsigned int i = 0; i < count; i++)
8515         if (!DECL_HAS_VALUE_EXPR_P (v[i]))
8516           {
8517             tree a = build_nt (ARRAY_REF, decl, size_int (i),
8518                                NULL_TREE, NULL_TREE);
8519             SET_DECL_VALUE_EXPR (v[i], a);
8520             DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
8521           }
8522     }
8523 }
8524
8525 /* Returns a declaration for a VAR_DECL as if:
8526
8527      extern "C" TYPE NAME;
8528
8529    had been seen.  Used to create compiler-generated global
8530    variables.  */
8531
8532 static tree
8533 declare_global_var (tree name, tree type)
8534 {
8535   tree decl;
8536
8537   push_to_top_level ();
8538   decl = build_decl (input_location, VAR_DECL, name, type);
8539   TREE_PUBLIC (decl) = 1;
8540   DECL_EXTERNAL (decl) = 1;
8541   DECL_ARTIFICIAL (decl) = 1;
8542   DECL_CONTEXT (decl) = FROB_CONTEXT (global_namespace);
8543   /* If the user has explicitly declared this variable (perhaps
8544      because the code we are compiling is part of a low-level runtime
8545      library), then it is possible that our declaration will be merged
8546      with theirs by pushdecl.  */
8547   decl = pushdecl (decl);
8548   cp_finish_decl (decl, NULL_TREE, false, NULL_TREE, 0);
8549   pop_from_top_level ();
8550
8551   return decl;
8552 }
8553
8554 /* Returns the type for the argument to "__cxa_atexit" (or "atexit",
8555    if "__cxa_atexit" is not being used) corresponding to the function
8556    to be called when the program exits.  */
8557
8558 static tree
8559 get_atexit_fn_ptr_type (void)
8560 {
8561   tree fn_type;
8562
8563   if (!atexit_fn_ptr_type_node)
8564     {
8565       tree arg_type;
8566       if (flag_use_cxa_atexit 
8567           && !targetm.cxx.use_atexit_for_cxa_atexit ())
8568         /* The parameter to "__cxa_atexit" is "void (*)(void *)".  */
8569         arg_type = ptr_type_node;
8570       else
8571         /* The parameter to "atexit" is "void (*)(void)".  */
8572         arg_type = NULL_TREE;
8573       
8574       fn_type = build_function_type_list (void_type_node,
8575                                           arg_type, NULL_TREE);
8576       atexit_fn_ptr_type_node = build_pointer_type (fn_type);
8577     }
8578
8579   return atexit_fn_ptr_type_node;
8580 }
8581
8582 /* Returns a pointer to the `atexit' function.  Note that if
8583    FLAG_USE_CXA_ATEXIT is nonzero, then this will actually be the new
8584    `__cxa_atexit' function specified in the IA64 C++ ABI.  */
8585
8586 static tree
8587 get_atexit_node (void)
8588 {
8589   tree atexit_fndecl;
8590   tree fn_type;
8591   tree fn_ptr_type;
8592   const char *name;
8593   bool use_aeabi_atexit;
8594
8595   if (atexit_node)
8596     return atexit_node;
8597
8598   if (flag_use_cxa_atexit && !targetm.cxx.use_atexit_for_cxa_atexit ())
8599     {
8600       /* The declaration for `__cxa_atexit' is:
8601
8602            int __cxa_atexit (void (*)(void *), void *, void *)
8603
8604          We build up the argument types and then the function type
8605          itself.  */
8606       tree argtype0, argtype1, argtype2;
8607
8608       use_aeabi_atexit = targetm.cxx.use_aeabi_atexit ();
8609       /* First, build the pointer-to-function type for the first
8610          argument.  */
8611       fn_ptr_type = get_atexit_fn_ptr_type ();
8612       /* Then, build the rest of the argument types.  */
8613       argtype2 = ptr_type_node;
8614       if (use_aeabi_atexit)
8615         {
8616           argtype1 = fn_ptr_type;
8617           argtype0 = ptr_type_node;
8618         }
8619       else
8620         {
8621           argtype1 = ptr_type_node;
8622           argtype0 = fn_ptr_type;
8623         }
8624       /* And the final __cxa_atexit type.  */
8625       fn_type = build_function_type_list (integer_type_node,
8626                                           argtype0, argtype1, argtype2,
8627                                           NULL_TREE);
8628       if (use_aeabi_atexit)
8629         name = "__aeabi_atexit";
8630       else
8631         name = "__cxa_atexit";
8632     }
8633   else
8634     {
8635       /* The declaration for `atexit' is:
8636
8637            int atexit (void (*)());
8638
8639          We build up the argument types and then the function type
8640          itself.  */
8641       fn_ptr_type = get_atexit_fn_ptr_type ();
8642       /* Build the final atexit type.  */
8643       fn_type = build_function_type_list (integer_type_node,
8644                                           fn_ptr_type, NULL_TREE);
8645       name = "atexit";
8646     }
8647
8648   /* Now, build the function declaration.  */
8649   push_lang_context (lang_name_c);
8650   atexit_fndecl = build_library_fn_ptr (name, fn_type, ECF_LEAF | ECF_NOTHROW);
8651   mark_used (atexit_fndecl);
8652   pop_lang_context ();
8653   atexit_node = decay_conversion (atexit_fndecl, tf_warning_or_error);
8654
8655   return atexit_node;
8656 }
8657
8658 /* Like get_atexit_node, but for thread-local cleanups.  */
8659
8660 static tree
8661 get_thread_atexit_node (void)
8662 {
8663   /* The declaration for `__cxa_thread_atexit' is:
8664
8665      int __cxa_thread_atexit (void (*)(void *), void *, void *) */
8666   tree fn_type = build_function_type_list (integer_type_node,
8667                                            get_atexit_fn_ptr_type (),
8668                                            ptr_type_node, ptr_type_node,
8669                                            NULL_TREE);
8670
8671   /* Now, build the function declaration.  */
8672   tree atexit_fndecl = build_library_fn_ptr ("__cxa_thread_atexit", fn_type,
8673                                              ECF_LEAF | ECF_NOTHROW);
8674   return decay_conversion (atexit_fndecl, tf_warning_or_error);
8675 }
8676
8677 /* Returns the __dso_handle VAR_DECL.  */
8678
8679 static tree
8680 get_dso_handle_node (void)
8681 {
8682   if (dso_handle_node)
8683     return dso_handle_node;
8684
8685   /* Declare the variable.  */
8686   dso_handle_node = declare_global_var (get_identifier ("__dso_handle"),
8687                                         ptr_type_node);
8688
8689 #ifdef HAVE_GAS_HIDDEN
8690   if (dso_handle_node != error_mark_node)
8691     {
8692       DECL_VISIBILITY (dso_handle_node) = VISIBILITY_HIDDEN;
8693       DECL_VISIBILITY_SPECIFIED (dso_handle_node) = 1;
8694     }
8695 #endif
8696
8697   return dso_handle_node;
8698 }
8699
8700 /* Begin a new function with internal linkage whose job will be simply
8701    to destroy some particular variable.  */
8702
8703 static GTY(()) int start_cleanup_cnt;
8704
8705 static tree
8706 start_cleanup_fn (void)
8707 {
8708   char name[32];
8709   tree fntype;
8710   tree fndecl;
8711   bool use_cxa_atexit = flag_use_cxa_atexit
8712                         && !targetm.cxx.use_atexit_for_cxa_atexit ();
8713
8714   push_to_top_level ();
8715
8716   /* No need to mangle this.  */
8717   push_lang_context (lang_name_c);
8718
8719   /* Build the name of the function.  */
8720   sprintf (name, "__tcf_%d", start_cleanup_cnt++);
8721   /* Build the function declaration.  */
8722   fntype = TREE_TYPE (get_atexit_fn_ptr_type ());
8723   fndecl = build_lang_decl (FUNCTION_DECL, get_identifier (name), fntype);
8724   /* It's a function with internal linkage, generated by the
8725      compiler.  */
8726   TREE_PUBLIC (fndecl) = 0;
8727   DECL_ARTIFICIAL (fndecl) = 1;
8728   /* Make the function `inline' so that it is only emitted if it is
8729      actually needed.  It is unlikely that it will be inlined, since
8730      it is only called via a function pointer, but we avoid unnecessary
8731      emissions this way.  */
8732   DECL_DECLARED_INLINE_P (fndecl) = 1;
8733   DECL_INTERFACE_KNOWN (fndecl) = 1;
8734   /* Build the parameter.  */
8735   if (use_cxa_atexit)
8736     {
8737       tree parmdecl = cp_build_parm_decl (fndecl, NULL_TREE, ptr_type_node);
8738       TREE_USED (parmdecl) = 1;
8739       DECL_READ_P (parmdecl) = 1;
8740       DECL_ARGUMENTS (fndecl) = parmdecl;
8741     }
8742
8743   pushdecl (fndecl);
8744   start_preparsed_function (fndecl, NULL_TREE, SF_PRE_PARSED);
8745
8746   pop_lang_context ();
8747
8748   return current_function_decl;
8749 }
8750
8751 /* Finish the cleanup function begun by start_cleanup_fn.  */
8752
8753 static void
8754 end_cleanup_fn (void)
8755 {
8756   expand_or_defer_fn (finish_function (/*inline_p=*/false));
8757
8758   pop_from_top_level ();
8759 }
8760
8761 /* Generate code to handle the destruction of DECL, an object with
8762    static storage duration.  */
8763
8764 tree
8765 register_dtor_fn (tree decl)
8766 {
8767   tree cleanup;
8768   tree addr;
8769   tree compound_stmt;
8770   tree fcall;
8771   tree type;
8772   bool ob_parm, dso_parm, use_dtor;
8773   tree arg0, arg1, arg2;
8774   tree atex_node;
8775
8776   type = TREE_TYPE (decl);
8777   if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
8778     return void_node;
8779
8780   if (decl_maybe_constant_destruction (decl, type)
8781       && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
8782     {
8783       cxx_maybe_build_cleanup (decl, tf_warning_or_error);
8784       return void_node;
8785     }
8786
8787   /* If we're using "__cxa_atexit" (or "__cxa_thread_atexit" or
8788      "__aeabi_atexit"), and DECL is a class object, we can just pass the
8789      destructor to "__cxa_atexit"; we don't have to build a temporary
8790      function to do the cleanup.  */
8791   dso_parm = (flag_use_cxa_atexit
8792               && !targetm.cxx.use_atexit_for_cxa_atexit ());
8793   ob_parm = (CP_DECL_THREAD_LOCAL_P (decl) || dso_parm);
8794   use_dtor = ob_parm && CLASS_TYPE_P (type);
8795   if (use_dtor)
8796     {
8797       cleanup = get_class_binding (type, complete_dtor_identifier);
8798
8799       /* Make sure it is accessible.  */
8800       perform_or_defer_access_check (TYPE_BINFO (type), cleanup, cleanup,
8801                                      tf_warning_or_error);
8802     }
8803   else
8804     {
8805       /* Call build_cleanup before we enter the anonymous function so
8806          that any access checks will be done relative to the current
8807          scope, rather than the scope of the anonymous function.  */
8808       build_cleanup (decl);
8809   
8810       /* Now start the function.  */
8811       cleanup = start_cleanup_fn ();
8812       
8813       /* Now, recompute the cleanup.  It may contain SAVE_EXPRs that refer
8814          to the original function, rather than the anonymous one.  That
8815          will make the back end think that nested functions are in use,
8816          which causes confusion.  */
8817       push_deferring_access_checks (dk_no_check);
8818       fcall = build_cleanup (decl);
8819       pop_deferring_access_checks ();
8820       
8821       /* Create the body of the anonymous function.  */
8822       compound_stmt = begin_compound_stmt (BCS_FN_BODY);
8823       finish_expr_stmt (fcall);
8824       finish_compound_stmt (compound_stmt);
8825       end_cleanup_fn ();
8826     }
8827
8828   /* Call atexit with the cleanup function.  */
8829   mark_used (cleanup);
8830   cleanup = build_address (cleanup);
8831
8832   if (CP_DECL_THREAD_LOCAL_P (decl))
8833     atex_node = get_thread_atexit_node ();
8834   else
8835     atex_node = get_atexit_node ();
8836
8837   if (use_dtor)
8838     {
8839       /* We must convert CLEANUP to the type that "__cxa_atexit"
8840          expects.  */
8841       cleanup = build_nop (get_atexit_fn_ptr_type (), cleanup);
8842       /* "__cxa_atexit" will pass the address of DECL to the
8843          cleanup function.  */
8844       mark_used (decl);
8845       addr = build_address (decl);
8846       /* The declared type of the parameter to "__cxa_atexit" is
8847          "void *".  For plain "T*", we could just let the
8848          machinery in cp_build_function_call convert it -- but if the
8849          type is "cv-qualified T *", then we need to convert it
8850          before passing it in, to avoid spurious errors.  */
8851       addr = build_nop (ptr_type_node, addr);
8852     }
8853   else
8854     /* Since the cleanup functions we build ignore the address
8855        they're given, there's no reason to pass the actual address
8856        in, and, in general, it's cheaper to pass NULL than any
8857        other value.  */
8858     addr = null_pointer_node;
8859
8860   if (dso_parm)
8861     arg2 = cp_build_addr_expr (get_dso_handle_node (),
8862                                tf_warning_or_error);
8863   else if (ob_parm)
8864     /* Just pass NULL to the dso handle parm if we don't actually
8865        have a DSO handle on this target.  */
8866     arg2 = null_pointer_node;
8867   else
8868     arg2 = NULL_TREE;
8869
8870   if (ob_parm)
8871     {
8872       if (!CP_DECL_THREAD_LOCAL_P (decl)
8873           && targetm.cxx.use_aeabi_atexit ())
8874         {
8875           arg1 = cleanup;
8876           arg0 = addr;
8877         }
8878       else
8879         {
8880           arg1 = addr;
8881           arg0 = cleanup;
8882         }
8883     }
8884   else
8885     {
8886       arg0 = cleanup;
8887       arg1 = NULL_TREE;
8888     }
8889   return cp_build_function_call_nary (atex_node, tf_warning_or_error,
8890                                       arg0, arg1, arg2, NULL_TREE);
8891 }
8892
8893 /* DECL is a VAR_DECL with static storage duration.  INIT, if present,
8894    is its initializer.  Generate code to handle the construction
8895    and destruction of DECL.  */
8896
8897 static void
8898 expand_static_init (tree decl, tree init)
8899 {
8900   gcc_assert (VAR_P (decl));
8901   gcc_assert (TREE_STATIC (decl));
8902
8903   /* Some variables require no dynamic initialization.  */
8904   if (decl_maybe_constant_destruction (decl, TREE_TYPE (decl)))
8905     {
8906       /* Make sure the destructor is callable.  */
8907       cxx_maybe_build_cleanup (decl, tf_warning_or_error);
8908       if (!init)
8909         return;
8910     }
8911
8912   if (CP_DECL_THREAD_LOCAL_P (decl) && DECL_GNU_TLS_P (decl)
8913       && !DECL_FUNCTION_SCOPE_P (decl))
8914     {
8915       location_t dloc = DECL_SOURCE_LOCATION (decl);
8916       if (init)
8917         error_at (dloc, "non-local variable %qD declared %<__thread%> "
8918                   "needs dynamic initialization", decl);
8919       else
8920         error_at (dloc, "non-local variable %qD declared %<__thread%> "
8921                   "has a non-trivial destructor", decl);
8922       static bool informed;
8923       if (!informed)
8924         {
8925           inform (dloc, "C++11 %<thread_local%> allows dynamic "
8926                   "initialization and destruction");
8927           informed = true;
8928         }
8929       return;
8930     }
8931
8932   if (DECL_FUNCTION_SCOPE_P (decl))
8933     {
8934       /* Emit code to perform this initialization but once.  */
8935       tree if_stmt = NULL_TREE, inner_if_stmt = NULL_TREE;
8936       tree then_clause = NULL_TREE, inner_then_clause = NULL_TREE;
8937       tree guard, guard_addr;
8938       tree flag, begin;
8939       /* We don't need thread-safety code for thread-local vars.  */
8940       bool thread_guard = (flag_threadsafe_statics
8941                            && !CP_DECL_THREAD_LOCAL_P (decl));
8942
8943       /* Emit code to perform this initialization but once.  This code
8944          looks like:
8945
8946            static <type> guard;
8947            if (!__atomic_load (guard.first_byte)) {
8948              if (__cxa_guard_acquire (&guard)) {
8949                bool flag = false;
8950                try {
8951                  // Do initialization.
8952                  flag = true; __cxa_guard_release (&guard);
8953                  // Register variable for destruction at end of program.
8954                } catch {
8955                  if (!flag) __cxa_guard_abort (&guard);
8956                }
8957              }
8958            }
8959
8960          Note that the `flag' variable is only set to 1 *after* the
8961          initialization is complete.  This ensures that an exception,
8962          thrown during the construction, will cause the variable to
8963          reinitialized when we pass through this code again, as per:
8964
8965            [stmt.dcl]
8966
8967            If the initialization exits by throwing an exception, the
8968            initialization is not complete, so it will be tried again
8969            the next time control enters the declaration.
8970
8971          This process should be thread-safe, too; multiple threads
8972          should not be able to initialize the variable more than
8973          once.  */
8974
8975       /* Create the guard variable.  */
8976       guard = get_guard (decl);
8977
8978       /* Begin the conditional initialization.  */
8979       if_stmt = begin_if_stmt ();
8980
8981       finish_if_stmt_cond (get_guard_cond (guard, thread_guard), if_stmt);
8982       then_clause = begin_compound_stmt (BCS_NO_SCOPE);
8983
8984       if (thread_guard)
8985         {
8986           tree vfntype = NULL_TREE;
8987           tree acquire_name, release_name, abort_name;
8988           tree acquire_fn, release_fn, abort_fn;
8989           guard_addr = build_address (guard);
8990
8991           acquire_name = get_identifier ("__cxa_guard_acquire");
8992           release_name = get_identifier ("__cxa_guard_release");
8993           abort_name = get_identifier ("__cxa_guard_abort");
8994           acquire_fn = get_global_binding (acquire_name);
8995           release_fn = get_global_binding (release_name);
8996           abort_fn = get_global_binding (abort_name);
8997           if (!acquire_fn)
8998             acquire_fn = push_library_fn
8999               (acquire_name, build_function_type_list (integer_type_node,
9000                                                        TREE_TYPE (guard_addr),
9001                                                        NULL_TREE),
9002                NULL_TREE, ECF_NOTHROW);
9003           if (!release_fn || !abort_fn)
9004             vfntype = build_function_type_list (void_type_node,
9005                                                 TREE_TYPE (guard_addr),
9006                                                 NULL_TREE);
9007           if (!release_fn)
9008             release_fn = push_library_fn (release_name, vfntype, NULL_TREE,
9009                                           ECF_NOTHROW);
9010           if (!abort_fn)
9011             abort_fn = push_library_fn (abort_name, vfntype, NULL_TREE,
9012                                         ECF_NOTHROW | ECF_LEAF);
9013
9014           inner_if_stmt = begin_if_stmt ();
9015           finish_if_stmt_cond (build_call_n (acquire_fn, 1, guard_addr),
9016                                inner_if_stmt);
9017
9018           inner_then_clause = begin_compound_stmt (BCS_NO_SCOPE);
9019           begin = get_target_expr (boolean_false_node);
9020           flag = TARGET_EXPR_SLOT (begin);
9021
9022           TARGET_EXPR_CLEANUP (begin)
9023             = build3 (COND_EXPR, void_type_node, flag,
9024                       void_node,
9025                       build_call_n (abort_fn, 1, guard_addr));
9026           CLEANUP_EH_ONLY (begin) = 1;
9027
9028           /* Do the initialization itself.  */
9029           init = add_stmt_to_compound (begin, init);
9030           init = add_stmt_to_compound
9031             (init, build2 (MODIFY_EXPR, void_type_node, flag, boolean_true_node));
9032           init = add_stmt_to_compound
9033             (init, build_call_n (release_fn, 1, guard_addr));
9034         }
9035       else
9036         init = add_stmt_to_compound (init, set_guard (guard));
9037
9038       /* Use atexit to register a function for destroying this static
9039          variable.  */
9040       init = add_stmt_to_compound (init, register_dtor_fn (decl));
9041
9042       finish_expr_stmt (init);
9043
9044       if (thread_guard)
9045         {
9046           finish_compound_stmt (inner_then_clause);
9047           finish_then_clause (inner_if_stmt);
9048           finish_if_stmt (inner_if_stmt);
9049         }
9050
9051       finish_compound_stmt (then_clause);
9052       finish_then_clause (if_stmt);
9053       finish_if_stmt (if_stmt);
9054     }
9055   else if (CP_DECL_THREAD_LOCAL_P (decl))
9056     tls_aggregates = tree_cons (init, decl, tls_aggregates);
9057   else
9058     static_aggregates = tree_cons (init, decl, static_aggregates);
9059 }
9060
9061 \f
9062 /* Make TYPE a complete type based on INITIAL_VALUE.
9063    Return 0 if successful, 1 if INITIAL_VALUE can't be deciphered,
9064    2 if there was no information (in which case assume 0 if DO_DEFAULT),
9065    3 if the initializer list is empty (in pedantic mode). */
9066
9067 int
9068 cp_complete_array_type (tree *ptype, tree initial_value, bool do_default)
9069 {
9070   int failure;
9071   tree type, elt_type;
9072
9073   /* Don't get confused by a CONSTRUCTOR for some other type.  */
9074   if (initial_value && TREE_CODE (initial_value) == CONSTRUCTOR
9075       && !BRACE_ENCLOSED_INITIALIZER_P (initial_value)
9076       && TREE_CODE (TREE_TYPE (initial_value)) != ARRAY_TYPE)
9077     return 1;
9078
9079   if (initial_value)
9080     {
9081       unsigned HOST_WIDE_INT i;
9082       tree value;
9083
9084       /* An array of character type can be initialized from a
9085          brace-enclosed string constant.
9086
9087          FIXME: this code is duplicated from reshape_init. Probably
9088          we should just call reshape_init here?  */
9089       if (char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (*ptype)))
9090           && TREE_CODE (initial_value) == CONSTRUCTOR
9091           && !vec_safe_is_empty (CONSTRUCTOR_ELTS (initial_value)))
9092         {
9093           vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (initial_value);
9094           tree value = (*v)[0].value;
9095           STRIP_ANY_LOCATION_WRAPPER (value);
9096
9097           if (TREE_CODE (value) == STRING_CST
9098               && v->length () == 1)
9099             initial_value = value;
9100         }
9101
9102       /* If any of the elements are parameter packs, we can't actually
9103          complete this type now because the array size is dependent.  */
9104       if (TREE_CODE (initial_value) == CONSTRUCTOR)
9105         {
9106           FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (initial_value), 
9107                                       i, value)
9108             {
9109               if (PACK_EXPANSION_P (value))
9110                 return 0;
9111             }
9112         }
9113     }
9114
9115   failure = complete_array_type (ptype, initial_value, do_default);
9116
9117   /* We can create the array before the element type is complete, which
9118      means that we didn't have these two bits set in the original type
9119      either.  In completing the type, we are expected to propagate these
9120      bits.  See also complete_type which does the same thing for arrays
9121      of fixed size.  */
9122   type = *ptype;
9123   if (type != error_mark_node && TYPE_DOMAIN (type))
9124     {
9125       elt_type = TREE_TYPE (type);
9126       TYPE_NEEDS_CONSTRUCTING (type) = TYPE_NEEDS_CONSTRUCTING (elt_type);
9127       TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
9128         = TYPE_HAS_NONTRIVIAL_DESTRUCTOR (elt_type);
9129     }
9130
9131   return failure;
9132 }
9133
9134 /* As above, but either give an error or reject zero-size arrays, depending
9135    on COMPLAIN.  */
9136
9137 int
9138 cp_complete_array_type_or_error (tree *ptype, tree initial_value,
9139                                  bool do_default, tsubst_flags_t complain)
9140 {
9141   int failure;
9142   bool sfinae = !(complain & tf_error);
9143   /* In SFINAE context we can't be lenient about zero-size arrays.  */
9144   if (sfinae)
9145     ++pedantic;
9146   failure = cp_complete_array_type (ptype, initial_value, do_default);
9147   if (sfinae)
9148     --pedantic;
9149   if (failure)
9150     {
9151       if (sfinae)
9152         /* Not an error.  */;
9153       else if (failure == 1)
9154         error ("initializer fails to determine size of %qT", *ptype);
9155       else if (failure == 2)
9156         {
9157           if (do_default)
9158             error ("array size missing in %qT", *ptype);
9159         }
9160       else if (failure == 3)
9161         error ("zero-size array %qT", *ptype);
9162       *ptype = error_mark_node;
9163     }
9164   return failure;
9165 }
9166 \f
9167 /* Return zero if something is declared to be a member of type
9168    CTYPE when in the context of CUR_TYPE.  STRING is the error
9169    message to print in that case.  Otherwise, quietly return 1.  */
9170
9171 static int
9172 member_function_or_else (tree ctype, tree cur_type, enum overload_flags flags)
9173 {
9174   if (ctype && ctype != cur_type)
9175     {
9176       if (flags == DTOR_FLAG)
9177         error ("destructor for alien class %qT cannot be a member", ctype);
9178       else
9179         error ("constructor for alien class %qT cannot be a member", ctype);
9180       return 0;
9181     }
9182   return 1;
9183 }
9184 \f
9185 /* Subroutine of `grokdeclarator'.  */
9186
9187 /* Generate errors possibly applicable for a given set of specifiers.
9188    This is for ARM $7.1.2.  */
9189
9190 static void
9191 bad_specifiers (tree object,
9192                 enum bad_spec_place type,
9193                 int virtualp,
9194                 int quals,
9195                 int inlinep,
9196                 int friendp,
9197                 int raises,
9198                 const location_t* locations)
9199 {
9200   switch (type)
9201     {
9202       case BSP_VAR:
9203         if (virtualp)
9204           error_at (locations[ds_virtual],
9205                     "%qD declared as a %<virtual%> variable", object);
9206         if (quals)
9207           error ("%<const%> and %<volatile%> function specifiers on "
9208                  "%qD invalid in variable declaration", object);
9209         break;
9210       case BSP_PARM:
9211         if (virtualp)
9212           error_at (locations[ds_virtual],
9213                     "%qD declared as a %<virtual%> parameter", object);
9214         if (inlinep)
9215           error_at (locations[ds_inline],
9216                     "%qD declared as an %<inline%> parameter", object);
9217         if (quals)
9218           error ("%<const%> and %<volatile%> function specifiers on "
9219                  "%qD invalid in parameter declaration", object);
9220         break;
9221       case BSP_TYPE:
9222         if (virtualp)
9223           error_at (locations[ds_virtual],
9224                     "%qD declared as a %<virtual%> type", object);
9225         if (inlinep)
9226           error_at (locations[ds_inline],
9227                     "%qD declared as an %<inline%> type", object);
9228         if (quals)
9229           error ("%<const%> and %<volatile%> function specifiers on "
9230                  "%qD invalid in type declaration", object);
9231         break;
9232       case BSP_FIELD:
9233         if (virtualp)
9234           error_at (locations[ds_virtual],
9235                     "%qD declared as a %<virtual%> field", object);
9236         if (inlinep)
9237           error_at (locations[ds_inline],
9238                     "%qD declared as an %<inline%> field", object);
9239         if (quals)
9240           error ("%<const%> and %<volatile%> function specifiers on "
9241                  "%qD invalid in field declaration", object);
9242         break;
9243       default:
9244         gcc_unreachable();
9245     }
9246   if (friendp)
9247     error ("%q+D declared as a friend", object);
9248   if (raises
9249       && !flag_noexcept_type
9250       && (TREE_CODE (object) == TYPE_DECL
9251           || (!TYPE_PTRFN_P (TREE_TYPE (object))
9252               && !TYPE_REFFN_P (TREE_TYPE (object))
9253               && !TYPE_PTRMEMFUNC_P (TREE_TYPE (object)))))
9254     error ("%q+D declared with an exception specification", object);
9255 }
9256
9257 /* DECL is a member function or static data member and is presently
9258    being defined.  Check that the definition is taking place in a
9259    valid namespace.  */
9260
9261 static void
9262 check_class_member_definition_namespace (tree decl)
9263 {
9264   /* These checks only apply to member functions and static data
9265      members.  */
9266   gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
9267   /* We check for problems with specializations in pt.c in
9268      check_specialization_namespace, where we can issue better
9269      diagnostics.  */
9270   if (processing_specialization)
9271     return;
9272   /* We check this in check_explicit_instantiation_namespace.  */
9273   if (processing_explicit_instantiation)
9274     return;
9275   /* [class.mfct]
9276
9277      A member function definition that appears outside of the
9278      class definition shall appear in a namespace scope enclosing
9279      the class definition.
9280
9281      [class.static.data]
9282
9283      The definition for a static data member shall appear in a
9284      namespace scope enclosing the member's class definition.  */
9285   if (!is_ancestor (current_namespace, DECL_CONTEXT (decl)))
9286     permerror (input_location, "definition of %qD is not in namespace enclosing %qT",
9287                decl, DECL_CONTEXT (decl));
9288 }
9289
9290 /* Build a PARM_DECL for the "this" parameter of FN.  TYPE is the
9291    METHOD_TYPE for a non-static member function; QUALS are the
9292    cv-qualifiers that apply to the function.  */
9293
9294 tree
9295 build_this_parm (tree fn, tree type, cp_cv_quals quals)
9296 {
9297   tree this_type;
9298   tree qual_type;
9299   tree parm;
9300   cp_cv_quals this_quals;
9301
9302   if (CLASS_TYPE_P (type))
9303     {
9304       this_type
9305         = cp_build_qualified_type (type, quals & ~TYPE_QUAL_RESTRICT);
9306       this_type = build_pointer_type (this_type);
9307     }
9308   else
9309     this_type = type_of_this_parm (type);
9310   /* The `this' parameter is implicitly `const'; it cannot be
9311      assigned to.  */
9312   this_quals = (quals & TYPE_QUAL_RESTRICT) | TYPE_QUAL_CONST;
9313   qual_type = cp_build_qualified_type (this_type, this_quals);
9314   parm = build_artificial_parm (fn, this_identifier, qual_type);
9315   cp_apply_type_quals_to_decl (this_quals, parm);
9316   return parm;
9317 }
9318
9319 /* DECL is a static member function.  Complain if it was declared
9320    with function-cv-quals.  */
9321
9322 static void
9323 check_static_quals (tree decl, cp_cv_quals quals)
9324 {
9325   if (quals != TYPE_UNQUALIFIED)
9326     error ("static member function %q#D declared with type qualifiers",
9327            decl);
9328 }
9329
9330 // Check that FN takes no arguments and returns bool.
9331 static void
9332 check_concept_fn (tree fn)
9333 {
9334   // A constraint is nullary.
9335   if (DECL_ARGUMENTS (fn))
9336     error_at (DECL_SOURCE_LOCATION (fn),
9337               "concept %q#D declared with function parameters", fn);
9338
9339   // The declared return type of the concept shall be bool, and
9340   // it shall not be deduced from it definition.
9341   tree type = TREE_TYPE (TREE_TYPE (fn));
9342   if (is_auto (type))
9343     error_at (DECL_SOURCE_LOCATION (fn),
9344               "concept %q#D declared with a deduced return type", fn);
9345   else if (type != boolean_type_node)
9346     error_at (DECL_SOURCE_LOCATION (fn),
9347               "concept %q#D with non-%<bool%> return type %qT", fn, type);
9348 }
9349
9350 /* Helper function.  Replace the temporary this parameter injected
9351    during cp_finish_omp_declare_simd with the real this parameter.  */
9352
9353 static tree
9354 declare_simd_adjust_this (tree *tp, int *walk_subtrees, void *data)
9355 {
9356   tree this_parm = (tree) data;
9357   if (TREE_CODE (*tp) == PARM_DECL
9358       && DECL_NAME (*tp) == this_identifier
9359       && *tp != this_parm)
9360     *tp = this_parm;
9361   else if (TYPE_P (*tp))
9362     *walk_subtrees = 0;
9363   return NULL_TREE;
9364 }
9365
9366 /* CTYPE is class type, or null if non-class.
9367    TYPE is type this FUNCTION_DECL should have, either FUNCTION_TYPE
9368    or METHOD_TYPE.
9369    DECLARATOR is the function's name.
9370    PARMS is a chain of PARM_DECLs for the function.
9371    VIRTUALP is truthvalue of whether the function is virtual or not.
9372    FLAGS are to be passed through to `grokclassfn'.
9373    QUALS are qualifiers indicating whether the function is `const'
9374    or `volatile'.
9375    RAISES is a list of exceptions that this function can raise.
9376    CHECK is 1 if we must find this method in CTYPE, 0 if we should
9377    not look, and -1 if we should not call `grokclassfn' at all.
9378
9379    SFK is the kind of special function (if any) for the new function.
9380
9381    Returns `NULL_TREE' if something goes wrong, after issuing
9382    applicable error messages.  */
9383
9384 static tree
9385 grokfndecl (tree ctype,
9386             tree type,
9387             tree declarator,
9388             tree parms,
9389             tree orig_declarator,
9390             const cp_decl_specifier_seq *declspecs,
9391             tree decl_reqs,
9392             int virtualp,
9393             enum overload_flags flags,
9394             cp_cv_quals quals,
9395             cp_ref_qualifier rqual,
9396             tree raises,
9397             int check,
9398             int friendp,
9399             int publicp,
9400             int inlinep,
9401             bool deletedp,
9402             special_function_kind sfk,
9403             bool funcdef_flag,
9404             bool late_return_type_p,
9405             int template_count,
9406             tree in_namespace,
9407             tree* attrlist,
9408             location_t location)
9409 {
9410   tree decl;
9411   int staticp = ctype && TREE_CODE (type) == FUNCTION_TYPE;
9412   tree t;
9413
9414   if (location == UNKNOWN_LOCATION)
9415     location = input_location;
9416
9417   /* Was the concept specifier present?  */
9418   bool concept_p = inlinep & 4;
9419
9420   /* Concept declarations must have a corresponding definition.  */
9421   if (concept_p && !funcdef_flag)
9422     {
9423       error_at (location, "concept %qD has no definition", declarator);
9424       return NULL_TREE;
9425     }
9426
9427   type = build_cp_fntype_variant (type, rqual, raises, late_return_type_p);
9428
9429   decl = build_lang_decl_loc (location, FUNCTION_DECL, declarator, type);
9430
9431   /* Set the constraints on the declaration. */
9432   if (flag_concepts)
9433     {
9434       tree tmpl_reqs = NULL_TREE;
9435       tree ctx = friendp ? current_class_type : ctype;
9436       bool block_local = TREE_CODE (current_scope ()) == FUNCTION_DECL;
9437       bool memtmpl = (!block_local
9438                       && (processing_template_decl
9439                           > template_class_depth (ctx)));
9440       if (memtmpl)
9441         tmpl_reqs = TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
9442       tree ci = build_constraints (tmpl_reqs, decl_reqs);
9443       if (concept_p && ci)
9444         {
9445           error_at (location, "a function concept cannot be constrained");
9446           ci = NULL_TREE;
9447         }
9448       /* C++20 CA378: Remove non-templated constrained functions.  */
9449       if (ci
9450           && (block_local
9451               || (!flag_concepts_ts
9452                   && (!processing_template_decl
9453                       || (friendp && !memtmpl && !funcdef_flag)))))
9454         {
9455           error_at (location, "constraints on a non-templated function");
9456           ci = NULL_TREE;
9457         }
9458       set_constraints (decl, ci);
9459     }
9460
9461   if (TREE_CODE (type) == METHOD_TYPE)
9462     {
9463       tree parm = build_this_parm (decl, type, quals);
9464       DECL_CHAIN (parm) = parms;
9465       parms = parm;
9466
9467       /* Allocate space to hold the vptr bit if needed.  */
9468       SET_DECL_ALIGN (decl, MINIMUM_METHOD_BOUNDARY);
9469     }
9470
9471   DECL_ARGUMENTS (decl) = parms;
9472   for (t = parms; t; t = DECL_CHAIN (t))
9473     DECL_CONTEXT (t) = decl;
9474
9475   /* Propagate volatile out from type to decl.  */
9476   if (TYPE_VOLATILE (type))
9477     TREE_THIS_VOLATILE (decl) = 1;
9478
9479   /* Setup decl according to sfk.  */
9480   switch (sfk)
9481     {
9482     case sfk_constructor:
9483     case sfk_copy_constructor:
9484     case sfk_move_constructor:
9485       DECL_CXX_CONSTRUCTOR_P (decl) = 1;
9486       DECL_NAME (decl) = ctor_identifier;
9487       break;
9488     case sfk_destructor:
9489       DECL_CXX_DESTRUCTOR_P (decl) = 1;
9490       DECL_NAME (decl) = dtor_identifier;
9491       break;
9492     default:
9493       break;
9494     }
9495
9496   if (friendp && TREE_CODE (orig_declarator) == TEMPLATE_ID_EXPR)
9497     {
9498       if (funcdef_flag)
9499         error_at (location,
9500                   "defining explicit specialization %qD in friend declaration",
9501                   orig_declarator);
9502       else
9503         {
9504           tree fns = TREE_OPERAND (orig_declarator, 0);
9505           tree args = TREE_OPERAND (orig_declarator, 1);
9506
9507           if (PROCESSING_REAL_TEMPLATE_DECL_P ())
9508             {
9509               /* Something like `template <class T> friend void f<T>()'.  */
9510               error_at (location,
9511                         "invalid use of template-id %qD in declaration "
9512                         "of primary template",
9513                         orig_declarator);
9514               return NULL_TREE;
9515             }
9516
9517
9518           /* A friend declaration of the form friend void f<>().  Record
9519              the information in the TEMPLATE_ID_EXPR.  */
9520           SET_DECL_IMPLICIT_INSTANTIATION (decl);
9521
9522           gcc_assert (identifier_p (fns) || OVL_P (fns));
9523           DECL_TEMPLATE_INFO (decl) = build_template_info (fns, args);
9524
9525           for (t = TYPE_ARG_TYPES (TREE_TYPE (decl)); t; t = TREE_CHAIN (t))
9526             if (TREE_PURPOSE (t)
9527                 && TREE_CODE (TREE_PURPOSE (t)) == DEFERRED_PARSE)
9528             {
9529               error_at (defparse_location (TREE_PURPOSE (t)),
9530                         "default arguments are not allowed in declaration "
9531                         "of friend template specialization %qD",
9532                         decl);
9533               return NULL_TREE;
9534             }
9535
9536           if (inlinep & 1)
9537             {
9538               error_at (declspecs->locations[ds_inline],
9539                         "%<inline%> is not allowed in declaration of friend "
9540                         "template specialization %qD",
9541                         decl);
9542               return NULL_TREE;
9543             }
9544         }
9545     }
9546
9547   /* C++17 11.3.6/4: "If a friend declaration specifies a default argument
9548      expression, that declaration shall be a definition..."  */
9549   if (friendp && !funcdef_flag)
9550     {
9551       for (tree t = FUNCTION_FIRST_USER_PARMTYPE (decl);
9552            t && t != void_list_node; t = TREE_CHAIN (t))
9553         if (TREE_PURPOSE (t))
9554           {
9555             permerror (DECL_SOURCE_LOCATION (decl),
9556                        "friend declaration of %qD specifies default "
9557                        "arguments and isn%'t a definition", decl);
9558             break;
9559           }
9560     }
9561
9562   /* If this decl has namespace scope, set that up.  */
9563   if (in_namespace)
9564     set_decl_namespace (decl, in_namespace, friendp);
9565   else if (ctype)
9566     DECL_CONTEXT (decl) = ctype;
9567   else
9568     DECL_CONTEXT (decl) = FROB_CONTEXT (current_decl_namespace ());
9569
9570   /* `main' and builtins have implicit 'C' linkage.  */
9571   if (ctype == NULL_TREE
9572       && DECL_FILE_SCOPE_P (decl)
9573       && current_lang_name == lang_name_cplusplus
9574       && (MAIN_NAME_P (declarator)
9575           || (IDENTIFIER_LENGTH (declarator) > 10
9576               && IDENTIFIER_POINTER (declarator)[0] == '_'
9577               && IDENTIFIER_POINTER (declarator)[1] == '_'
9578               && strncmp (IDENTIFIER_POINTER (declarator)+2,
9579                           "builtin_", 8) == 0)
9580           || (targetcm.cxx_implicit_extern_c
9581               && (targetcm.cxx_implicit_extern_c
9582                   (IDENTIFIER_POINTER (declarator))))))
9583     SET_DECL_LANGUAGE (decl, lang_c);
9584
9585   /* Should probably propagate const out from type to decl I bet (mrs).  */
9586   if (staticp)
9587     {
9588       DECL_STATIC_FUNCTION_P (decl) = 1;
9589       DECL_CONTEXT (decl) = ctype;
9590     }
9591
9592   if (deletedp)
9593     DECL_DELETED_FN (decl) = 1;
9594
9595   if (ctype && funcdef_flag)
9596     check_class_member_definition_namespace (decl);
9597
9598   if (ctype == NULL_TREE && DECL_MAIN_P (decl))
9599     {
9600       if (PROCESSING_REAL_TEMPLATE_DECL_P())
9601         error_at (location, "cannot declare %<::main%> to be a template");
9602       if (inlinep & 1)
9603         error_at (declspecs->locations[ds_inline],
9604                   "cannot declare %<::main%> to be inline");
9605       if (inlinep & 2)
9606         error_at (declspecs->locations[ds_constexpr],
9607                   "cannot declare %<::main%> to be %qs", "constexpr");
9608       if (inlinep & 8)
9609         error_at (declspecs->locations[ds_consteval],
9610                   "cannot declare %<::main%> to be %qs", "consteval");
9611       if (!publicp)
9612         error_at (location, "cannot declare %<::main%> to be static");
9613       inlinep = 0;
9614       publicp = 1;
9615     }
9616
9617   /* Members of anonymous types and local classes have no linkage; make
9618      them internal.  If a typedef is made later, this will be changed.  */
9619   if (ctype && (!TREE_PUBLIC (TYPE_MAIN_DECL (ctype))
9620                 || decl_function_context (TYPE_MAIN_DECL (ctype))))
9621     publicp = 0;
9622
9623   if (publicp && cxx_dialect == cxx98)
9624     {
9625       /* [basic.link]: A name with no linkage (notably, the name of a class
9626          or enumeration declared in a local scope) shall not be used to
9627          declare an entity with linkage.
9628
9629          DR 757 relaxes this restriction for C++0x.  */
9630       no_linkage_error (decl);
9631     }
9632
9633   TREE_PUBLIC (decl) = publicp;
9634   if (! publicp)
9635     {
9636       DECL_INTERFACE_KNOWN (decl) = 1;
9637       DECL_NOT_REALLY_EXTERN (decl) = 1;
9638     }
9639
9640   /* If the declaration was declared inline, mark it as such.  */
9641   if (inlinep)
9642     {
9643       DECL_DECLARED_INLINE_P (decl) = 1;
9644       if (publicp)
9645         DECL_COMDAT (decl) = 1;
9646     }
9647   if (inlinep & 2)
9648     DECL_DECLARED_CONSTEXPR_P (decl) = true;
9649   else if (inlinep & 8)
9650     {
9651       DECL_DECLARED_CONSTEXPR_P (decl) = true;
9652       SET_DECL_IMMEDIATE_FUNCTION_P (decl);
9653     }
9654
9655   // If the concept declaration specifier was found, check
9656   // that the declaration satisfies the necessary requirements.
9657   if (concept_p)
9658     {
9659       DECL_DECLARED_CONCEPT_P (decl) = true;
9660       check_concept_fn (decl);
9661     }
9662
9663   DECL_EXTERNAL (decl) = 1;
9664   if (TREE_CODE (type) == FUNCTION_TYPE)
9665     {
9666       if (quals || rqual)
9667         TREE_TYPE (decl) = apply_memfn_quals (TREE_TYPE (decl),
9668                                               TYPE_UNQUALIFIED,
9669                                               REF_QUAL_NONE);
9670
9671       if (quals)
9672         {
9673           error (ctype
9674                  ? G_("static member function %qD cannot have cv-qualifier")
9675                  : G_("non-member function %qD cannot have cv-qualifier"),
9676                  decl);
9677           quals = TYPE_UNQUALIFIED;
9678         }
9679
9680       if (rqual)
9681         {
9682           error (ctype
9683                  ? G_("static member function %qD cannot have ref-qualifier")
9684                  : G_("non-member function %qD cannot have ref-qualifier"),
9685                  decl);
9686           rqual = REF_QUAL_NONE;
9687         }
9688     }
9689
9690   if (deduction_guide_p (decl))
9691     {
9692       if (!DECL_NAMESPACE_SCOPE_P (decl))
9693         {
9694           error_at (location, "deduction guide %qD must be declared at "
9695                     "namespace scope", decl);
9696           return NULL_TREE;
9697         }
9698       tree type = TREE_TYPE (DECL_NAME (decl));
9699       if (in_namespace == NULL_TREE
9700           && CP_DECL_CONTEXT (decl) != CP_TYPE_CONTEXT (type))
9701         {
9702           error_at (location, "deduction guide %qD must be declared in the "
9703                               "same scope as %qT", decl, type);
9704           inform (location_of (type), "  declared here");
9705           return NULL_TREE;
9706         }
9707       if (funcdef_flag)
9708         error_at (location,
9709                   "deduction guide %qD must not have a function body", decl);
9710     }
9711   else if (IDENTIFIER_ANY_OP_P (DECL_NAME (decl))
9712            && !grok_op_properties (decl, /*complain=*/true))
9713     return NULL_TREE;
9714   else if (UDLIT_OPER_P (DECL_NAME (decl)))
9715     {
9716       bool long_long_unsigned_p;
9717       bool long_double_p;
9718       const char *suffix = NULL;
9719       /* [over.literal]/6: Literal operators shall not have C linkage. */
9720       if (DECL_LANGUAGE (decl) == lang_c)
9721         {
9722           error_at (location, "literal operator with C linkage");
9723           maybe_show_extern_c_location ();
9724           return NULL_TREE;
9725         }
9726
9727       if (DECL_NAMESPACE_SCOPE_P (decl))
9728         {
9729           if (!check_literal_operator_args (decl, &long_long_unsigned_p,
9730                                             &long_double_p))
9731             {
9732               error_at (location, "%qD has invalid argument list", decl);
9733               return NULL_TREE;
9734             }
9735
9736           suffix = UDLIT_OP_SUFFIX (DECL_NAME (decl));
9737           if (long_long_unsigned_p)
9738             {
9739               if (cpp_interpret_int_suffix (parse_in, suffix, strlen (suffix)))
9740                 warning_at (location, 0, "integer suffix %qs"
9741                             " shadowed by implementation", suffix);
9742             }
9743           else if (long_double_p)
9744             {
9745               if (cpp_interpret_float_suffix (parse_in, suffix, strlen (suffix)))
9746                 warning_at (location, 0, "floating-point suffix %qs"
9747                             " shadowed by implementation", suffix);
9748             }
9749           /* 17.6.3.3.5  */
9750           if (suffix[0] != '_'
9751               && !current_function_decl && !(friendp && !funcdef_flag))
9752             warning_at (location, OPT_Wliteral_suffix,
9753                         "literal operator suffixes not preceded by %<_%>"
9754                         " are reserved for future standardization");
9755         }
9756       else
9757         {
9758           error_at (location, "%qD must be a non-member function", decl);
9759           return NULL_TREE;
9760         }
9761     }
9762
9763   if (funcdef_flag)
9764     /* Make the init_value nonzero so pushdecl knows this is not
9765        tentative.  error_mark_node is replaced later with the BLOCK.  */
9766     DECL_INITIAL (decl) = error_mark_node;
9767
9768   if (TYPE_NOTHROW_P (type) || nothrow_libfn_p (decl))
9769     TREE_NOTHROW (decl) = 1;
9770
9771   if (flag_openmp || flag_openmp_simd)
9772     {
9773       /* Adjust "omp declare simd" attributes.  */
9774       tree ods = lookup_attribute ("omp declare simd", *attrlist);
9775       if (ods)
9776         {
9777           tree attr;
9778           for (attr = ods; attr;
9779                attr = lookup_attribute ("omp declare simd", TREE_CHAIN (attr)))
9780             {
9781               if (TREE_CODE (type) == METHOD_TYPE)
9782                 walk_tree (&TREE_VALUE (attr), declare_simd_adjust_this,
9783                            DECL_ARGUMENTS (decl), NULL);
9784               if (TREE_VALUE (attr) != NULL_TREE)
9785                 {
9786                   tree cl = TREE_VALUE (TREE_VALUE (attr));
9787                   cl = c_omp_declare_simd_clauses_to_numbers
9788                                                 (DECL_ARGUMENTS (decl), cl);
9789                   if (cl)
9790                     TREE_VALUE (TREE_VALUE (attr)) = cl;
9791                   else
9792                     TREE_VALUE (attr) = NULL_TREE;
9793                 }
9794             }
9795         }
9796     }
9797
9798   /* Caller will do the rest of this.  */
9799   if (check < 0)
9800     return decl;
9801
9802   if (ctype != NULL_TREE)
9803     grokclassfn (ctype, decl, flags);
9804
9805   /* 12.4/3  */
9806   if (cxx_dialect >= cxx11
9807       && DECL_DESTRUCTOR_P (decl)
9808       && !TYPE_BEING_DEFINED (DECL_CONTEXT (decl))
9809       && !processing_template_decl)
9810     deduce_noexcept_on_destructor (decl);
9811
9812   decl = check_explicit_specialization (orig_declarator, decl,
9813                                         template_count,
9814                                         2 * funcdef_flag +
9815                                         4 * (friendp != 0) +
9816                                         8 * concept_p,
9817                                         *attrlist);
9818   if (decl == error_mark_node)
9819     return NULL_TREE;
9820
9821   if (DECL_STATIC_FUNCTION_P (decl))
9822     check_static_quals (decl, quals);
9823
9824   if (attrlist)
9825     {
9826       cplus_decl_attributes (&decl, *attrlist, 0);
9827       *attrlist = NULL_TREE;
9828     }
9829
9830   /* Check main's type after attributes have been applied.  */
9831   if (ctype == NULL_TREE && DECL_MAIN_P (decl))
9832     {
9833       if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
9834                         integer_type_node))
9835         {
9836           tree oldtypeargs = TYPE_ARG_TYPES (TREE_TYPE (decl));
9837           tree newtype;
9838           error_at (declspecs->locations[ds_type_spec],
9839                     "%<::main%> must return %<int%>");
9840           newtype = build_function_type (integer_type_node, oldtypeargs);
9841           TREE_TYPE (decl) = newtype;
9842         }
9843       if (warn_main)
9844         check_main_parameter_types (decl);
9845     }
9846
9847   if (ctype != NULL_TREE && check)
9848     {
9849       tree old_decl = check_classfn (ctype, decl,
9850                                      (processing_template_decl
9851                                       > template_class_depth (ctype))
9852                                      ? current_template_parms
9853                                      : NULL_TREE);
9854
9855       if (old_decl == error_mark_node)
9856         return NULL_TREE;
9857
9858       if (old_decl)
9859         {
9860           tree ok;
9861           tree pushed_scope;
9862
9863           if (TREE_CODE (old_decl) == TEMPLATE_DECL)
9864             /* Because grokfndecl is always supposed to return a
9865                FUNCTION_DECL, we pull out the DECL_TEMPLATE_RESULT
9866                here.  We depend on our callers to figure out that its
9867                really a template that's being returned.  */
9868             old_decl = DECL_TEMPLATE_RESULT (old_decl);
9869
9870           if (DECL_STATIC_FUNCTION_P (old_decl)
9871               && TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
9872             {
9873               /* Remove the `this' parm added by grokclassfn.  */
9874               revert_static_member_fn (decl);
9875               check_static_quals (decl, quals);
9876             }
9877           if (DECL_ARTIFICIAL (old_decl))
9878             {
9879               error ("definition of implicitly-declared %qD", old_decl);
9880               return NULL_TREE;
9881             }
9882           else if (DECL_DEFAULTED_FN (old_decl))
9883             {
9884               error ("definition of explicitly-defaulted %q+D", decl);
9885               inform (DECL_SOURCE_LOCATION (old_decl),
9886                       "%q#D explicitly defaulted here", old_decl);
9887               return NULL_TREE;
9888             }
9889
9890           /* Since we've smashed OLD_DECL to its
9891              DECL_TEMPLATE_RESULT, we must do the same to DECL.  */
9892           if (TREE_CODE (decl) == TEMPLATE_DECL)
9893             decl = DECL_TEMPLATE_RESULT (decl);
9894
9895           /* Attempt to merge the declarations.  This can fail, in
9896              the case of some invalid specialization declarations.  */
9897           pushed_scope = push_scope (ctype);
9898           ok = duplicate_decls (decl, old_decl);
9899           if (pushed_scope)
9900             pop_scope (pushed_scope);
9901           if (!ok)
9902             {
9903               error ("no %q#D member function declared in class %qT",
9904                      decl, ctype);
9905               return NULL_TREE;
9906             }
9907           if (ok == error_mark_node)
9908             return NULL_TREE;
9909           return old_decl;
9910         }
9911     }
9912
9913   if (DECL_CONSTRUCTOR_P (decl) && !grok_ctor_properties (ctype, decl))
9914     return NULL_TREE;
9915
9916   if (ctype == NULL_TREE || check)
9917     return decl;
9918
9919   if (virtualp)
9920     DECL_VIRTUAL_P (decl) = 1;
9921
9922   return decl;
9923 }
9924
9925 /* decl is a FUNCTION_DECL.
9926    specifiers are the parsed virt-specifiers.
9927
9928    Set flags to reflect the virt-specifiers.
9929
9930    Returns decl.  */
9931
9932 static tree
9933 set_virt_specifiers (tree decl, cp_virt_specifiers specifiers)
9934 {
9935   if (decl == NULL_TREE)
9936     return decl;
9937   if (specifiers & VIRT_SPEC_OVERRIDE)
9938     DECL_OVERRIDE_P (decl) = 1;
9939   if (specifiers & VIRT_SPEC_FINAL)
9940     DECL_FINAL_P (decl) = 1;
9941   return decl;
9942 }
9943
9944 /* DECL is a VAR_DECL for a static data member.  Set flags to reflect
9945    the linkage that DECL will receive in the object file.  */
9946
9947 static void
9948 set_linkage_for_static_data_member (tree decl)
9949 {
9950   /* A static data member always has static storage duration and
9951      external linkage.  Note that static data members are forbidden in
9952      local classes -- the only situation in which a class has
9953      non-external linkage.  */
9954   TREE_PUBLIC (decl) = 1;
9955   TREE_STATIC (decl) = 1;
9956   /* For non-template classes, static data members are always put
9957      out in exactly those files where they are defined, just as
9958      with ordinary namespace-scope variables.  */
9959   if (!processing_template_decl)
9960     DECL_INTERFACE_KNOWN (decl) = 1;
9961 }
9962
9963 /* Create a VAR_DECL named NAME with the indicated TYPE.
9964
9965    If SCOPE is non-NULL, it is the class type or namespace containing
9966    the variable.  If SCOPE is NULL, the variable should is created in
9967    the innermost enclosing scope.  */
9968
9969 static tree
9970 grokvardecl (tree type,
9971              tree name,
9972              tree orig_declarator,
9973              const cp_decl_specifier_seq *declspecs,
9974              int initialized,
9975              int type_quals,
9976              int inlinep,
9977              bool conceptp,
9978              int template_count,
9979              tree scope,
9980              location_t location)
9981 {
9982   tree decl;
9983   tree explicit_scope;
9984
9985   gcc_assert (!name || identifier_p (name));
9986
9987   bool constp = (type_quals & TYPE_QUAL_CONST) != 0;
9988   bool volatilep = (type_quals & TYPE_QUAL_VOLATILE) != 0;
9989
9990   /* Compute the scope in which to place the variable, but remember
9991      whether or not that scope was explicitly specified by the user.   */
9992   explicit_scope = scope;
9993   if (!scope)
9994     {
9995       /* An explicit "extern" specifier indicates a namespace-scope
9996          variable.  */
9997       if (declspecs->storage_class == sc_extern)
9998         scope = current_decl_namespace ();
9999       else if (!at_function_scope_p ())
10000         scope = current_scope ();
10001     }
10002
10003   if (scope
10004       && (/* If the variable is a namespace-scope variable declared in a
10005              template, we need DECL_LANG_SPECIFIC.  */
10006           (TREE_CODE (scope) == NAMESPACE_DECL && processing_template_decl)
10007           /* Similarly for namespace-scope variables with language linkage
10008              other than C++.  */
10009           || (TREE_CODE (scope) == NAMESPACE_DECL
10010               && current_lang_name != lang_name_cplusplus)
10011           /* Similarly for static data members.  */
10012           || TYPE_P (scope)
10013           /* Similarly for explicit specializations.  */
10014           || (orig_declarator
10015               && TREE_CODE (orig_declarator) == TEMPLATE_ID_EXPR)))
10016     decl = build_lang_decl_loc (location, VAR_DECL, name, type);
10017   else
10018     decl = build_decl (location, VAR_DECL, name, type);
10019
10020   if (explicit_scope && TREE_CODE (explicit_scope) == NAMESPACE_DECL)
10021     set_decl_namespace (decl, explicit_scope, 0);
10022   else
10023     DECL_CONTEXT (decl) = FROB_CONTEXT (scope);
10024
10025   if (declspecs->storage_class == sc_extern)
10026     {
10027       DECL_THIS_EXTERN (decl) = 1;
10028       DECL_EXTERNAL (decl) = !initialized;
10029     }
10030
10031   if (DECL_CLASS_SCOPE_P (decl))
10032     {
10033       set_linkage_for_static_data_member (decl);
10034       /* This function is only called with out-of-class definitions.  */
10035       DECL_EXTERNAL (decl) = 0;
10036       check_class_member_definition_namespace (decl);
10037     }
10038   /* At top level, either `static' or no s.c. makes a definition
10039      (perhaps tentative), and absence of `static' makes it public.  */
10040   else if (toplevel_bindings_p ())
10041     {
10042       TREE_PUBLIC (decl) = (declspecs->storage_class != sc_static
10043                             && (DECL_THIS_EXTERN (decl)
10044                                 || ! constp
10045                                 || volatilep
10046                                 || inlinep));
10047       TREE_STATIC (decl) = ! DECL_EXTERNAL (decl);
10048     }
10049   /* Not at top level, only `static' makes a static definition.  */
10050   else
10051     {
10052       TREE_STATIC (decl) = declspecs->storage_class == sc_static;
10053       TREE_PUBLIC (decl) = DECL_EXTERNAL (decl);
10054     }
10055
10056   if (decl_spec_seq_has_spec_p (declspecs, ds_thread))
10057     {
10058       if (DECL_EXTERNAL (decl) || TREE_STATIC (decl))
10059         {
10060           CP_DECL_THREAD_LOCAL_P (decl) = true;
10061           if (!processing_template_decl)
10062             set_decl_tls_model (decl, decl_default_tls_model (decl));
10063         }
10064       if (declspecs->gnu_thread_keyword_p)
10065         SET_DECL_GNU_TLS_P (decl);
10066     }
10067
10068   /* If the type of the decl has no linkage, make sure that we'll
10069      notice that in mark_used.  */
10070   if (cxx_dialect > cxx98
10071       && decl_linkage (decl) != lk_none
10072       && DECL_LANG_SPECIFIC (decl) == NULL
10073       && !DECL_EXTERN_C_P (decl)
10074       && no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false))
10075     retrofit_lang_decl (decl);
10076
10077   if (TREE_PUBLIC (decl))
10078     {
10079       /* [basic.link]: A name with no linkage (notably, the name of a class
10080          or enumeration declared in a local scope) shall not be used to
10081          declare an entity with linkage.
10082
10083          DR 757 relaxes this restriction for C++0x.  */
10084       if (cxx_dialect < cxx11)
10085         no_linkage_error (decl);
10086     }
10087   else
10088     DECL_INTERFACE_KNOWN (decl) = 1;
10089
10090   if (DECL_NAME (decl)
10091       && MAIN_NAME_P (DECL_NAME (decl))
10092       && scope == global_namespace)
10093     error_at (DECL_SOURCE_LOCATION (decl),
10094               "cannot declare %<::main%> to be a global variable");
10095
10096   /* Check that the variable can be safely declared as a concept.
10097      Note that this also forbids explicit specializations.  */
10098   if (conceptp)
10099     {
10100       if (!processing_template_decl)
10101         {
10102           error_at (declspecs->locations[ds_concept],
10103                     "a non-template variable cannot be %<concept%>");
10104           return NULL_TREE;
10105         }
10106       else
10107         DECL_DECLARED_CONCEPT_P (decl) = true;
10108       if (!same_type_ignoring_top_level_qualifiers_p (type, boolean_type_node))
10109         error_at (declspecs->locations[ds_type_spec],
10110                   "concept must have type %<bool%>");
10111       if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
10112         {
10113           error_at (location, "a variable concept cannot be constrained");
10114           TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
10115         }
10116     }
10117   else if (flag_concepts
10118            && processing_template_decl > template_class_depth (scope))
10119     {
10120       tree reqs = TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
10121       tree ci = build_constraints (reqs, NULL_TREE);
10122
10123       set_constraints (decl, ci);
10124     }
10125
10126   // Handle explicit specializations and instantiations of variable templates.
10127   if (orig_declarator)
10128     decl = check_explicit_specialization (orig_declarator, decl,
10129                                           template_count, conceptp * 8);
10130
10131   return decl != error_mark_node ? decl : NULL_TREE;
10132 }
10133
10134 /* Create and return a canonical pointer to member function type, for
10135    TYPE, which is a POINTER_TYPE to a METHOD_TYPE.  */
10136
10137 tree
10138 build_ptrmemfunc_type (tree type)
10139 {
10140   tree field, fields;
10141   tree t;
10142
10143   if (type == error_mark_node)
10144     return type;
10145
10146   /* Make sure that we always have the unqualified pointer-to-member
10147      type first.  */
10148   if (cp_cv_quals quals = cp_type_quals (type))
10149     {
10150       tree unqual = build_ptrmemfunc_type (TYPE_MAIN_VARIANT (type));
10151       return cp_build_qualified_type (unqual, quals);
10152     }
10153
10154   /* If a canonical type already exists for this type, use it.  We use
10155      this method instead of type_hash_canon, because it only does a
10156      simple equality check on the list of field members.  */
10157
10158   t = TYPE_PTRMEMFUNC_TYPE (type);
10159   if (t)
10160     return t;
10161
10162   t = make_node (RECORD_TYPE);
10163
10164   /* Let the front end know this is a pointer to member function.  */
10165   TYPE_PTRMEMFUNC_FLAG (t) = 1;
10166
10167   field = build_decl (input_location, FIELD_DECL, pfn_identifier, type);
10168   DECL_NONADDRESSABLE_P (field) = 1;
10169   fields = field;
10170
10171   field = build_decl (input_location, FIELD_DECL, delta_identifier, 
10172                       delta_type_node);
10173   DECL_NONADDRESSABLE_P (field) = 1;
10174   DECL_CHAIN (field) = fields;
10175   fields = field;
10176
10177   finish_builtin_struct (t, "__ptrmemfunc_type", fields, ptr_type_node);
10178
10179   /* Zap out the name so that the back end will give us the debugging
10180      information for this anonymous RECORD_TYPE.  */
10181   TYPE_NAME (t) = NULL_TREE;
10182
10183   /* Cache this pointer-to-member type so that we can find it again
10184      later.  */
10185   TYPE_PTRMEMFUNC_TYPE (type) = t;
10186
10187   if (TYPE_STRUCTURAL_EQUALITY_P (type))
10188     SET_TYPE_STRUCTURAL_EQUALITY (t);
10189   else if (TYPE_CANONICAL (type) != type)
10190     TYPE_CANONICAL (t) = build_ptrmemfunc_type (TYPE_CANONICAL (type));
10191
10192   return t;
10193 }
10194
10195 /* Create and return a pointer to data member type.  */
10196
10197 tree
10198 build_ptrmem_type (tree class_type, tree member_type)
10199 {
10200   if (TREE_CODE (member_type) == METHOD_TYPE)
10201     {
10202       cp_cv_quals quals = type_memfn_quals (member_type);
10203       cp_ref_qualifier rqual = type_memfn_rqual (member_type);
10204       member_type = build_memfn_type (member_type, class_type, quals, rqual);
10205       return build_ptrmemfunc_type (build_pointer_type (member_type));
10206     }
10207   else
10208     {
10209       gcc_assert (TREE_CODE (member_type) != FUNCTION_TYPE);
10210       return build_offset_type (class_type, member_type);
10211     }
10212 }
10213
10214 /* DECL is a VAR_DECL defined in-class, whose TYPE is also given.
10215    Check to see that the definition is valid.  Issue appropriate error
10216    messages.  */
10217
10218 static void
10219 check_static_variable_definition (tree decl, tree type)
10220 {
10221   /* Avoid redundant diagnostics on out-of-class definitions.  */
10222   if (!current_class_type || !TYPE_BEING_DEFINED (current_class_type))
10223     ;
10224   /* Can't check yet if we don't know the type.  */
10225   else if (dependent_type_p (type))
10226     ;
10227   /* If DECL is declared constexpr, we'll do the appropriate checks
10228      in check_initializer.  Similarly for inline static data members.  */
10229   else if (DECL_P (decl)
10230       && (DECL_DECLARED_CONSTEXPR_P (decl)
10231           || DECL_VAR_DECLARED_INLINE_P (decl)))
10232     ;
10233   else if (cxx_dialect >= cxx11 && !INTEGRAL_OR_ENUMERATION_TYPE_P (type))
10234     {
10235       if (!COMPLETE_TYPE_P (type))
10236         error_at (DECL_SOURCE_LOCATION (decl),
10237                   "in-class initialization of static data member %q#D of "
10238                   "incomplete type", decl);
10239       else if (literal_type_p (type))
10240         permerror (DECL_SOURCE_LOCATION (decl),
10241                    "%<constexpr%> needed for in-class initialization of "
10242                    "static data member %q#D of non-integral type", decl);
10243       else
10244         error_at (DECL_SOURCE_LOCATION (decl),
10245                   "in-class initialization of static data member %q#D of "
10246                   "non-literal type", decl);
10247     }
10248   /* Motion 10 at San Diego: If a static const integral data member is
10249      initialized with an integral constant expression, the initializer
10250      may appear either in the declaration (within the class), or in
10251      the definition, but not both.  If it appears in the class, the
10252      member is a member constant.  The file-scope definition is always
10253      required.  */
10254   else if (!ARITHMETIC_TYPE_P (type) && TREE_CODE (type) != ENUMERAL_TYPE)
10255     error_at (DECL_SOURCE_LOCATION (decl),
10256               "invalid in-class initialization of static data member "
10257               "of non-integral type %qT",
10258               type);
10259   else if (!CP_TYPE_CONST_P (type))
10260     error_at (DECL_SOURCE_LOCATION (decl),
10261               "ISO C++ forbids in-class initialization of non-const "
10262               "static member %qD",
10263               decl);
10264   else if (!INTEGRAL_OR_ENUMERATION_TYPE_P (type))
10265     pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wpedantic,
10266              "ISO C++ forbids initialization of member constant "
10267              "%qD of non-integral type %qT", decl, type);
10268 }
10269
10270 /* *expr_p is part of the TYPE_SIZE of a variably-sized array.  If any
10271    SAVE_EXPRs in *expr_p wrap expressions with side-effects, break those
10272    expressions out into temporary variables so that walk_tree doesn't
10273    step into them (c++/15764).  */
10274
10275 static tree
10276 stabilize_save_expr_r (tree *expr_p, int *walk_subtrees, void *data)
10277 {
10278   hash_set<tree> *pset = (hash_set<tree> *)data;
10279   tree expr = *expr_p;
10280   if (TREE_CODE (expr) == SAVE_EXPR)
10281     {
10282       tree op = TREE_OPERAND (expr, 0);
10283       cp_walk_tree (&op, stabilize_save_expr_r, data, pset);
10284       if (TREE_SIDE_EFFECTS (op))
10285         TREE_OPERAND (expr, 0) = get_temp_regvar (TREE_TYPE (op), op);
10286       *walk_subtrees = 0;
10287     }
10288   else if (!EXPR_P (expr) || !TREE_SIDE_EFFECTS (expr))
10289     *walk_subtrees = 0;
10290   return NULL;
10291 }
10292
10293 /* Entry point for the above.  */
10294
10295 static void
10296 stabilize_vla_size (tree size)
10297 {
10298   hash_set<tree> pset;
10299   /* Break out any function calls into temporary variables.  */
10300   cp_walk_tree (&size, stabilize_save_expr_r, &pset, &pset);
10301 }
10302
10303 /* Reduce a SIZEOF_EXPR to its value.  */
10304
10305 tree
10306 fold_sizeof_expr (tree t)
10307 {
10308   tree r;
10309   if (SIZEOF_EXPR_TYPE_P (t))
10310     r = cxx_sizeof_or_alignof_type (EXPR_LOCATION (t),
10311                                     TREE_TYPE (TREE_OPERAND (t, 0)),
10312                                     SIZEOF_EXPR, false, false);
10313   else if (TYPE_P (TREE_OPERAND (t, 0)))
10314     r = cxx_sizeof_or_alignof_type (EXPR_LOCATION (t),
10315                                     TREE_OPERAND (t, 0), SIZEOF_EXPR,
10316                                     false, false);
10317   else
10318     r = cxx_sizeof_or_alignof_expr (EXPR_LOCATION (t),
10319                                     TREE_OPERAND (t, 0), SIZEOF_EXPR,
10320                                     false);
10321   if (r == error_mark_node)
10322     r = size_one_node;
10323   return r;
10324 }
10325
10326 /* Given the SIZE (i.e., number of elements) in an array, compute
10327    an appropriate index type for the array.  If non-NULL, NAME is
10328    the name of the entity being declared.  */
10329
10330 static tree
10331 compute_array_index_type_loc (location_t name_loc, tree name, tree size,
10332                               tsubst_flags_t complain)
10333 {
10334   if (error_operand_p (size))
10335     return error_mark_node;
10336
10337   /* The type of the index being computed.  */
10338   tree itype;
10339
10340   /* The original numeric size as seen in the source code before
10341      conversion to size_t.  */
10342   tree origsize = size;
10343
10344   location_t loc = cp_expr_loc_or_loc (size, name ? name_loc : input_location);
10345
10346   if (!type_dependent_expression_p (size))
10347     {
10348       origsize = size = mark_rvalue_use (size);
10349
10350       if (cxx_dialect < cxx11 && TREE_CODE (size) == NOP_EXPR
10351           && TREE_SIDE_EFFECTS (size))
10352         /* In C++98, we mark a non-constant array bound with a magic
10353            NOP_EXPR with TREE_SIDE_EFFECTS; don't fold in that case.  */;
10354       else
10355         {
10356           size = build_converted_constant_expr (size_type_node, size, complain);
10357           /* Pedantically a constant expression is required here and so
10358              __builtin_is_constant_evaluated () should fold to true if it
10359              is successfully folded into a constant.  */
10360           size = fold_non_dependent_expr (size, complain,
10361                                           /*manifestly_const_eval=*/true);
10362
10363           if (!TREE_CONSTANT (size))
10364             size = origsize;
10365         }
10366
10367       if (error_operand_p (size))
10368         return error_mark_node;
10369
10370       /* The array bound must be an integer type.  */
10371       tree type = TREE_TYPE (size);
10372       if (!INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
10373         {
10374           if (!(complain & tf_error))
10375             return error_mark_node;
10376           if (name)
10377             error_at (loc, "size of array %qD has non-integral type %qT",
10378                       name, type);
10379           else
10380             error_at (loc, "size of array has non-integral type %qT", type);
10381           size = integer_one_node;
10382         }
10383     }
10384
10385   /* A type is dependent if it is...an array type constructed from any
10386      dependent type or whose size is specified by a constant expression
10387      that is value-dependent.  */
10388   /* We can only call value_dependent_expression_p on integral constant
10389      expressions.  */
10390   if (processing_template_decl
10391       && potential_constant_expression (size)
10392       && value_dependent_expression_p (size))
10393     {
10394       /* Just build the index type and mark that it requires
10395          structural equality checks.  */
10396     in_template:
10397       itype = build_index_type (build_min (MINUS_EXPR, sizetype,
10398                                            size, size_one_node));
10399       TYPE_DEPENDENT_P (itype) = 1;
10400       TYPE_DEPENDENT_P_VALID (itype) = 1;
10401       SET_TYPE_STRUCTURAL_EQUALITY (itype);
10402       return itype;
10403     }
10404
10405   if (TREE_CODE (size) != INTEGER_CST)
10406     {
10407       tree folded = cp_fully_fold (size);
10408       if (TREE_CODE (folded) == INTEGER_CST)
10409         {
10410           if (name)
10411             pedwarn (loc, OPT_Wpedantic, "size of array %qD is not an "
10412                      "integral constant-expression", name);
10413           else
10414             pedwarn (loc, OPT_Wpedantic,
10415                      "size of array is not an integral constant-expression");
10416         }
10417       if (TREE_CONSTANT (size) && !TREE_CONSTANT (folded))
10418         /* We might have lost the TREE_CONSTANT flag e.g. when we are
10419            folding a conversion from a pointer to integral type.  In that
10420            case issue an error below and don't treat this as a VLA.  */;
10421       else
10422         /* Use the folded result for VLAs, too; it will have resolved
10423            SIZEOF_EXPR.  */
10424         size = folded;
10425     }
10426
10427   /* Normally, the array-bound will be a constant.  */
10428   if (TREE_CODE (size) == INTEGER_CST)
10429     {
10430       /* The size to use in diagnostics that reflects the constant
10431          size used in the source, rather than SIZE massaged above.  */
10432       tree diagsize = size;
10433
10434       /* If the original size before conversion to size_t was signed
10435          and negative, convert it to ssizetype to restore the sign.  */
10436       if (!TYPE_UNSIGNED (TREE_TYPE (origsize))
10437           && TREE_CODE (size) == INTEGER_CST
10438           && tree_int_cst_sign_bit (size))
10439         {
10440           diagsize = fold_convert (ssizetype, size);
10441
10442           /* Clear the overflow bit that may have been set as a result
10443              of the conversion from the sizetype of the new size to
10444              ssizetype.  */
10445           TREE_OVERFLOW (diagsize) = false;
10446         }
10447
10448       /* Verify that the array has a positive number of elements
10449          and issue the appropriate diagnostic if it doesn't.  */
10450       if (!valid_array_size_p (loc, diagsize, name, (complain & tf_error)))
10451         {
10452           if (!(complain & tf_error))
10453             return error_mark_node;
10454           size = integer_one_node;
10455         }
10456       /* As an extension we allow zero-sized arrays.  */
10457       else if (integer_zerop (size))
10458         {
10459           if (!(complain & tf_error))
10460             /* We must fail if performing argument deduction (as
10461                indicated by the state of complain), so that
10462                another substitution can be found.  */
10463             return error_mark_node;
10464           else if (name)
10465             pedwarn (loc, OPT_Wpedantic,
10466                      "ISO C++ forbids zero-size array %qD", name);
10467           else
10468             pedwarn (loc, OPT_Wpedantic,
10469                      "ISO C++ forbids zero-size array");
10470         }
10471     }
10472   else if (TREE_CONSTANT (size)
10473            /* We don't allow VLAs at non-function scopes, or during
10474               tentative template substitution.  */
10475            || !at_function_scope_p ()
10476            || !(complain & tf_error))
10477     {
10478       if (!(complain & tf_error))
10479         return error_mark_node;
10480       /* `(int) &fn' is not a valid array bound.  */
10481       if (name)
10482         error_at (loc,
10483                   "size of array %qD is not an integral constant-expression",
10484                   name);
10485       else
10486         error_at (loc, "size of array is not an integral constant-expression");
10487       size = integer_one_node;
10488     }
10489   else if (pedantic && warn_vla != 0)
10490     {
10491       if (name)
10492         pedwarn (name_loc, OPT_Wvla,
10493                  "ISO C++ forbids variable length array %qD", name);
10494       else
10495         pedwarn (input_location, OPT_Wvla,
10496                  "ISO C++ forbids variable length array");
10497     }
10498   else if (warn_vla > 0)
10499     {
10500       if (name)
10501         warning_at (name_loc, OPT_Wvla, 
10502                     "variable length array %qD is used", name);
10503       else
10504         warning (OPT_Wvla, 
10505                  "variable length array is used");
10506     }
10507
10508   if (processing_template_decl && !TREE_CONSTANT (size))
10509     goto in_template;
10510   else
10511     {
10512       if (!TREE_CONSTANT (size))
10513         {
10514           /* A variable sized array.  Arrange for the SAVE_EXPR on the inside
10515              of the MINUS_EXPR, which allows the -1 to get folded with the +1
10516              that happens when building TYPE_SIZE.  */
10517           size = variable_size (size);
10518           stabilize_vla_size (size);
10519         }
10520
10521       /* Compute the index of the largest element in the array.  It is
10522          one less than the number of elements in the array.  We save
10523          and restore PROCESSING_TEMPLATE_DECL so that computations in
10524          cp_build_binary_op will be appropriately folded.  */
10525       {
10526         processing_template_decl_sentinel s;
10527         itype = cp_build_binary_op (input_location,
10528                                     MINUS_EXPR,
10529                                     cp_convert (ssizetype, size, complain),
10530                                     cp_convert (ssizetype, integer_one_node,
10531                                                 complain),
10532                                     complain);
10533         itype = maybe_constant_value (itype);
10534       }
10535
10536       if (!TREE_CONSTANT (itype))
10537         {
10538           if (sanitize_flags_p (SANITIZE_VLA)
10539               && current_function_decl != NULL_TREE)
10540             {
10541               /* We have to add 1 -- in the ubsan routine we generate
10542                  LE_EXPR rather than LT_EXPR.  */
10543               tree t = fold_build2 (PLUS_EXPR, TREE_TYPE (itype), itype,
10544                                     build_one_cst (TREE_TYPE (itype)));
10545               t = ubsan_instrument_vla (input_location, t);
10546               finish_expr_stmt (t);
10547             }
10548         }
10549       /* Make sure that there was no overflow when creating to a signed
10550          index type.  (For example, on a 32-bit machine, an array with
10551          size 2^32 - 1 is too big.)  */
10552       else if (TREE_CODE (itype) == INTEGER_CST
10553                && TREE_OVERFLOW (itype))
10554         {
10555           if (!(complain & tf_error))
10556             return error_mark_node;
10557           error ("overflow in array dimension");
10558           TREE_OVERFLOW (itype) = 0;
10559         }
10560     }
10561
10562   /* Create and return the appropriate index type.  */
10563   itype = build_index_type (itype);
10564
10565   /* If the index type were dependent, we would have returned early, so
10566      remember that it isn't.  */
10567   TYPE_DEPENDENT_P (itype) = 0;
10568   TYPE_DEPENDENT_P_VALID (itype) = 1;
10569   return itype;
10570 }
10571
10572 tree
10573 compute_array_index_type (tree name, tree size, tsubst_flags_t complain)
10574 {
10575   return compute_array_index_type_loc (input_location, name, size, complain);
10576 }
10577
10578 /* Returns the scope (if any) in which the entity declared by
10579    DECLARATOR will be located.  If the entity was declared with an
10580    unqualified name, NULL_TREE is returned.  */
10581
10582 tree
10583 get_scope_of_declarator (const cp_declarator *declarator)
10584 {
10585   while (declarator && declarator->kind != cdk_id)
10586     declarator = declarator->declarator;
10587
10588   /* If the declarator-id is a SCOPE_REF, the scope in which the
10589      declaration occurs is the first operand.  */
10590   if (declarator
10591       && declarator->u.id.qualifying_scope)
10592     return declarator->u.id.qualifying_scope;
10593
10594   /* Otherwise, the declarator is not a qualified name; the entity will
10595      be declared in the current scope.  */
10596   return NULL_TREE;
10597 }
10598
10599 /* Returns an ARRAY_TYPE for an array with SIZE elements of the
10600    indicated TYPE.  If non-NULL, NAME is the NAME of the declaration
10601    with this type.  */
10602
10603 static tree
10604 create_array_type_for_decl (tree name, tree type, tree size, location_t loc)
10605 {
10606   tree itype = NULL_TREE;
10607
10608   /* If things have already gone awry, bail now.  */
10609   if (type == error_mark_node || size == error_mark_node)
10610     return error_mark_node;
10611
10612   /* 8.3.4/1: If the type of the identifier of D contains the auto
10613      type-specifier, the program is ill-formed.  */
10614   if (type_uses_auto (type))
10615     {
10616       if (name)
10617         error_at (loc, "%qD declared as array of %qT", name, type);
10618       else
10619         error ("creating array of %qT", type);
10620       return error_mark_node;
10621     }
10622
10623   /* If there are some types which cannot be array elements,
10624      issue an error-message and return.  */
10625   switch (TREE_CODE (type))
10626     {
10627     case VOID_TYPE:
10628       if (name)
10629         error_at (loc, "declaration of %qD as array of void", name);
10630       else
10631         error ("creating array of void");
10632       return error_mark_node;
10633
10634     case FUNCTION_TYPE:
10635       if (name)
10636         error_at (loc, "declaration of %qD as array of functions", name);
10637       else
10638         error ("creating array of functions");
10639       return error_mark_node;
10640
10641     case REFERENCE_TYPE:
10642       if (name)
10643         error_at (loc, "declaration of %qD as array of references", name);
10644       else
10645         error ("creating array of references");
10646       return error_mark_node;
10647
10648     case METHOD_TYPE:
10649       if (name)
10650         error_at (loc, "declaration of %qD as array of function members",
10651                   name);
10652       else
10653         error ("creating array of function members");
10654       return error_mark_node;
10655
10656     default:
10657       break;
10658     }
10659
10660   if (!verify_type_context (name ? loc : input_location,
10661                             TCTX_ARRAY_ELEMENT, type))
10662     return error_mark_node;
10663
10664   /* [dcl.array]
10665
10666      The constant expressions that specify the bounds of the arrays
10667      can be omitted only for the first member of the sequence.  */
10668   if (TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type))
10669     {
10670       if (name)
10671         error_at (loc, "declaration of %qD as multidimensional array must "
10672                   "have bounds for all dimensions except the first",
10673                   name);
10674       else
10675         error ("multidimensional array must have bounds for all "
10676                "dimensions except the first");
10677
10678       return error_mark_node;
10679     }
10680
10681   /* Figure out the index type for the array.  */
10682   if (size)
10683     itype = compute_array_index_type_loc (loc, name, size,
10684                                           tf_warning_or_error);
10685
10686   /* [dcl.array]
10687      T is called the array element type; this type shall not be [...] an
10688      abstract class type.  */
10689   abstract_virtuals_error (name, type);
10690
10691   return build_cplus_array_type (type, itype);
10692 }
10693
10694 /* Returns the smallest location that is not UNKNOWN_LOCATION.  */
10695
10696 static location_t
10697 min_location (location_t loca, location_t locb)
10698 {
10699   if (loca == UNKNOWN_LOCATION
10700       || (locb != UNKNOWN_LOCATION
10701           && linemap_location_before_p (line_table, locb, loca)))
10702     return locb;
10703   return loca;
10704 }
10705
10706 /* Returns the smallest location != UNKNOWN_LOCATION among the
10707    three stored in LOCATIONS[ds_const], LOCATIONS[ds_volatile],
10708    and LOCATIONS[ds_restrict].  */
10709
10710 static location_t
10711 smallest_type_quals_location (int type_quals, const location_t* locations)
10712 {
10713   location_t loc = UNKNOWN_LOCATION;
10714
10715   if (type_quals & TYPE_QUAL_CONST)
10716     loc = locations[ds_const];
10717
10718   if (type_quals & TYPE_QUAL_VOLATILE)
10719     loc = min_location (loc, locations[ds_volatile]);
10720
10721   if (type_quals & TYPE_QUAL_RESTRICT)
10722     loc = min_location (loc, locations[ds_restrict]);
10723
10724   return loc;
10725 }
10726
10727 /* Returns the smallest among the latter and locations[ds_type_spec].  */
10728
10729 static location_t
10730 smallest_type_location (int type_quals, const location_t* locations)
10731 {
10732   location_t loc = smallest_type_quals_location (type_quals, locations);
10733   return min_location (loc, locations[ds_type_spec]);
10734 }
10735
10736 static location_t
10737 smallest_type_location (const cp_decl_specifier_seq *declspecs)
10738 {
10739   int type_quals = get_type_quals (declspecs);
10740   return smallest_type_location (type_quals, declspecs->locations);
10741 }
10742
10743 /* Check that it's OK to declare a function with the indicated TYPE
10744    and TYPE_QUALS.  SFK indicates the kind of special function (if any)
10745    that this function is.  OPTYPE is the type given in a conversion
10746    operator declaration, or the class type for a constructor/destructor.
10747    Returns the actual return type of the function; that may be different
10748    than TYPE if an error occurs, or for certain special functions.  */
10749
10750 static tree
10751 check_special_function_return_type (special_function_kind sfk,
10752                                     tree type,
10753                                     tree optype,
10754                                     int type_quals,
10755                                     const location_t* locations)
10756 {
10757   switch (sfk)
10758     {
10759     case sfk_constructor:
10760       if (type)
10761         error_at (smallest_type_location (type_quals, locations),
10762                   "return type specification for constructor invalid");
10763       else if (type_quals != TYPE_UNQUALIFIED)
10764         error_at (smallest_type_quals_location (type_quals, locations),
10765                   "qualifiers are not allowed on constructor declaration");
10766
10767       if (targetm.cxx.cdtor_returns_this ())
10768         type = build_pointer_type (optype);
10769       else
10770         type = void_type_node;
10771       break;
10772
10773     case sfk_destructor:
10774       if (type)
10775         error_at (smallest_type_location (type_quals, locations),
10776                   "return type specification for destructor invalid");
10777       else if (type_quals != TYPE_UNQUALIFIED)
10778         error_at (smallest_type_quals_location (type_quals, locations),
10779                   "qualifiers are not allowed on destructor declaration");
10780
10781       /* We can't use the proper return type here because we run into
10782          problems with ambiguous bases and covariant returns.  */
10783       if (targetm.cxx.cdtor_returns_this ())
10784         type = build_pointer_type (void_type_node);
10785       else
10786         type = void_type_node;
10787       break;
10788
10789     case sfk_conversion:
10790       if (type)
10791         error_at (smallest_type_location (type_quals, locations),
10792                   "return type specified for %<operator %T%>", optype);
10793       else if (type_quals != TYPE_UNQUALIFIED)
10794         error_at (smallest_type_quals_location (type_quals, locations),
10795                   "qualifiers are not allowed on declaration of "
10796                   "%<operator %T%>", optype);
10797
10798       type = optype;
10799       break;
10800
10801     case sfk_deduction_guide:
10802       if (type)
10803         error_at (smallest_type_location (type_quals, locations),
10804                   "return type specified for deduction guide");
10805       else if (type_quals != TYPE_UNQUALIFIED)
10806         error_at (smallest_type_quals_location (type_quals, locations),
10807                   "qualifiers are not allowed on declaration of "
10808                   "deduction guide");
10809       if (TREE_CODE (optype) == TEMPLATE_TEMPLATE_PARM)
10810         {
10811           error ("template template parameter %qT in declaration of "
10812                  "deduction guide", optype);
10813           type = error_mark_node;
10814         }
10815       else
10816         type = make_template_placeholder (CLASSTYPE_TI_TEMPLATE (optype));
10817       for (int i = 0; i < ds_last; ++i)
10818         if (i != ds_explicit && locations[i])
10819           error_at (locations[i],
10820                     "%<decl-specifier%> in declaration of deduction guide");
10821       break;
10822
10823     default:
10824       gcc_unreachable ();
10825     }
10826
10827   return type;
10828 }
10829
10830 /* A variable or data member (whose unqualified name is IDENTIFIER)
10831    has been declared with the indicated TYPE.  If the TYPE is not
10832    acceptable, issue an error message and return a type to use for
10833    error-recovery purposes.  */
10834
10835 tree
10836 check_var_type (tree identifier, tree type, location_t loc)
10837 {
10838   if (VOID_TYPE_P (type))
10839     {
10840       if (!identifier)
10841         error_at (loc, "unnamed variable or field declared void");
10842       else if (identifier_p (identifier))
10843         {
10844           gcc_assert (!IDENTIFIER_ANY_OP_P (identifier));
10845           error_at (loc, "variable or field %qE declared void",
10846                     identifier);
10847         }
10848       else
10849         error_at (loc, "variable or field declared void");
10850       type = error_mark_node;
10851     }
10852
10853   return type;
10854 }
10855
10856 /* Handle declaring DECL as an inline variable.  */
10857
10858 static void
10859 mark_inline_variable (tree decl, location_t loc)
10860 {
10861   bool inlinep = true;
10862   if (! toplevel_bindings_p ())
10863     {
10864       error_at (loc, "%<inline%> specifier invalid for variable "
10865                 "%qD declared at block scope", decl);
10866       inlinep = false;
10867     }
10868   else if (cxx_dialect < cxx17)
10869     pedwarn (loc, 0, "inline variables are only available "
10870              "with %<-std=c++17%> or %<-std=gnu++17%>");
10871   if (inlinep)
10872     {
10873       retrofit_lang_decl (decl);
10874       SET_DECL_VAR_DECLARED_INLINE_P (decl);
10875     }
10876 }
10877
10878
10879 /* Assign a typedef-given name to a class or enumeration type declared
10880    as anonymous at first.  This was split out of grokdeclarator
10881    because it is also used in libcc1.  */
10882
10883 void
10884 name_unnamed_type (tree type, tree decl)
10885 {
10886   gcc_assert (TYPE_UNNAMED_P (type));
10887
10888   /* Replace the anonymous name with the real name everywhere.  */
10889   for (tree t = TYPE_MAIN_VARIANT (type); t; t = TYPE_NEXT_VARIANT (t))
10890     if (IDENTIFIER_ANON_P (TYPE_IDENTIFIER (t)))
10891       /* We do not rename the debug info representing the unnamed
10892          tagged type because the standard says in [dcl.typedef] that
10893          the naming applies only for linkage purposes.  */
10894       /*debug_hooks->set_name (t, decl);*/
10895       TYPE_NAME (t) = decl;
10896
10897   /* If this is a typedef within a template class, the nested
10898      type is a (non-primary) template.  The name for the
10899      template needs updating as well.  */
10900   if (TYPE_LANG_SPECIFIC (type) && CLASSTYPE_TEMPLATE_INFO (type))
10901     DECL_NAME (CLASSTYPE_TI_TEMPLATE (type))
10902       = TYPE_IDENTIFIER (type);
10903
10904   /* Adjust linkage now that we aren't unnamed anymore.  */
10905   reset_type_linkage (type);
10906
10907   /* FIXME remangle member functions; member functions of a
10908      type with external linkage have external linkage.  */
10909
10910   /* Check that our job is done, and that it would fail if we
10911      attempted to do it again.  */
10912   gcc_assert (!TYPE_UNNAMED_P (type));
10913 }
10914
10915 /* Given declspecs and a declarator (abstract or otherwise), determine
10916    the name and type of the object declared and construct a DECL node
10917    for it.
10918
10919    DECLSPECS points to the representation of declaration-specifier
10920    sequence that precedes declarator.
10921
10922    DECL_CONTEXT says which syntactic context this declaration is in:
10923      NORMAL for most contexts.  Make a VAR_DECL or FUNCTION_DECL or TYPE_DECL.
10924      FUNCDEF for a function definition.  Like NORMAL but a few different
10925       error messages in each case.  Return value may be zero meaning
10926       this definition is too screwy to try to parse.
10927      MEMFUNCDEF for a function definition.  Like FUNCDEF but prepares to
10928       handle member functions (which have FIELD context).
10929       Return value may be zero meaning this definition is too screwy to
10930       try to parse.
10931      PARM for a parameter declaration (either within a function prototype
10932       or before a function body).  Make a PARM_DECL, or return void_type_node.
10933      TPARM for a template parameter declaration.
10934      CATCHPARM for a parameter declaration before a catch clause.
10935      TYPENAME if for a typename (in a cast or sizeof).
10936       Don't make a DECL node; just return the ..._TYPE node.
10937      FIELD for a struct or union field; make a FIELD_DECL.
10938      BITFIELD for a field with specified width.
10939
10940    INITIALIZED is as for start_decl.
10941
10942    ATTRLIST is a pointer to the list of attributes, which may be NULL
10943    if there are none; *ATTRLIST may be modified if attributes from inside
10944    the declarator should be applied to the declaration.
10945
10946    When this function is called, scoping variables (such as
10947    CURRENT_CLASS_TYPE) should reflect the scope in which the
10948    declaration occurs, not the scope in which the new declaration will
10949    be placed.  For example, on:
10950
10951      void S::f() { ... }
10952
10953    when grokdeclarator is called for `S::f', the CURRENT_CLASS_TYPE
10954    should not be `S'.
10955
10956    Returns a DECL (if a declarator is present), a TYPE (if there is no
10957    declarator, in cases like "struct S;"), or the ERROR_MARK_NODE if an
10958    error occurs. */
10959
10960 tree
10961 grokdeclarator (const cp_declarator *declarator,
10962                 cp_decl_specifier_seq *declspecs,
10963                 enum decl_context decl_context,
10964                 int initialized,
10965                 tree* attrlist)
10966 {
10967   tree type = NULL_TREE;
10968   int longlong = 0;
10969   int explicit_intN = 0;
10970   int int_n_alt = 0;
10971   int virtualp, explicitp, friendp, inlinep, staticp;
10972   int explicit_int = 0;
10973   int explicit_char = 0;
10974   int defaulted_int = 0;
10975
10976   tree typedef_decl = NULL_TREE;
10977   const char *name = NULL;
10978   tree typedef_type = NULL_TREE;
10979   /* True if this declarator is a function definition.  */
10980   bool funcdef_flag = false;
10981   cp_declarator_kind innermost_code = cdk_error;
10982   int bitfield = 0;
10983 #if 0
10984   /* See the code below that used this.  */
10985   tree decl_attr = NULL_TREE;
10986 #endif
10987
10988   /* Keep track of what sort of function is being processed
10989      so that we can warn about default return values, or explicit
10990      return values which do not match prescribed defaults.  */
10991   special_function_kind sfk = sfk_none;
10992
10993   tree dname = NULL_TREE;
10994   tree ctor_return_type = NULL_TREE;
10995   enum overload_flags flags = NO_SPECIAL;
10996   /* cv-qualifiers that apply to the declarator, for a declaration of
10997      a member function.  */
10998   cp_cv_quals memfn_quals = TYPE_UNQUALIFIED;
10999   /* virt-specifiers that apply to the declarator, for a declaration of
11000      a member function.  */
11001   cp_virt_specifiers virt_specifiers = VIRT_SPEC_UNSPECIFIED;
11002   /* ref-qualifier that applies to the declarator, for a declaration of
11003      a member function.  */
11004   cp_ref_qualifier rqual = REF_QUAL_NONE;
11005   /* cv-qualifiers that apply to the type specified by the DECLSPECS.  */
11006   int type_quals = get_type_quals (declspecs);
11007   tree raises = NULL_TREE;
11008   int template_count = 0;
11009   tree returned_attrs = NULL_TREE;
11010   tree parms = NULL_TREE;
11011   const cp_declarator *id_declarator;
11012   /* The unqualified name of the declarator; either an
11013      IDENTIFIER_NODE, BIT_NOT_EXPR, or TEMPLATE_ID_EXPR.  */
11014   tree unqualified_id;
11015   /* The class type, if any, in which this entity is located,
11016      or NULL_TREE if none.  Note that this value may be different from
11017      the current class type; for example if an attempt is made to declare
11018      "A::f" inside "B", this value will be "A".  */
11019   tree ctype = current_class_type;
11020   /* The NAMESPACE_DECL for the namespace in which this entity is
11021      located.  If an unqualified name is used to declare the entity,
11022      this value will be NULL_TREE, even if the entity is located at
11023      namespace scope.  */
11024   tree in_namespace = NULL_TREE;
11025   cp_storage_class storage_class;
11026   bool unsigned_p, signed_p, short_p, long_p, thread_p;
11027   bool type_was_error_mark_node = false;
11028   bool parameter_pack_p = declarator ? declarator->parameter_pack_p : false;
11029   bool template_type_arg = false;
11030   bool template_parm_flag = false;
11031   bool typedef_p = decl_spec_seq_has_spec_p (declspecs, ds_typedef);
11032   bool constexpr_p = decl_spec_seq_has_spec_p (declspecs, ds_constexpr);
11033   bool constinit_p = decl_spec_seq_has_spec_p (declspecs, ds_constinit);
11034   bool consteval_p = decl_spec_seq_has_spec_p (declspecs, ds_consteval);
11035   bool late_return_type_p = false;
11036   bool array_parameter_p = false;
11037   tree reqs = NULL_TREE;
11038
11039   signed_p = decl_spec_seq_has_spec_p (declspecs, ds_signed);
11040   unsigned_p = decl_spec_seq_has_spec_p (declspecs, ds_unsigned);
11041   short_p = decl_spec_seq_has_spec_p (declspecs, ds_short);
11042   long_p = decl_spec_seq_has_spec_p (declspecs, ds_long);
11043   longlong = decl_spec_seq_has_spec_p (declspecs, ds_long_long);
11044   explicit_intN = declspecs->explicit_intN_p;
11045   int_n_alt = declspecs->int_n_alt;
11046   thread_p = decl_spec_seq_has_spec_p (declspecs, ds_thread);
11047
11048   // Was concept_p specified? Note that ds_concept
11049   // implies ds_constexpr!
11050   bool concept_p = decl_spec_seq_has_spec_p (declspecs, ds_concept);
11051   if (concept_p)
11052     constexpr_p = true;
11053
11054   if (decl_context == FUNCDEF)
11055     funcdef_flag = true, decl_context = NORMAL;
11056   else if (decl_context == MEMFUNCDEF)
11057     funcdef_flag = true, decl_context = FIELD;
11058   else if (decl_context == BITFIELD)
11059     bitfield = 1, decl_context = FIELD;
11060   else if (decl_context == TEMPLATE_TYPE_ARG)
11061     template_type_arg = true, decl_context = TYPENAME;
11062   else if (decl_context == TPARM)
11063     template_parm_flag = true, decl_context = PARM;
11064
11065   if (initialized == SD_DEFAULTED || initialized == SD_DELETED)
11066     funcdef_flag = true;
11067
11068   location_t typespec_loc = smallest_type_location (type_quals,
11069                                                     declspecs->locations);
11070   if (typespec_loc == UNKNOWN_LOCATION)
11071     typespec_loc = input_location;
11072
11073   location_t id_loc = declarator ? declarator->id_loc : input_location;
11074   if (id_loc == UNKNOWN_LOCATION)
11075     id_loc = input_location;
11076
11077   /* Look inside a declarator for the name being declared
11078      and get it as a string, for an error message.  */
11079   for (id_declarator = declarator;
11080        id_declarator;
11081        id_declarator = id_declarator->declarator)
11082     {
11083       if (id_declarator->kind != cdk_id)
11084         innermost_code = id_declarator->kind;
11085
11086       switch (id_declarator->kind)
11087         {
11088         case cdk_function:
11089           if (id_declarator->declarator
11090               && id_declarator->declarator->kind == cdk_id)
11091             {
11092               sfk = id_declarator->declarator->u.id.sfk;
11093               if (sfk == sfk_destructor)
11094                 flags = DTOR_FLAG;
11095             }
11096           break;
11097
11098         case cdk_id:
11099           {
11100             tree qualifying_scope = id_declarator->u.id.qualifying_scope;
11101             tree decl = id_declarator->u.id.unqualified_name;
11102             if (!decl)
11103               break;
11104             if (qualifying_scope)
11105               {
11106                 if (check_for_bare_parameter_packs (qualifying_scope,
11107                                                     id_declarator->id_loc))
11108                   return error_mark_node;
11109                 if (at_function_scope_p ())
11110                   {
11111                     /* [dcl.meaning] 
11112
11113                        A declarator-id shall not be qualified except
11114                        for ... 
11115
11116                        None of the cases are permitted in block
11117                        scope.  */
11118                     if (qualifying_scope == global_namespace)
11119                       error ("invalid use of qualified-name %<::%D%>",
11120                              decl);
11121                     else if (TYPE_P (qualifying_scope))
11122                       error ("invalid use of qualified-name %<%T::%D%>",
11123                              qualifying_scope, decl);
11124                     else 
11125                       error ("invalid use of qualified-name %<%D::%D%>",
11126                              qualifying_scope, decl);
11127                     return error_mark_node;
11128                   }
11129                 else if (TYPE_P (qualifying_scope))
11130                   {
11131                     ctype = qualifying_scope;
11132                     if (!MAYBE_CLASS_TYPE_P (ctype))
11133                       {
11134                         error_at (id_declarator->id_loc,
11135                                   "%q#T is not a class or namespace", ctype);
11136                         ctype = NULL_TREE;
11137                       }
11138                     else if (innermost_code != cdk_function
11139                              && current_class_type
11140                              && !uniquely_derived_from_p (ctype,
11141                                                           current_class_type))
11142                       {
11143                         error_at (id_declarator->id_loc,
11144                                   "invalid use of qualified-name %<%T::%D%>",
11145                                   qualifying_scope, decl);
11146                         return error_mark_node;
11147                       }
11148                   }
11149                 else if (TREE_CODE (qualifying_scope) == NAMESPACE_DECL)
11150                   in_namespace = qualifying_scope;
11151               }
11152             switch (TREE_CODE (decl))
11153               {
11154               case BIT_NOT_EXPR:
11155                 {
11156                   if (innermost_code != cdk_function)
11157                     {
11158                       error_at (EXPR_LOCATION (decl),
11159                                 "declaration of %qE as non-function", decl);
11160                       return error_mark_node;
11161                     }
11162                   else if (!qualifying_scope
11163                            && !(current_class_type && at_class_scope_p ()))
11164                     {
11165                       error_at (EXPR_LOCATION (decl),
11166                                 "declaration of %qE as non-member", decl);
11167                       return error_mark_node;
11168                     }
11169
11170                   tree type = TREE_OPERAND (decl, 0);
11171                   if (TYPE_P (type))
11172                     type = constructor_name (type);
11173                   name = identifier_to_locale (IDENTIFIER_POINTER (type));
11174                   dname = decl;
11175                 }
11176                 break;
11177
11178               case TEMPLATE_ID_EXPR:
11179                 {
11180                   tree fns = TREE_OPERAND (decl, 0);
11181
11182                   dname = fns;
11183                   if (!identifier_p (dname))
11184                     dname = OVL_NAME (dname);
11185                 }
11186                 /* Fall through.  */
11187
11188               case IDENTIFIER_NODE:
11189                 if (identifier_p (decl))
11190                   dname = decl;
11191
11192                 if (IDENTIFIER_KEYWORD_P (dname))
11193                   {
11194                     error ("declarator-id missing; using reserved word %qD",
11195                            dname);
11196                     name = identifier_to_locale (IDENTIFIER_POINTER (dname));
11197                   }
11198                 else if (!IDENTIFIER_CONV_OP_P (dname))
11199                   name = identifier_to_locale (IDENTIFIER_POINTER (dname));
11200                 else
11201                   {
11202                     gcc_assert (flags == NO_SPECIAL);
11203                     flags = TYPENAME_FLAG;
11204                     sfk = sfk_conversion;
11205                     tree glob = get_global_binding (dname);
11206                     if (glob && TREE_CODE (glob) == TYPE_DECL)
11207                       name = identifier_to_locale (IDENTIFIER_POINTER (dname));
11208                     else
11209                       name = "<invalid operator>";
11210                   }
11211                 break;
11212
11213               default:
11214                 gcc_unreachable ();
11215               }
11216             break;
11217           }
11218
11219         case cdk_array:
11220         case cdk_pointer:
11221         case cdk_reference:
11222         case cdk_ptrmem:
11223           break;
11224
11225         case cdk_decomp:
11226           name = "structured binding";
11227           break;
11228
11229         case cdk_error:
11230           return error_mark_node;
11231
11232         default:
11233           gcc_unreachable ();
11234         }
11235       if (id_declarator->kind == cdk_id)
11236         break;
11237     }
11238
11239   /* [dcl.fct.edf]
11240
11241      The declarator in a function-definition shall have the form
11242      D1 ( parameter-declaration-clause) ...  */
11243   if (funcdef_flag && innermost_code != cdk_function)
11244     {
11245       error_at (id_loc, "function definition does not declare parameters");
11246       return error_mark_node;
11247     }
11248
11249   if (flags == TYPENAME_FLAG
11250       && innermost_code != cdk_function
11251       && ! (ctype && !declspecs->any_specifiers_p))
11252     {
11253       error_at (id_loc, "declaration of %qD as non-function", dname);
11254       return error_mark_node;
11255     }
11256
11257   if (dname && identifier_p (dname))
11258     {
11259       if (UDLIT_OPER_P (dname)
11260           && innermost_code != cdk_function)
11261         {
11262           error_at (id_loc, "declaration of %qD as non-function", dname);
11263           return error_mark_node;
11264         }
11265
11266       if (IDENTIFIER_ANY_OP_P (dname))
11267         {
11268           if (typedef_p)
11269             {
11270               error_at (id_loc, "declaration of %qD as %<typedef%>", dname);
11271               return error_mark_node;
11272             }
11273           else if (decl_context == PARM || decl_context == CATCHPARM)
11274             {
11275               error_at (id_loc, "declaration of %qD as parameter", dname);
11276               return error_mark_node;
11277             }
11278         }
11279     }
11280
11281   /* Anything declared one level down from the top level
11282      must be one of the parameters of a function
11283      (because the body is at least two levels down).  */
11284
11285   /* This heuristic cannot be applied to C++ nodes! Fixed, however,
11286      by not allowing C++ class definitions to specify their parameters
11287      with xdecls (must be spec.d in the parmlist).
11288
11289      Since we now wait to push a class scope until we are sure that
11290      we are in a legitimate method context, we must set oldcname
11291      explicitly (since current_class_name is not yet alive).
11292
11293      We also want to avoid calling this a PARM if it is in a namespace.  */
11294
11295   if (decl_context == NORMAL && !toplevel_bindings_p ())
11296     {
11297       cp_binding_level *b = current_binding_level;
11298       current_binding_level = b->level_chain;
11299       if (current_binding_level != 0 && toplevel_bindings_p ())
11300         decl_context = PARM;
11301       current_binding_level = b;
11302     }
11303
11304   if (name == NULL)
11305     name = decl_context == PARM ? "parameter" : "type name";
11306
11307   if (consteval_p && constexpr_p)
11308     {
11309       error_at (declspecs->locations[ds_consteval],
11310                 "both %qs and %qs specified", "constexpr", "consteval");
11311       return error_mark_node;
11312     }
11313
11314   if (concept_p && typedef_p)
11315     {
11316       error_at (declspecs->locations[ds_concept],
11317                 "%qs cannot appear in a typedef declaration", "concept");
11318       return error_mark_node;
11319     }
11320
11321   if (constexpr_p && typedef_p)
11322     {
11323       error_at (declspecs->locations[ds_constexpr],
11324                 "%qs cannot appear in a typedef declaration", "constexpr");
11325       return error_mark_node;
11326     }
11327
11328   if (consteval_p && typedef_p)
11329     {
11330       error_at (declspecs->locations[ds_consteval],
11331                 "%qs cannot appear in a typedef declaration", "consteval");
11332       return error_mark_node;
11333     }
11334
11335   if (constinit_p && typedef_p)
11336     {
11337       error_at (declspecs->locations[ds_constinit],
11338                 "%qs cannot appear in a typedef declaration", "constinit");
11339       return error_mark_node;
11340     }
11341
11342   /* [dcl.spec]/2 "At most one of the constexpr, consteval, and constinit
11343      keywords shall appear in a decl-specifier-seq."  */
11344   if (constinit_p && constexpr_p)
11345     {
11346       gcc_rich_location richloc (declspecs->locations[ds_constinit]);
11347       richloc.add_range (declspecs->locations[ds_constexpr]);
11348       error_at (&richloc,
11349                 "can use at most one of the %<constinit%> and %<constexpr%> "
11350                 "specifiers");
11351       return error_mark_node;
11352     }
11353
11354   /* If there were multiple types specified in the decl-specifier-seq,
11355      issue an error message.  */
11356   if (declspecs->multiple_types_p)
11357     {
11358       error_at (typespec_loc,
11359                 "two or more data types in declaration of %qs", name);
11360       return error_mark_node;
11361     }
11362
11363   if (declspecs->conflicting_specifiers_p)
11364     {
11365       error_at (min_location (declspecs->locations[ds_typedef],
11366                               declspecs->locations[ds_storage_class]),
11367                 "conflicting specifiers in declaration of %qs", name);
11368       return error_mark_node;
11369     }
11370
11371   /* Extract the basic type from the decl-specifier-seq.  */
11372   type = declspecs->type;
11373   if (type == error_mark_node)
11374     {
11375       type = NULL_TREE;
11376       type_was_error_mark_node = true;
11377     }
11378
11379   /* Ignore erroneous attributes.  */
11380   if (attrlist && *attrlist == error_mark_node)
11381     *attrlist = NULL_TREE;
11382
11383   /* An object declared as __attribute__((deprecated)) suppresses
11384      warnings of uses of other deprecated items.  */
11385   temp_override<deprecated_states> ds (deprecated_state);
11386   if (attrlist && lookup_attribute ("deprecated", *attrlist))
11387     deprecated_state = DEPRECATED_SUPPRESS;
11388
11389   cp_warn_deprecated_use (type);
11390   if (type && TREE_CODE (type) == TYPE_DECL)
11391     {
11392       cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (type));
11393       typedef_decl = type;
11394       type = TREE_TYPE (typedef_decl);
11395       if (DECL_ARTIFICIAL (typedef_decl))
11396         cp_warn_deprecated_use (type);
11397     }
11398   /* No type at all: default to `int', and set DEFAULTED_INT
11399      because it was not a user-defined typedef.  */
11400   if (type == NULL_TREE)
11401     {
11402       if (signed_p || unsigned_p || long_p || short_p)
11403         {
11404           /* These imply 'int'.  */
11405           type = integer_type_node;
11406           defaulted_int = 1;
11407         }
11408       /* If we just have "complex", it is equivalent to "complex double".  */
11409       else if (!longlong && !explicit_intN
11410                && decl_spec_seq_has_spec_p (declspecs, ds_complex))
11411         {
11412           type = double_type_node;
11413           pedwarn (declspecs->locations[ds_complex], OPT_Wpedantic,
11414                    "ISO C++ does not support plain %<complex%> meaning "
11415                    "%<double complex%>");
11416         }
11417     }
11418   /* Gather flags.  */
11419   explicit_int = declspecs->explicit_int_p;
11420   explicit_char = declspecs->explicit_char_p;
11421
11422 #if 0
11423   /* See the code below that used this.  */
11424   if (typedef_decl)
11425     decl_attr = DECL_ATTRIBUTES (typedef_decl);
11426 #endif
11427   typedef_type = type;
11428
11429   if (sfk == sfk_conversion || sfk == sfk_deduction_guide)
11430     ctor_return_type = TREE_TYPE (dname);
11431   else
11432     ctor_return_type = ctype;
11433
11434   if (sfk != sfk_none)
11435     {
11436       type = check_special_function_return_type (sfk, type,
11437                                                  ctor_return_type,
11438                                                  type_quals,
11439                                                  declspecs->locations);
11440       type_quals = TYPE_UNQUALIFIED;
11441     }
11442   else if (type == NULL_TREE)
11443     {
11444       int is_main;
11445
11446       explicit_int = -1;
11447
11448       /* We handle `main' specially here, because 'main () { }' is so
11449          common.  With no options, it is allowed.  With -Wreturn-type,
11450          it is a warning.  It is only an error with -pedantic-errors.  */
11451       is_main = (funcdef_flag
11452                  && dname && identifier_p (dname)
11453                  && MAIN_NAME_P (dname)
11454                  && ctype == NULL_TREE
11455                  && in_namespace == NULL_TREE
11456                  && current_namespace == global_namespace);
11457
11458       if (type_was_error_mark_node)
11459         /* We've already issued an error, don't complain more.  */;
11460       else if (in_system_header_at (id_loc) || flag_ms_extensions)
11461         /* Allow it, sigh.  */;
11462       else if (! is_main)
11463         permerror (id_loc, "ISO C++ forbids declaration of %qs with no type",
11464                    name);
11465       else if (pedantic)
11466         pedwarn (id_loc, OPT_Wpedantic,
11467                  "ISO C++ forbids declaration of %qs with no type", name);
11468       else
11469         warning_at (id_loc, OPT_Wreturn_type,
11470                     "ISO C++ forbids declaration of %qs with no type", name);
11471
11472       if (type_was_error_mark_node && template_parm_flag)
11473         /* FIXME we should be able to propagate the error_mark_node as is
11474            for other contexts too.  */
11475         type = error_mark_node;
11476       else
11477         type = integer_type_node;
11478     }
11479
11480   ctype = NULL_TREE;
11481
11482   if (explicit_intN)
11483     {
11484       if (! int_n_enabled_p[declspecs->int_n_idx])
11485         {
11486           error_at (declspecs->locations[ds_type_spec],
11487                     "%<__int%d%> is not supported by this target",
11488                     int_n_data[declspecs->int_n_idx].bitsize);
11489           explicit_intN = false;
11490         }
11491       /* Don't pedwarn if the alternate "__intN__" form has been used instead
11492          of "__intN".  */
11493       else if (!int_n_alt && pedantic)
11494         pedwarn (declspecs->locations[ds_type_spec], OPT_Wpedantic,
11495                  "ISO C++ does not support %<__int%d%> for %qs",
11496                  int_n_data[declspecs->int_n_idx].bitsize, name);
11497     }
11498
11499   /* Now process the modifiers that were specified
11500      and check for invalid combinations.  */
11501
11502   /* Long double is a special combination.  */
11503   if (long_p && !longlong && TYPE_MAIN_VARIANT (type) == double_type_node)
11504     {
11505       long_p = false;
11506       type = cp_build_qualified_type (long_double_type_node,
11507                                       cp_type_quals (type));
11508     }
11509
11510   /* Check all other uses of type modifiers.  */
11511
11512   if (unsigned_p || signed_p || long_p || short_p)
11513     {
11514       location_t loc;
11515       const char *key;
11516       if (unsigned_p)
11517         {
11518           key = "unsigned";
11519           loc = declspecs->locations[ds_unsigned];
11520         }
11521       else if (signed_p)
11522         {
11523           key = "signed";
11524           loc = declspecs->locations[ds_signed];
11525         }
11526       else if (longlong)
11527         {
11528           key = "long long";
11529           loc = declspecs->locations[ds_long_long];
11530         }
11531       else if (long_p)
11532         {
11533           key = "long";
11534           loc = declspecs->locations[ds_long];
11535         }
11536       else /* if (short_p) */
11537         {
11538           key = "short";
11539           loc = declspecs->locations[ds_short];
11540         }
11541
11542       int ok = 0;
11543
11544       if (signed_p && unsigned_p)
11545         {
11546           gcc_rich_location richloc (declspecs->locations[ds_signed]);
11547           richloc.add_range (declspecs->locations[ds_unsigned]);
11548           error_at (&richloc,
11549                     "%<signed%> and %<unsigned%> specified together");
11550         }
11551       else if (long_p && short_p)
11552         {
11553           gcc_rich_location richloc (declspecs->locations[ds_long]);
11554           richloc.add_range (declspecs->locations[ds_short]);
11555           error_at (&richloc, "%<long%> and %<short%> specified together");
11556         }
11557       else if (TREE_CODE (type) != INTEGER_TYPE
11558                || type == char8_type_node
11559                || type == char16_type_node
11560                || type == char32_type_node
11561                || ((long_p || short_p)
11562                    && (explicit_char || explicit_intN)))
11563         error_at (loc, "%qs specified with %qT", key, type);
11564       else if (!explicit_int && !defaulted_int
11565                && !explicit_char && !explicit_intN)
11566         {
11567           if (typedef_decl)
11568             {
11569               pedwarn (loc, OPT_Wpedantic, "%qs specified with %qT",
11570                        key, type);
11571               ok = !flag_pedantic_errors;
11572             }
11573           else if (declspecs->decltype_p)
11574             error_at (loc, "%qs specified with %<decltype%>", key);
11575           else
11576             error_at (loc, "%qs specified with %<typeof%>", key);
11577         }
11578       else
11579         ok = 1;
11580
11581       /* Discard the type modifiers if they are invalid.  */
11582       if (! ok)
11583         {
11584           unsigned_p = false;
11585           signed_p = false;
11586           long_p = false;
11587           short_p = false;
11588           longlong = 0;
11589         }
11590     }
11591
11592   /* Decide whether an integer type is signed or not.
11593      Optionally treat bitfields as signed by default.  */
11594   if (unsigned_p
11595       /* [class.bit]
11596
11597          It is implementation-defined whether a plain (neither
11598          explicitly signed or unsigned) char, short, int, or long
11599          bit-field is signed or unsigned.
11600
11601          Naturally, we extend this to long long as well.  Note that
11602          this does not include wchar_t.  */
11603       || (bitfield && !flag_signed_bitfields
11604           && !signed_p
11605           /* A typedef for plain `int' without `signed' can be
11606              controlled just like plain `int', but a typedef for
11607              `signed int' cannot be so controlled.  */
11608           && !(typedef_decl
11609                && C_TYPEDEF_EXPLICITLY_SIGNED (typedef_decl))
11610           && TREE_CODE (type) == INTEGER_TYPE
11611           && !same_type_p (TYPE_MAIN_VARIANT (type), wchar_type_node)))
11612     {
11613       if (explicit_intN)
11614         type = int_n_trees[declspecs->int_n_idx].unsigned_type;
11615       else if (longlong)
11616         type = long_long_unsigned_type_node;
11617       else if (long_p)
11618         type = long_unsigned_type_node;
11619       else if (short_p)
11620         type = short_unsigned_type_node;
11621       else if (type == char_type_node)
11622         type = unsigned_char_type_node;
11623       else if (typedef_decl)
11624         type = unsigned_type_for (type);
11625       else
11626         type = unsigned_type_node;
11627     }
11628   else if (signed_p && type == char_type_node)
11629     type = signed_char_type_node;
11630   else if (explicit_intN)
11631     type = int_n_trees[declspecs->int_n_idx].signed_type;
11632   else if (longlong)
11633     type = long_long_integer_type_node;
11634   else if (long_p)
11635     type = long_integer_type_node;
11636   else if (short_p)
11637     type = short_integer_type_node;
11638
11639   if (decl_spec_seq_has_spec_p (declspecs, ds_complex))
11640     {
11641       if (TREE_CODE (type) != INTEGER_TYPE && TREE_CODE (type) != REAL_TYPE)
11642         error_at (declspecs->locations[ds_complex],
11643                   "complex invalid for %qs", name);
11644       /* If a modifier is specified, the resulting complex is the complex
11645          form of TYPE.  E.g, "complex short" is "complex short int".  */
11646       else if (type == integer_type_node)
11647         type = complex_integer_type_node;
11648       else if (type == float_type_node)
11649         type = complex_float_type_node;
11650       else if (type == double_type_node)
11651         type = complex_double_type_node;
11652       else if (type == long_double_type_node)
11653         type = complex_long_double_type_node;
11654       else
11655         type = build_complex_type (type);
11656     }
11657
11658   /* If we're using the injected-class-name to form a compound type or a
11659      declaration, replace it with the underlying class so we don't get
11660      redundant typedefs in the debug output.  But if we are returning the
11661      type unchanged, leave it alone so that it's available to
11662      maybe_get_template_decl_from_type_decl.  */
11663   if (CLASS_TYPE_P (type)
11664       && DECL_SELF_REFERENCE_P (TYPE_NAME (type))
11665       && type == TREE_TYPE (TYPE_NAME (type))
11666       && (declarator || type_quals))
11667     type = DECL_ORIGINAL_TYPE (TYPE_NAME (type));
11668
11669   type_quals |= cp_type_quals (type);
11670   type = cp_build_qualified_type_real
11671     (type, type_quals, ((((typedef_decl && !DECL_ARTIFICIAL (typedef_decl))
11672                           || declspecs->decltype_p)
11673                          ? tf_ignore_bad_quals : 0) | tf_warning_or_error));
11674   /* We might have ignored or rejected some of the qualifiers.  */
11675   type_quals = cp_type_quals (type);
11676
11677   if (cxx_dialect >= cxx17 && type && is_auto (type)
11678       && innermost_code != cdk_function
11679       && id_declarator && declarator != id_declarator)
11680     if (tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (type))
11681     {
11682       error_at (typespec_loc, "template placeholder type %qT must be followed "
11683                 "by a simple declarator-id", type);
11684       inform (DECL_SOURCE_LOCATION (tmpl), "%qD declared here", tmpl);
11685       type = error_mark_node;
11686     }
11687
11688   staticp = 0;
11689   inlinep = decl_spec_seq_has_spec_p (declspecs, ds_inline);
11690   virtualp =  decl_spec_seq_has_spec_p (declspecs, ds_virtual);
11691   explicitp = decl_spec_seq_has_spec_p (declspecs, ds_explicit);
11692
11693   storage_class = declspecs->storage_class;
11694   if (storage_class == sc_static)
11695     staticp = 1 + (decl_context == FIELD);
11696
11697   if (virtualp)
11698     {
11699       if (staticp == 2)
11700         {
11701           gcc_rich_location richloc (declspecs->locations[ds_virtual]);
11702           richloc.add_range (declspecs->locations[ds_storage_class]);
11703           error_at (&richloc, "member %qD cannot be declared both %<virtual%> "
11704                     "and %<static%>", dname);
11705           storage_class = sc_none;
11706           staticp = 0;
11707         }
11708       if (constexpr_p && cxx_dialect < cxx20)
11709         {
11710           gcc_rich_location richloc (declspecs->locations[ds_virtual]);
11711           richloc.add_range (declspecs->locations[ds_constexpr]);
11712           pedwarn (&richloc, OPT_Wpedantic, "member %qD can be declared both "
11713                    "%<virtual%> and %<constexpr%> only in %<-std=c++20%> or "
11714                    "%<-std=gnu++20%>", dname);
11715         }
11716     }
11717   friendp = decl_spec_seq_has_spec_p (declspecs, ds_friend);
11718
11719   /* Issue errors about use of storage classes for parameters.  */
11720   if (decl_context == PARM)
11721     {
11722       if (typedef_p)
11723         {
11724           error_at (declspecs->locations[ds_typedef],
11725                     "typedef declaration invalid in parameter declaration");
11726           return error_mark_node;
11727         }
11728       else if (template_parm_flag && storage_class != sc_none)
11729         {
11730           error_at (min_location (declspecs->locations[ds_thread],
11731                                   declspecs->locations[ds_storage_class]),
11732                     "storage class specified for template parameter %qs",
11733                     name);
11734           return error_mark_node;
11735         }
11736       else if (storage_class == sc_static
11737                || storage_class == sc_extern
11738                || thread_p)
11739         {
11740           error_at (min_location (declspecs->locations[ds_thread],
11741                                   declspecs->locations[ds_storage_class]),
11742                     "storage class specified for parameter %qs", name);
11743           return error_mark_node;
11744         }
11745
11746       /* Function parameters cannot be concept. */
11747       if (concept_p)
11748         {
11749           error_at (declspecs->locations[ds_concept],
11750                     "a parameter cannot be declared %qs", "concept");
11751           concept_p = 0;
11752           constexpr_p = 0;
11753         }
11754       /* Function parameters cannot be constexpr.  If we saw one, moan
11755          and pretend it wasn't there.  */
11756       else if (constexpr_p)
11757         {
11758           error_at (declspecs->locations[ds_constexpr],
11759                     "a parameter cannot be declared %qs", "constexpr");
11760           constexpr_p = 0;
11761         }
11762       if (constinit_p)
11763         {
11764           error_at (declspecs->locations[ds_constinit],
11765                     "a parameter cannot be declared %qs", "constinit");
11766           constinit_p = 0;
11767         }
11768       if (consteval_p)
11769         {
11770           error_at (declspecs->locations[ds_consteval],
11771                     "a parameter cannot be declared %qs", "consteval");
11772           consteval_p = 0;
11773         }
11774     }
11775
11776   /* Give error if `virtual' is used outside of class declaration.  */
11777   if (virtualp
11778       && (current_class_name == NULL_TREE || decl_context != FIELD))
11779     {
11780       error_at (declspecs->locations[ds_virtual],
11781                 "%<virtual%> outside class declaration");
11782       virtualp = 0;
11783     }
11784
11785   if (innermost_code == cdk_decomp)
11786     {
11787       location_t loc = (declarator->kind == cdk_reference
11788                         ? declarator->declarator->id_loc : declarator->id_loc);
11789       if (inlinep)
11790         error_at (declspecs->locations[ds_inline],
11791                   "structured binding declaration cannot be %qs", "inline");
11792       if (typedef_p)
11793         error_at (declspecs->locations[ds_typedef],
11794                   "structured binding declaration cannot be %qs", "typedef");
11795       if (constexpr_p && !concept_p)
11796         error_at (declspecs->locations[ds_constexpr], "structured "
11797                   "binding declaration cannot be %qs", "constexpr");
11798       if (consteval_p)
11799         error_at (declspecs->locations[ds_consteval], "structured "
11800                   "binding declaration cannot be %qs", "consteval");
11801       if (thread_p && cxx_dialect < cxx20)
11802         pedwarn (declspecs->locations[ds_thread], 0,
11803                  "structured binding declaration can be %qs only in "
11804                  "%<-std=c++20%> or %<-std=gnu++20%>",
11805                  declspecs->gnu_thread_keyword_p
11806                  ? "__thread" : "thread_local");
11807       if (concept_p)
11808         error_at (declspecs->locations[ds_concept],
11809                   "structured binding declaration cannot be %qs", "concept");
11810       /* [dcl.struct.bind] "A cv that includes volatile is deprecated."  */
11811       if (type_quals & TYPE_QUAL_VOLATILE)
11812         warning_at (declspecs->locations[ds_volatile], OPT_Wvolatile,
11813                     "%<volatile%>-qualified structured binding is deprecated");
11814       switch (storage_class)
11815         {
11816         case sc_none:
11817           break;
11818         case sc_register:
11819           error_at (loc, "structured binding declaration cannot be %qs",
11820                     "register");
11821           break;
11822         case sc_static:
11823           if (cxx_dialect < cxx20)
11824             pedwarn (loc, 0,
11825                      "structured binding declaration can be %qs only in "
11826                      "%<-std=c++20%> or %<-std=gnu++20%>", "static");
11827           break;
11828         case sc_extern:
11829           error_at (loc, "structured binding declaration cannot be %qs",
11830                     "extern");
11831           break;
11832         case sc_mutable:
11833           error_at (loc, "structured binding declaration cannot be %qs",
11834                     "mutable");
11835           break;
11836         case sc_auto:
11837           error_at (loc, "structured binding declaration cannot be "
11838                     "C++98 %<auto%>");
11839           break;
11840         default:
11841           gcc_unreachable ();
11842         }
11843       if (TREE_CODE (type) != TEMPLATE_TYPE_PARM
11844           || TYPE_IDENTIFIER (type) != auto_identifier)
11845         {
11846           if (type != error_mark_node)
11847             {
11848               error_at (loc, "structured binding declaration cannot have "
11849                         "type %qT", type);
11850               inform (loc,
11851                       "type must be cv-qualified %<auto%> or reference to "
11852                       "cv-qualified %<auto%>");
11853             }
11854           type = build_qualified_type (make_auto (), type_quals);
11855           declspecs->type = type;
11856         }
11857       inlinep = 0;
11858       typedef_p = 0;
11859       constexpr_p = 0;
11860       consteval_p = 0;
11861       concept_p = 0;
11862       if (storage_class != sc_static)
11863         {
11864           storage_class = sc_none;
11865           declspecs->storage_class = sc_none;
11866         }
11867     }
11868
11869   /* Static anonymous unions are dealt with here.  */
11870   if (staticp && decl_context == TYPENAME
11871       && declspecs->type
11872       && ANON_AGGR_TYPE_P (declspecs->type))
11873     decl_context = FIELD;
11874
11875   /* Warn about storage classes that are invalid for certain
11876      kinds of declarations (parameters, typenames, etc.).  */
11877   if (thread_p
11878       && ((storage_class
11879            && storage_class != sc_extern
11880            && storage_class != sc_static)
11881           || typedef_p))
11882     {
11883       location_t loc
11884         = min_location (declspecs->locations[ds_thread],
11885                         declspecs->locations[ds_storage_class]);
11886       error_at (loc, "multiple storage classes in declaration of %qs", name);
11887       thread_p = false;
11888     }
11889   if (decl_context != NORMAL
11890       && ((storage_class != sc_none
11891            && storage_class != sc_mutable)
11892           || thread_p))
11893     {
11894       if ((decl_context == PARM || decl_context == CATCHPARM)
11895           && (storage_class == sc_register
11896               || storage_class == sc_auto))
11897         ;
11898       else if (typedef_p)
11899         ;
11900       else if (decl_context == FIELD
11901                /* C++ allows static class elements.  */
11902                && storage_class == sc_static)
11903         /* C++ also allows inlines and signed and unsigned elements,
11904            but in those cases we don't come in here.  */
11905         ;
11906       else
11907         {
11908           location_t loc
11909             = min_location (declspecs->locations[ds_thread],
11910                             declspecs->locations[ds_storage_class]);
11911           if (decl_context == FIELD)
11912             error_at (loc, "storage class specified for %qs", name);
11913           else if (decl_context == PARM || decl_context == CATCHPARM)
11914             error_at (loc, "storage class specified for parameter %qs", name);
11915           else
11916             error_at (loc, "storage class specified for typename");
11917           if (storage_class == sc_register
11918               || storage_class == sc_auto
11919               || storage_class == sc_extern
11920               || thread_p)
11921             storage_class = sc_none;
11922         }
11923     }
11924   else if (storage_class == sc_extern && funcdef_flag
11925            && ! toplevel_bindings_p ())
11926     error ("nested function %qs declared %<extern%>", name);
11927   else if (toplevel_bindings_p ())
11928     {
11929       if (storage_class == sc_auto)
11930         error_at (declspecs->locations[ds_storage_class],
11931                   "top-level declaration of %qs specifies %<auto%>", name);
11932     }
11933   else if (thread_p
11934            && storage_class != sc_extern
11935            && storage_class != sc_static)
11936     {
11937       if (declspecs->gnu_thread_keyword_p)
11938         pedwarn (declspecs->locations[ds_thread],
11939                  0, "function-scope %qs implicitly auto and "
11940                  "declared %<__thread%>", name);
11941
11942       /* When thread_local is applied to a variable of block scope the
11943          storage-class-specifier static is implied if it does not appear
11944          explicitly.  */
11945       storage_class = declspecs->storage_class = sc_static;
11946       staticp = 1;
11947     }
11948
11949   if (storage_class && friendp)
11950     {
11951       error_at (min_location (declspecs->locations[ds_thread],
11952                               declspecs->locations[ds_storage_class]),
11953                 "storage class specifiers invalid in friend function "
11954                 "declarations");
11955       storage_class = sc_none;
11956       staticp = 0;
11957     }
11958
11959   if (!id_declarator)
11960     unqualified_id = NULL_TREE;
11961   else
11962     {
11963       unqualified_id = id_declarator->u.id.unqualified_name;
11964       switch (TREE_CODE (unqualified_id))
11965         {
11966         case BIT_NOT_EXPR:
11967           unqualified_id = TREE_OPERAND (unqualified_id, 0);
11968           if (TYPE_P (unqualified_id))
11969             unqualified_id = constructor_name (unqualified_id);
11970           break;
11971
11972         case IDENTIFIER_NODE:
11973         case TEMPLATE_ID_EXPR:
11974           break;
11975
11976         default:
11977           gcc_unreachable ();
11978         }
11979     }
11980
11981   if (declspecs->std_attributes)
11982     {
11983       location_t attr_loc = declspecs->locations[ds_std_attribute];
11984       if (warning_at (attr_loc, OPT_Wattributes, "attribute ignored"))
11985         inform (attr_loc, "an attribute that appertains to a type-specifier "
11986                 "is ignored");
11987     }
11988
11989   /* Determine the type of the entity declared by recurring on the
11990      declarator.  */
11991   for (; declarator; declarator = declarator->declarator)
11992     {
11993       const cp_declarator *inner_declarator;
11994       tree attrs;
11995
11996       if (type == error_mark_node)
11997         return error_mark_node;
11998
11999       attrs = declarator->attributes;
12000       if (attrs)
12001         {
12002           int attr_flags;
12003
12004           attr_flags = 0;
12005           if (declarator == NULL || declarator->kind == cdk_id)
12006             attr_flags |= (int) ATTR_FLAG_DECL_NEXT;
12007           if (declarator->kind == cdk_function)
12008             attr_flags |= (int) ATTR_FLAG_FUNCTION_NEXT;
12009           if (declarator->kind == cdk_array)
12010             attr_flags |= (int) ATTR_FLAG_ARRAY_NEXT;
12011           tree late_attrs = NULL_TREE;
12012           if (decl_context != PARM && decl_context != TYPENAME)
12013             /* Assume that any attributes that get applied late to
12014                templates will DTRT when applied to the declaration
12015                as a whole.  */
12016             late_attrs = splice_template_attributes (&attrs, type);
12017           returned_attrs = decl_attributes (&type,
12018                                             chainon (returned_attrs, attrs),
12019                                             attr_flags);
12020           returned_attrs = chainon (late_attrs, returned_attrs);
12021         }
12022
12023       inner_declarator = declarator->declarator;
12024
12025       /* We don't want to warn in parameter context because we don't
12026          yet know if the parse will succeed, and this might turn out
12027          to be a constructor call.  */
12028       if (decl_context != PARM
12029           && decl_context != TYPENAME
12030           && !typedef_p
12031           && declarator->parenthesized != UNKNOWN_LOCATION
12032           /* If the type is class-like and the inner name used a
12033              global namespace qualifier, we need the parens.
12034              Unfortunately all we can tell is whether a qualified name
12035              was used or not.  */
12036           && !(inner_declarator
12037                && inner_declarator->kind == cdk_id
12038                && inner_declarator->u.id.qualifying_scope
12039                && (MAYBE_CLASS_TYPE_P (type)
12040                    || TREE_CODE (type) == ENUMERAL_TYPE)))
12041         warning_at (declarator->parenthesized, OPT_Wparentheses,
12042                     "unnecessary parentheses in declaration of %qs", name);
12043       if (declarator->kind == cdk_id || declarator->kind == cdk_decomp)
12044         break;
12045
12046       switch (declarator->kind)
12047         {
12048         case cdk_array:
12049           type = create_array_type_for_decl (dname, type,
12050                                              declarator->u.array.bounds,
12051                                              declarator->id_loc);
12052           if (!valid_array_size_p (dname
12053                                    ? declarator->id_loc : input_location,
12054                                    type, dname))
12055             type = error_mark_node;
12056
12057           if (declarator->std_attributes)
12058             /* [dcl.array]/1:
12059
12060                The optional attribute-specifier-seq appertains to the
12061                array.  */
12062             returned_attrs = chainon (returned_attrs,
12063                                       declarator->std_attributes);
12064           break;
12065
12066         case cdk_function:
12067           {
12068             tree arg_types;
12069             int funcdecl_p;
12070
12071             /* Declaring a function type.  */
12072
12073             {
12074               iloc_sentinel ils (declspecs->locations[ds_type_spec]);
12075               abstract_virtuals_error (ACU_RETURN, type);
12076             }
12077
12078             /* Pick up type qualifiers which should be applied to `this'.  */
12079             memfn_quals = declarator->u.function.qualifiers;
12080             /* Pick up virt-specifiers.  */
12081             virt_specifiers = declarator->u.function.virt_specifiers;
12082             /* And ref-qualifier, too */
12083             rqual = declarator->u.function.ref_qualifier;
12084             /* And tx-qualifier.  */
12085             tree tx_qual = declarator->u.function.tx_qualifier;
12086             /* Pick up the exception specifications.  */
12087             raises = declarator->u.function.exception_specification;
12088             /* If the exception-specification is ill-formed, let's pretend
12089                there wasn't one.  */
12090             if (raises == error_mark_node)
12091               raises = NULL_TREE;
12092
12093             if (reqs)
12094               error_at (location_of (reqs), "requires-clause on return type");
12095             reqs = declarator->u.function.requires_clause;
12096
12097             /* Say it's a definition only for the CALL_EXPR
12098                closest to the identifier.  */
12099             funcdecl_p = inner_declarator && inner_declarator->kind == cdk_id;
12100
12101             /* Handle a late-specified return type.  */
12102             tree late_return_type = declarator->u.function.late_return_type;
12103             if (tree auto_node = type_uses_auto (type))
12104               {
12105                 if (!late_return_type && funcdecl_p)
12106                   {
12107                     if (current_class_type
12108                         && LAMBDA_TYPE_P (current_class_type))
12109                       /* OK for C++11 lambdas.  */;
12110                     else if (cxx_dialect < cxx14)
12111                       {
12112                         error_at (typespec_loc, "%qs function uses "
12113                                   "%<auto%> type specifier without "
12114                                   "trailing return type", name);
12115                         inform (typespec_loc,
12116                                 "deduced return type only available "
12117                                 "with %<-std=c++14%> or %<-std=gnu++14%>");
12118                       }
12119                     else if (virtualp)
12120                       {
12121                         error_at (typespec_loc, "virtual function "
12122                                   "cannot have deduced return type");
12123                         virtualp = false;
12124                       }
12125                   }
12126                 else if (!is_auto (type) && sfk != sfk_conversion)
12127                   {
12128                     error_at (typespec_loc, "%qs function with trailing "
12129                               "return type has %qT as its type rather "
12130                               "than plain %<auto%>", name, type);
12131                     return error_mark_node;
12132                   }
12133                 else if (is_auto (type) && AUTO_IS_DECLTYPE (type))
12134                   {
12135                     if (funcdecl_p)
12136                       error_at (typespec_loc,
12137                                 "%qs function with trailing return type "
12138                                 "has %<decltype(auto)%> as its type "
12139                                 "rather than plain %<auto%>", name);
12140                     else
12141                       error_at (typespec_loc,
12142                                 "invalid use of %<decltype(auto)%>");
12143                     return error_mark_node;
12144                   }
12145                 tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node);
12146                 if (!tmpl)
12147                   if (tree late_auto = type_uses_auto (late_return_type))
12148                     tmpl = CLASS_PLACEHOLDER_TEMPLATE (late_auto);
12149                 if (tmpl && funcdecl_p)
12150                   {
12151                     if (!dguide_name_p (unqualified_id))
12152                       {
12153                         error_at (declarator->id_loc, "deduced class "
12154                                   "type %qD in function return type",
12155                                   DECL_NAME (tmpl));
12156                         inform (DECL_SOURCE_LOCATION (tmpl),
12157                                 "%qD declared here", tmpl);
12158                         return error_mark_node;
12159                       }
12160                     else if (!late_return_type)
12161                       {
12162                         error_at (declarator->id_loc, "deduction guide "
12163                                   "for %qT must have trailing return "
12164                                   "type", TREE_TYPE (tmpl));
12165                         inform (DECL_SOURCE_LOCATION (tmpl),
12166                                 "%qD declared here", tmpl);
12167                         return error_mark_node;
12168                       }
12169                     else if (CLASS_TYPE_P (late_return_type)
12170                               && CLASSTYPE_TEMPLATE_INFO (late_return_type)
12171                               && (CLASSTYPE_TI_TEMPLATE (late_return_type)
12172                                   == tmpl))
12173                       /* OK */;
12174                     else
12175                       error ("trailing return type %qT of deduction guide "
12176                               "is not a specialization of %qT",
12177                               late_return_type, TREE_TYPE (tmpl));
12178                   }
12179               }
12180             else if (late_return_type
12181                      && sfk != sfk_conversion)
12182               {
12183                 if (late_return_type == error_mark_node)
12184                   return error_mark_node;
12185                 if (cxx_dialect < cxx11)
12186                   /* Not using maybe_warn_cpp0x because this should
12187                      always be an error.  */
12188                   error_at (typespec_loc,
12189                             "trailing return type only available "
12190                             "with %<-std=c++11%> or %<-std=gnu++11%>");
12191                 else
12192                   error_at (typespec_loc, "%qs function with trailing "
12193                             "return type not declared with %<auto%> "
12194                             "type specifier", name);
12195                 return error_mark_node;
12196               }
12197             type = splice_late_return_type (type, late_return_type);
12198             if (type == error_mark_node)
12199               return error_mark_node;
12200
12201             if (late_return_type)
12202               {
12203                 late_return_type_p = true;
12204                 type_quals = cp_type_quals (type);
12205               }
12206
12207             if (type_quals != TYPE_UNQUALIFIED)
12208               {
12209                 if (SCALAR_TYPE_P (type) || VOID_TYPE_P (type))
12210                   warning_at (typespec_loc, OPT_Wignored_qualifiers, "type "
12211                               "qualifiers ignored on function return type");
12212                 /* [dcl.fct] "A volatile-qualified return type is
12213                    deprecated."  */
12214                 if (type_quals & TYPE_QUAL_VOLATILE)
12215                   warning_at (typespec_loc, OPT_Wvolatile,
12216                               "%<volatile%>-qualified return type is "
12217                               "deprecated");
12218
12219                 /* We now know that the TYPE_QUALS don't apply to the
12220                    decl, but to its return type.  */
12221                 type_quals = TYPE_UNQUALIFIED;
12222               }
12223
12224             /* Error about some types functions can't return.  */
12225
12226             if (TREE_CODE (type) == FUNCTION_TYPE)
12227               {
12228                 error_at (typespec_loc, "%qs declared as function returning "
12229                           "a function", name);
12230                 return error_mark_node;
12231               }
12232             if (TREE_CODE (type) == ARRAY_TYPE)
12233               {
12234                 error_at (typespec_loc, "%qs declared as function returning "
12235                           "an array", name);
12236                 return error_mark_node;
12237               }
12238             if (constinit_p)
12239               {
12240                 error_at (declspecs->locations[ds_constinit],
12241                           "%<constinit%> on function return type is not "
12242                           "allowed");
12243                 return error_mark_node;
12244               }
12245             /* Only plain decltype(auto) is allowed.  */
12246             if (tree a = type_uses_auto (type))
12247               {
12248                 if (AUTO_IS_DECLTYPE (a))
12249                   {
12250                     if (a != type)
12251                       {
12252                         error_at (typespec_loc, "%qT as type rather than "
12253                                   "plain %<decltype(auto)%>", type);
12254                         return error_mark_node;
12255                       }
12256                     else if (TYPE_QUALS (type) != TYPE_UNQUALIFIED)
12257                       {
12258                         error_at (typespec_loc, "%<decltype(auto)%> cannot be "
12259                                   "cv-qualified");
12260                         return error_mark_node;
12261                       }
12262                   }
12263               }
12264
12265             if (ctype == NULL_TREE
12266                 && decl_context == FIELD
12267                 && funcdecl_p
12268                 && friendp == 0)
12269               ctype = current_class_type;
12270
12271             if (ctype && (sfk == sfk_constructor
12272                           || sfk == sfk_destructor))
12273               {
12274                 /* We are within a class's scope. If our declarator name
12275                    is the same as the class name, and we are defining
12276                    a function, then it is a constructor/destructor, and
12277                    therefore returns a void type.  */
12278
12279                 /* ISO C++ 12.4/2.  A destructor may not be declared
12280                    const or volatile.  A destructor may not be static.
12281                    A destructor may not be declared with ref-qualifier.
12282
12283                    ISO C++ 12.1.  A constructor may not be declared
12284                    const or volatile.  A constructor may not be
12285                    virtual.  A constructor may not be static.
12286                    A constructor may not be declared with ref-qualifier. */
12287                 if (staticp == 2)
12288                   error_at (declspecs->locations[ds_storage_class],
12289                             (flags == DTOR_FLAG)
12290                             ? G_("destructor cannot be static member "
12291                                  "function")
12292                             : G_("constructor cannot be static member "
12293                                  "function"));
12294                 if (memfn_quals)
12295                   {
12296                     error ((flags == DTOR_FLAG)
12297                            ? G_("destructors may not be cv-qualified")
12298                            : G_("constructors may not be cv-qualified"));
12299                     memfn_quals = TYPE_UNQUALIFIED;
12300                   }
12301
12302                 if (rqual)
12303                   {
12304                     maybe_warn_cpp0x (CPP0X_REF_QUALIFIER);
12305                     error ((flags == DTOR_FLAG)
12306                            ? G_("destructors may not be ref-qualified")
12307                            : G_("constructors may not be ref-qualified"));
12308                     rqual = REF_QUAL_NONE;
12309                   }
12310
12311                 if (decl_context == FIELD
12312                     && !member_function_or_else (ctype,
12313                                                  current_class_type,
12314                                                  flags))
12315                   return error_mark_node;
12316
12317                 if (flags != DTOR_FLAG)
12318                   {
12319                     /* It's a constructor.  */
12320                     if (explicitp == 1)
12321                       explicitp = 2;
12322                     if (virtualp)
12323                       {
12324                         permerror (declspecs->locations[ds_virtual],
12325                                    "constructors cannot be declared %<virtual%>");
12326                         virtualp = 0;
12327                       }
12328                     if (decl_context == FIELD
12329                         && sfk != sfk_constructor)
12330                       return error_mark_node;
12331                   }
12332                 if (decl_context == FIELD)
12333                   staticp = 0;
12334               }
12335             else if (friendp)
12336               {
12337                 if (virtualp)
12338                   {
12339                     /* Cannot be both friend and virtual.  */
12340                     gcc_rich_location richloc (declspecs->locations[ds_virtual]);
12341                     richloc.add_range (declspecs->locations[ds_friend]);
12342                     error_at (&richloc, "virtual functions cannot be friends");
12343                     friendp = 0;
12344                   }
12345                 if (decl_context == NORMAL)
12346                   error_at (declarator->id_loc,
12347                             "friend declaration not in class definition");
12348                 if (current_function_decl && funcdef_flag)
12349                   {
12350                     error_at (declarator->id_loc,
12351                               "cannot define friend function %qs in a local "
12352                               "class definition", name);
12353                     friendp = 0;
12354                   }
12355                 /* [class.friend]/6: A function can be defined in a friend
12356                    declaration if the function name is unqualified.  */
12357                 if (funcdef_flag && in_namespace)
12358                   {
12359                     if (in_namespace == global_namespace)
12360                       error_at (declarator->id_loc,
12361                                 "friend function definition %qs cannot have "
12362                                 "a name qualified with %<::%>", name);
12363                     else
12364                       error_at (declarator->id_loc,
12365                                 "friend function definition %qs cannot have "
12366                                 "a name qualified with %<%D::%>", name,
12367                                 in_namespace);
12368                   }
12369               }
12370             else if (ctype && sfk == sfk_conversion)
12371               {
12372                 if (explicitp == 1)
12373                   {
12374                     maybe_warn_cpp0x (CPP0X_EXPLICIT_CONVERSION);
12375                     explicitp = 2;
12376                   }
12377                 if (late_return_type_p)
12378                   error ("a conversion function cannot have a trailing return type");
12379               }
12380             else if (sfk == sfk_deduction_guide)
12381               {
12382                 if (explicitp == 1)
12383                   explicitp = 2;
12384               }
12385
12386             tree pushed_scope = NULL_TREE;
12387             if (funcdecl_p
12388                 && decl_context != FIELD
12389                 && inner_declarator->u.id.qualifying_scope
12390                 && CLASS_TYPE_P (inner_declarator->u.id.qualifying_scope))
12391               pushed_scope
12392                 = push_scope (inner_declarator->u.id.qualifying_scope);
12393
12394             arg_types = grokparms (declarator->u.function.parameters, &parms);
12395
12396             if (pushed_scope)
12397               pop_scope (pushed_scope);
12398
12399             if (inner_declarator
12400                 && inner_declarator->kind == cdk_id
12401                 && inner_declarator->u.id.sfk == sfk_destructor
12402                 && arg_types != void_list_node)
12403               {
12404                 error_at (declarator->id_loc,
12405                           "destructors may not have parameters");
12406                 arg_types = void_list_node;
12407                 parms = NULL_TREE;
12408               }
12409
12410             type = build_function_type (type, arg_types);
12411
12412             tree attrs = declarator->std_attributes;
12413             if (tx_qual)
12414               {
12415                 tree att = build_tree_list (tx_qual, NULL_TREE);
12416                 /* transaction_safe applies to the type, but
12417                    transaction_safe_dynamic applies to the function.  */
12418                 if (is_attribute_p ("transaction_safe", tx_qual))
12419                   attrs = chainon (attrs, att);
12420                 else
12421                   returned_attrs = chainon (returned_attrs, att);
12422               }
12423             if (attrs)
12424               /* [dcl.fct]/2:
12425
12426                  The optional attribute-specifier-seq appertains to
12427                  the function type.  */
12428               cplus_decl_attributes (&type, attrs, 0);
12429
12430             if (raises)
12431               type = build_exception_variant (type, raises);
12432           }
12433           break;
12434
12435         case cdk_pointer:
12436         case cdk_reference:
12437         case cdk_ptrmem:
12438           /* Filter out pointers-to-references and references-to-references.
12439              We can get these if a TYPE_DECL is used.  */
12440
12441           if (TYPE_REF_P (type))
12442             {
12443               if (declarator->kind != cdk_reference)
12444                 {
12445                   error ("cannot declare pointer to %q#T", type);
12446                   type = TREE_TYPE (type);
12447                 }
12448
12449               /* In C++0x, we allow reference to reference declarations
12450                  that occur indirectly through typedefs [7.1.3/8 dcl.typedef]
12451                  and template type arguments [14.3.1/4 temp.arg.type]. The
12452                  check for direct reference to reference declarations, which
12453                  are still forbidden, occurs below. Reasoning behind the change
12454                  can be found in DR106, DR540, and the rvalue reference
12455                  proposals. */
12456               else if (cxx_dialect == cxx98)
12457                 {
12458                   error ("cannot declare reference to %q#T", type);
12459                   type = TREE_TYPE (type);
12460                 }
12461             }
12462           else if (VOID_TYPE_P (type))
12463             {
12464               if (declarator->kind == cdk_reference)
12465                 error ("cannot declare reference to %q#T", type);
12466               else if (declarator->kind == cdk_ptrmem)
12467                 error ("cannot declare pointer to %q#T member", type);
12468             }
12469
12470           /* We now know that the TYPE_QUALS don't apply to the decl,
12471              but to the target of the pointer.  */
12472           type_quals = TYPE_UNQUALIFIED;
12473
12474           /* This code used to handle METHOD_TYPE, but I don't think it's
12475              possible to get it here anymore.  */
12476           gcc_assert (TREE_CODE (type) != METHOD_TYPE);
12477           if (declarator->kind == cdk_ptrmem
12478               && TREE_CODE (type) == FUNCTION_TYPE)
12479             {
12480               memfn_quals |= type_memfn_quals (type);
12481               type = build_memfn_type (type,
12482                                        declarator->u.pointer.class_type,
12483                                        memfn_quals,
12484                                        rqual);
12485               if (type == error_mark_node)
12486                 return error_mark_node;
12487
12488               rqual = REF_QUAL_NONE;
12489               memfn_quals = TYPE_UNQUALIFIED;
12490             }
12491
12492           if (TREE_CODE (type) == FUNCTION_TYPE
12493               && (type_memfn_quals (type) != TYPE_UNQUALIFIED
12494                   || type_memfn_rqual (type) != REF_QUAL_NONE))
12495             error (declarator->kind == cdk_reference
12496                    ? G_("cannot declare reference to qualified function type %qT")
12497                    : G_("cannot declare pointer to qualified function type %qT"),
12498                    type);
12499
12500           /* When the pointed-to type involves components of variable size,
12501              care must be taken to ensure that the size evaluation code is
12502              emitted early enough to dominate all the possible later uses
12503              and late enough for the variables on which it depends to have
12504              been assigned.
12505
12506              This is expected to happen automatically when the pointed-to
12507              type has a name/declaration of it's own, but special attention
12508              is required if the type is anonymous.
12509
12510              We handle the NORMAL and FIELD contexts here by inserting a
12511              dummy statement that just evaluates the size at a safe point
12512              and ensures it is not deferred until e.g. within a deeper
12513              conditional context (c++/43555).
12514
12515              We expect nothing to be needed here for PARM or TYPENAME.
12516              Evaluating the size at this point for TYPENAME would
12517              actually be incorrect, as we might be in the middle of an
12518              expression with side effects on the pointed-to type size
12519              "arguments" prior to the pointer declaration point and the
12520              size evaluation could end up prior to the side effects.  */
12521
12522           if (!TYPE_NAME (type)
12523               && (decl_context == NORMAL || decl_context == FIELD)
12524               && at_function_scope_p ()
12525               && variably_modified_type_p (type, NULL_TREE))
12526             {
12527               TYPE_NAME (type) = build_decl (UNKNOWN_LOCATION, TYPE_DECL,
12528                                              NULL_TREE, type);
12529               add_decl_expr (TYPE_NAME (type));
12530             }
12531
12532           if (declarator->kind == cdk_reference)
12533             {
12534               /* In C++0x, the type we are creating a reference to might be
12535                  a typedef which is itself a reference type. In that case,
12536                  we follow the reference collapsing rules in
12537                  [7.1.3/8 dcl.typedef] to create the final reference type:
12538
12539                  "If a typedef TD names a type that is a reference to a type
12540                  T, an attempt to create the type 'lvalue reference to cv TD'
12541                  creates the type 'lvalue reference to T,' while an attempt
12542                  to create the type "rvalue reference to cv TD' creates the
12543                  type TD."
12544               */
12545               if (VOID_TYPE_P (type))
12546                 /* We already gave an error.  */;
12547               else if (TYPE_REF_P (type))
12548                 {
12549                   if (declarator->u.reference.rvalue_ref)
12550                     /* Leave type alone.  */;
12551                   else
12552                     type = cp_build_reference_type (TREE_TYPE (type), false);
12553                 }
12554               else
12555                 type = cp_build_reference_type
12556                   (type, declarator->u.reference.rvalue_ref);
12557
12558               /* In C++0x, we need this check for direct reference to
12559                  reference declarations, which are forbidden by
12560                  [8.3.2/5 dcl.ref]. Reference to reference declarations
12561                  are only allowed indirectly through typedefs and template
12562                  type arguments. Example:
12563
12564                    void foo(int & &);      // invalid ref-to-ref decl
12565
12566                    typedef int & int_ref;
12567                    void foo(int_ref &);    // valid ref-to-ref decl
12568               */
12569               if (inner_declarator && inner_declarator->kind == cdk_reference)
12570                 error ("cannot declare reference to %q#T, which is not "
12571                        "a typedef or a template type argument", type);
12572             }
12573           else if (TREE_CODE (type) == METHOD_TYPE)
12574             type = build_ptrmemfunc_type (build_pointer_type (type));
12575           else if (declarator->kind == cdk_ptrmem)
12576             {
12577               gcc_assert (TREE_CODE (declarator->u.pointer.class_type)
12578                           != NAMESPACE_DECL);
12579               if (declarator->u.pointer.class_type == error_mark_node)
12580                 /* We will already have complained.  */
12581                 type = error_mark_node;
12582               else
12583                 type = build_ptrmem_type (declarator->u.pointer.class_type,
12584                                           type);
12585             }
12586           else
12587             type = build_pointer_type (type);
12588
12589           /* Process a list of type modifier keywords (such as
12590              const or volatile) that were given inside the `*' or `&'.  */
12591
12592           if (declarator->u.pointer.qualifiers)
12593             {
12594               type
12595                 = cp_build_qualified_type (type,
12596                                            declarator->u.pointer.qualifiers);
12597               type_quals = cp_type_quals (type);
12598             }
12599
12600           /* Apply C++11 attributes to the pointer, and not to the
12601              type pointed to.  This is unlike what is done for GNU
12602              attributes above.  It is to comply with [dcl.ptr]/1:
12603
12604                  [the optional attribute-specifier-seq (7.6.1) appertains
12605                   to the pointer and not to the object pointed to].  */
12606           if (declarator->std_attributes)
12607             decl_attributes (&type, declarator->std_attributes,
12608                              0);
12609
12610           ctype = NULL_TREE;
12611           break;
12612
12613         case cdk_error:
12614           break;
12615
12616         default:
12617           gcc_unreachable ();
12618         }
12619     }
12620
12621   id_loc = declarator ? declarator->id_loc : input_location;
12622
12623   /* A `constexpr' specifier used in an object declaration declares
12624      the object as `const'.  */
12625   if (constexpr_p && innermost_code != cdk_function)
12626     {
12627       /* DR1688 says that a `constexpr' specifier in combination with
12628          `volatile' is valid.  */
12629
12630       if (!TYPE_REF_P (type))
12631         {
12632           type_quals |= TYPE_QUAL_CONST;
12633           type = cp_build_qualified_type (type, type_quals);
12634         }
12635     }
12636
12637   if (unqualified_id && TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR
12638       && !FUNC_OR_METHOD_TYPE_P (type)
12639       && !variable_template_p (TREE_OPERAND (unqualified_id, 0)))
12640     {
12641       error ("template-id %qD used as a declarator",
12642              unqualified_id);
12643       unqualified_id = dname;
12644     }
12645
12646   /* If TYPE is a FUNCTION_TYPE, but the function name was explicitly
12647      qualified with a class-name, turn it into a METHOD_TYPE, unless
12648      we know that the function is static.  We take advantage of this
12649      opportunity to do other processing that pertains to entities
12650      explicitly declared to be class members.  Note that if DECLARATOR
12651      is non-NULL, we know it is a cdk_id declarator; otherwise, we
12652      would not have exited the loop above.  */
12653   if (declarator
12654       && declarator->kind == cdk_id
12655       && declarator->u.id.qualifying_scope
12656       && MAYBE_CLASS_TYPE_P (declarator->u.id.qualifying_scope))
12657     {
12658       ctype = declarator->u.id.qualifying_scope;
12659       ctype = TYPE_MAIN_VARIANT (ctype);
12660       template_count = num_template_headers_for_class (ctype);
12661
12662       if (ctype == current_class_type)
12663         {
12664           if (friendp)
12665             {
12666               permerror (declspecs->locations[ds_friend],
12667                          "member functions are implicitly "
12668                          "friends of their class");
12669               friendp = 0;
12670             }
12671           else
12672             permerror (id_loc, "extra qualification %<%T::%> on member %qs",
12673                        ctype, name);
12674         }
12675       else if (/* If the qualifying type is already complete, then we
12676                   can skip the following checks.  */
12677                !COMPLETE_TYPE_P (ctype)
12678                && (/* If the function is being defined, then
12679                       qualifying type must certainly be complete.  */
12680                    funcdef_flag
12681                    /* A friend declaration of "T::f" is OK, even if
12682                       "T" is a template parameter.  But, if this
12683                       function is not a friend, the qualifying type
12684                       must be a class.  */
12685                    || (!friendp && !CLASS_TYPE_P (ctype))
12686                    /* For a declaration, the type need not be
12687                       complete, if either it is dependent (since there
12688                       is no meaningful definition of complete in that
12689                       case) or the qualifying class is currently being
12690                       defined.  */
12691                    || !(dependent_type_p (ctype)
12692                         || currently_open_class (ctype)))
12693                /* Check that the qualifying type is complete.  */
12694                && !complete_type_or_else (ctype, NULL_TREE))
12695         return error_mark_node;
12696       else if (TREE_CODE (type) == FUNCTION_TYPE)
12697         {
12698           if (current_class_type
12699               && (!friendp || funcdef_flag || initialized))
12700             {
12701               error_at (id_loc, funcdef_flag || initialized
12702                         ? G_("cannot define member function %<%T::%s%> "
12703                              "within %qT")
12704                         : G_("cannot declare member function %<%T::%s%> "
12705                              "within %qT"),
12706                         ctype, name, current_class_type);
12707               return error_mark_node;
12708             }
12709         }
12710       else if (typedef_p && current_class_type)
12711         {
12712           error_at (id_loc, "cannot declare member %<%T::%s%> within %qT",
12713                     ctype, name, current_class_type);
12714           return error_mark_node;
12715         }
12716     }
12717
12718   if (ctype == NULL_TREE && decl_context == FIELD && friendp == 0)
12719     ctype = current_class_type;
12720
12721   /* Now TYPE has the actual type.  */
12722
12723   if (returned_attrs)
12724     {
12725       if (attrlist)
12726         *attrlist = chainon (returned_attrs, *attrlist);
12727       else
12728         attrlist = &returned_attrs;
12729     }
12730
12731   if (declarator
12732       && declarator->kind == cdk_id
12733       && declarator->std_attributes
12734       && attrlist != NULL)
12735     {
12736       /* [dcl.meaning]/1: The optional attribute-specifier-seq following
12737          a declarator-id appertains to the entity that is declared.  */
12738       if (declarator->std_attributes != error_mark_node)
12739         *attrlist = chainon (*attrlist, declarator->std_attributes);
12740       else
12741         /* We should have already diagnosed the issue (c++/78344).  */
12742         gcc_assert (seen_error ());
12743     }
12744
12745   /* Handle parameter packs. */
12746   if (parameter_pack_p)
12747     {
12748       if (decl_context == PARM)
12749         /* Turn the type into a pack expansion.*/
12750         type = make_pack_expansion (type);
12751       else
12752         error ("non-parameter %qs cannot be a parameter pack", name);
12753     }
12754
12755   if ((decl_context == FIELD || decl_context == PARM)
12756       && !processing_template_decl
12757       && variably_modified_type_p (type, NULL_TREE))
12758     {
12759       if (decl_context == FIELD)
12760         error_at (id_loc,
12761                   "data member may not have variably modified type %qT", type);
12762       else
12763         error_at (id_loc,
12764                   "parameter may not have variably modified type %qT", type);
12765       type = error_mark_node;
12766     }
12767
12768   if (explicitp == 1 || (explicitp && friendp))
12769     {
12770       /* [dcl.fct.spec] (C++11) The explicit specifier shall be used only
12771          in the declaration of a constructor or conversion function within
12772          a class definition.  */
12773       if (!current_class_type)
12774         error_at (declspecs->locations[ds_explicit],
12775                   "%<explicit%> outside class declaration");
12776       else if (friendp)
12777         error_at (declspecs->locations[ds_explicit],
12778                   "%<explicit%> in friend declaration");
12779       else
12780         error_at (declspecs->locations[ds_explicit],
12781                   "only declarations of constructors and conversion operators "
12782                   "can be %<explicit%>");
12783       explicitp = 0;
12784     }
12785
12786   if (storage_class == sc_mutable)
12787     {
12788       location_t sloc = declspecs->locations[ds_storage_class];
12789       if (decl_context != FIELD || friendp)
12790         {
12791           error_at (sloc, "non-member %qs cannot be declared %<mutable%>",
12792                     name);
12793           storage_class = sc_none;
12794         }
12795       else if (decl_context == TYPENAME || typedef_p)
12796         {
12797           error_at (sloc,
12798                     "non-object member %qs cannot be declared %<mutable%>",
12799                     name);
12800           storage_class = sc_none;
12801         }
12802       else if (FUNC_OR_METHOD_TYPE_P (type))
12803         {
12804           error_at (sloc, "function %qs cannot be declared %<mutable%>",
12805                     name);
12806           storage_class = sc_none;
12807         }
12808       else if (staticp)
12809         {
12810           error_at (sloc, "%<static%> %qs cannot be declared %<mutable%>",
12811                     name);
12812           storage_class = sc_none;
12813         }
12814       else if (type_quals & TYPE_QUAL_CONST)
12815         {
12816           error_at (sloc, "%<const%> %qs cannot be declared %<mutable%>",
12817                     name);
12818           storage_class = sc_none;
12819         }
12820       else if (TYPE_REF_P (type))
12821         {
12822           permerror (sloc, "reference %qs cannot be declared %<mutable%>",
12823                      name);
12824           storage_class = sc_none;
12825         }
12826     }
12827
12828   /* If this is declaring a typedef name, return a TYPE_DECL.  */
12829   if (typedef_p && decl_context != TYPENAME)
12830     {
12831       bool alias_p = decl_spec_seq_has_spec_p (declspecs, ds_alias);
12832       tree decl;
12833
12834       if (funcdef_flag)
12835         {
12836           if (decl_context == NORMAL)
12837             error_at (id_loc,
12838                       "typedef may not be a function definition");
12839           else
12840             error_at (id_loc,
12841                       "typedef may not be a member function definition");
12842           return error_mark_node;
12843         }
12844
12845       /* This declaration:
12846
12847            typedef void f(int) const;
12848
12849          declares a function type which is not a member of any
12850          particular class, but which is cv-qualified; for
12851          example "f S::*" declares a pointer to a const-qualified
12852          member function of S.  We record the cv-qualification in the
12853          function type.  */
12854       if ((rqual || memfn_quals) && TREE_CODE (type) == FUNCTION_TYPE)
12855         {
12856           type = apply_memfn_quals (type, memfn_quals, rqual);
12857           
12858           /* We have now dealt with these qualifiers.  */
12859           memfn_quals = TYPE_UNQUALIFIED;
12860           rqual = REF_QUAL_NONE;
12861         }
12862
12863       if (type_uses_auto (type))
12864         {
12865           if (alias_p)
12866             error_at (declspecs->locations[ds_type_spec],
12867                       "%<auto%> not allowed in alias declaration");
12868           else
12869             error_at (declspecs->locations[ds_type_spec],
12870                       "typedef declared %<auto%>");
12871           type = error_mark_node;
12872         }
12873
12874       if (reqs)
12875         error_at (location_of (reqs), "requires-clause on typedef");
12876
12877       if (id_declarator && declarator->u.id.qualifying_scope)
12878         {
12879           error_at (id_loc, "typedef name may not be a nested-name-specifier");
12880           type = error_mark_node;
12881         }
12882
12883       if (decl_context == FIELD)
12884         decl = build_lang_decl_loc (id_loc, TYPE_DECL, unqualified_id, type);
12885       else
12886         decl = build_decl (id_loc, TYPE_DECL, unqualified_id, type);
12887
12888       if (decl_context != FIELD)
12889         {
12890           if (!current_function_decl)
12891             DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
12892           else if (DECL_MAYBE_IN_CHARGE_CDTOR_P (current_function_decl))
12893             /* The TYPE_DECL is "abstract" because there will be
12894                clones of this constructor/destructor, and there will
12895                be copies of this TYPE_DECL generated in those
12896                clones.  The decloning optimization (for space) may
12897                revert this subsequently if it determines that
12898                the clones should share a common implementation.  */
12899             DECL_ABSTRACT_P (decl) = true;
12900         }
12901       else if (current_class_type
12902                && constructor_name_p (unqualified_id, current_class_type))
12903         permerror (id_loc, "ISO C++ forbids nested type %qD with same name "
12904                    "as enclosing class",
12905                    unqualified_id);
12906
12907       /* If the user declares "typedef struct {...} foo" then the
12908          struct will have an anonymous name.  Fill that name in now.
12909          Nothing can refer to it, so nothing needs know about the name
12910          change.  */
12911       if (type != error_mark_node
12912           && unqualified_id
12913           && TYPE_NAME (type)
12914           && TREE_CODE (TYPE_NAME (type)) == TYPE_DECL
12915           && TYPE_UNNAMED_P (type)
12916           && declspecs->type_definition_p
12917           && attributes_naming_typedef_ok (*attrlist)
12918           && cp_type_quals (type) == TYPE_UNQUALIFIED)
12919         name_unnamed_type (type, decl);
12920
12921       if (signed_p
12922           || (typedef_decl && C_TYPEDEF_EXPLICITLY_SIGNED (typedef_decl)))
12923         C_TYPEDEF_EXPLICITLY_SIGNED (decl) = 1;
12924
12925       bad_specifiers (decl, BSP_TYPE, virtualp,
12926                       memfn_quals != TYPE_UNQUALIFIED,
12927                       inlinep, friendp, raises != NULL_TREE,
12928                       declspecs->locations);
12929
12930       if (alias_p)
12931         /* Acknowledge that this was written:
12932              `using analias = atype;'.  */
12933         TYPE_DECL_ALIAS_P (decl) = 1;
12934
12935       return decl;
12936     }
12937
12938   /* Detect the case of an array type of unspecified size
12939      which came, as such, direct from a typedef name.
12940      We must copy the type, so that the array's domain can be
12941      individually set by the object's initializer.  */
12942
12943   if (type && typedef_type
12944       && TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type)
12945       && TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (typedef_type))
12946     type = build_cplus_array_type (TREE_TYPE (type), NULL_TREE);
12947
12948   /* Detect where we're using a typedef of function type to declare a
12949      function. PARMS will not be set, so we must create it now.  */
12950
12951   if (type == typedef_type && TREE_CODE (type) == FUNCTION_TYPE)
12952     {
12953       tree decls = NULL_TREE;
12954       tree args;
12955
12956       for (args = TYPE_ARG_TYPES (type);
12957            args && args != void_list_node;
12958            args = TREE_CHAIN (args))
12959         {
12960           tree decl = cp_build_parm_decl (NULL_TREE, NULL_TREE,
12961                                           TREE_VALUE (args));
12962
12963           DECL_CHAIN (decl) = decls;
12964           decls = decl;
12965         }
12966
12967       parms = nreverse (decls);
12968
12969       if (decl_context != TYPENAME)
12970         {
12971           /* The qualifiers on the function type become the qualifiers on
12972              the non-static member function. */
12973           memfn_quals |= type_memfn_quals (type);
12974           rqual = type_memfn_rqual (type);
12975           type_quals = TYPE_UNQUALIFIED;
12976           raises = TYPE_RAISES_EXCEPTIONS (type);
12977         }
12978     }
12979
12980   /* If this is a type name (such as, in a cast or sizeof),
12981      compute the type and return it now.  */
12982
12983   if (decl_context == TYPENAME)
12984     {
12985       /* Note that here we don't care about type_quals.  */
12986
12987       /* Special case: "friend class foo" looks like a TYPENAME context.  */
12988       if (friendp)
12989         {
12990           if (inlinep)
12991             {
12992               error ("%<inline%> specified for friend class declaration");
12993               inlinep = 0;
12994             }
12995
12996           if (!current_aggr)
12997             {
12998               /* Don't allow friend declaration without a class-key.  */
12999               if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
13000                 permerror (input_location, "template parameters cannot be friends");
13001               else if (TREE_CODE (type) == TYPENAME_TYPE)
13002                 permerror (input_location, "friend declaration requires class-key, "
13003                            "i.e. %<friend class %T::%D%>",
13004                            TYPE_CONTEXT (type), TYPENAME_TYPE_FULLNAME (type));
13005               else
13006                 permerror (input_location, "friend declaration requires class-key, "
13007                            "i.e. %<friend %#T%>",
13008                            type);
13009             }
13010
13011           /* Only try to do this stuff if we didn't already give up.  */
13012           if (type != integer_type_node)
13013             {
13014               /* A friendly class?  */
13015               if (current_class_type)
13016                 make_friend_class (current_class_type, TYPE_MAIN_VARIANT (type),
13017                                    /*complain=*/true);
13018               else
13019                 error ("trying to make class %qT a friend of global scope",
13020                        type);
13021
13022               type = void_type_node;
13023             }
13024         }
13025       else if (memfn_quals || rqual)
13026         {
13027           if (ctype == NULL_TREE
13028               && TREE_CODE (type) == METHOD_TYPE)
13029             ctype = TYPE_METHOD_BASETYPE (type);
13030
13031           if (ctype)
13032             type = build_memfn_type (type, ctype, memfn_quals, rqual);
13033           /* Core issue #547: need to allow this in template type args.
13034              Allow it in general in C++11 for alias-declarations.  */
13035           else if ((template_type_arg || cxx_dialect >= cxx11)
13036                    && TREE_CODE (type) == FUNCTION_TYPE)
13037             type = apply_memfn_quals (type, memfn_quals, rqual);
13038           else
13039             error ("invalid qualifiers on non-member function type");
13040         }
13041
13042       if (reqs)
13043         error_at (location_of (reqs), "requires-clause on type-id");
13044
13045       return type;
13046     }
13047   else if (unqualified_id == NULL_TREE && decl_context != PARM
13048            && decl_context != CATCHPARM
13049            && TREE_CODE (type) != UNION_TYPE
13050            && ! bitfield
13051            && innermost_code != cdk_decomp)
13052     {
13053       error ("abstract declarator %qT used as declaration", type);
13054       return error_mark_node;
13055     }
13056
13057   if (!FUNC_OR_METHOD_TYPE_P (type))
13058     {
13059       /* Only functions may be declared using an operator-function-id.  */
13060       if (dname && IDENTIFIER_ANY_OP_P (dname))
13061         {
13062           error_at (id_loc, "declaration of %qD as non-function", dname);
13063           return error_mark_node;
13064         }
13065
13066       if (reqs)
13067         error_at (location_of (reqs),
13068                   "requires-clause on declaration of non-function type %qT",
13069                   type);
13070     }
13071
13072   /* We don't check parameter types here because we can emit a better
13073      error message later.  */
13074   if (decl_context != PARM)
13075     {
13076       type = check_var_type (unqualified_id, type, id_loc);
13077       if (type == error_mark_node)
13078         return error_mark_node;
13079     }
13080
13081   /* Now create the decl, which may be a VAR_DECL, a PARM_DECL
13082      or a FUNCTION_DECL, depending on DECL_CONTEXT and TYPE.  */
13083
13084   if (decl_context == PARM || decl_context == CATCHPARM)
13085     {
13086       if (ctype || in_namespace)
13087         error ("cannot use %<::%> in parameter declaration");
13088
13089       tree auto_node = type_uses_auto (type);
13090       if (auto_node && !(cxx_dialect >= cxx17 && template_parm_flag))
13091         {
13092           if (cxx_dialect >= cxx14)
13093             {
13094               if (decl_context == PARM && AUTO_IS_DECLTYPE (auto_node))
13095                 error_at (typespec_loc,
13096                           "cannot declare a parameter with %<decltype(auto)%>");
13097               else
13098                 error_at (typespec_loc,
13099                           "%<auto%> parameter not permitted in this context");
13100             }
13101           else
13102             error_at (typespec_loc, "parameter declared %<auto%>");
13103           type = error_mark_node;
13104         }
13105
13106       /* A parameter declared as an array of T is really a pointer to T.
13107          One declared as a function is really a pointer to a function.
13108          One declared as a member is really a pointer to member.  */
13109
13110       if (TREE_CODE (type) == ARRAY_TYPE)
13111         {
13112           /* Transfer const-ness of array into that of type pointed to.  */
13113           type = build_pointer_type (TREE_TYPE (type));
13114           type_quals = TYPE_UNQUALIFIED;
13115           array_parameter_p = true;
13116         }
13117       else if (TREE_CODE (type) == FUNCTION_TYPE)
13118         type = build_pointer_type (type);
13119     }
13120
13121   if (ctype && TREE_CODE (type) == FUNCTION_TYPE && staticp < 2
13122       && !(unqualified_id
13123            && identifier_p (unqualified_id)
13124            && IDENTIFIER_NEWDEL_OP_P (unqualified_id)))
13125     {
13126       cp_cv_quals real_quals = memfn_quals;
13127       if (cxx_dialect < cxx14 && constexpr_p
13128           && sfk != sfk_constructor && sfk != sfk_destructor)
13129         real_quals |= TYPE_QUAL_CONST;
13130       type = build_memfn_type (type, ctype, real_quals, rqual);
13131     }
13132
13133   {
13134     tree decl = NULL_TREE;
13135
13136     if (decl_context == PARM)
13137       {
13138         decl = cp_build_parm_decl (NULL_TREE, unqualified_id, type);
13139         DECL_ARRAY_PARAMETER_P (decl) = array_parameter_p;
13140
13141         bad_specifiers (decl, BSP_PARM, virtualp,
13142                         memfn_quals != TYPE_UNQUALIFIED,
13143                         inlinep, friendp, raises != NULL_TREE,
13144                         declspecs->locations);
13145       }
13146     else if (decl_context == FIELD)
13147       {
13148         if (!staticp && !friendp && TREE_CODE (type) != METHOD_TYPE)
13149           if (tree auto_node = type_uses_auto (type))
13150             {
13151               location_t tloc = declspecs->locations[ds_type_spec];
13152               if (CLASS_PLACEHOLDER_TEMPLATE (auto_node))
13153                 error_at (tloc, "invalid use of template-name %qE without an "
13154                           "argument list",
13155                           CLASS_PLACEHOLDER_TEMPLATE (auto_node));
13156               else
13157                 error_at (tloc, "non-static data member declared with "
13158                           "placeholder %qT", auto_node);
13159               type = error_mark_node;
13160             }
13161
13162         /* The C99 flexible array extension.  */
13163         if (!staticp && TREE_CODE (type) == ARRAY_TYPE
13164             && TYPE_DOMAIN (type) == NULL_TREE)
13165           {
13166             if (ctype
13167                 && (TREE_CODE (ctype) == UNION_TYPE
13168                     || TREE_CODE (ctype) == QUAL_UNION_TYPE))
13169               {
13170                 error_at (id_loc, "flexible array member in union");
13171                 type = error_mark_node;
13172               }
13173             else
13174               {
13175                 /* Array is a flexible member.  */
13176                 if (name)
13177                   pedwarn (id_loc, OPT_Wpedantic,
13178                            "ISO C++ forbids flexible array member %qs", name);
13179                 else
13180                   pedwarn (input_location, OPT_Wpedantic,
13181                            "ISO C++ forbids flexible array members");
13182
13183                 /* Flexible array member has a null domain.  */
13184                 type = build_cplus_array_type (TREE_TYPE (type), NULL_TREE);
13185               }
13186           }
13187
13188         if (type == error_mark_node)
13189           {
13190             /* Happens when declaring arrays of sizes which
13191                are error_mark_node, for example.  */
13192             decl = NULL_TREE;
13193           }
13194         else if (in_namespace && !friendp)
13195           {
13196             /* Something like struct S { int N::j; };  */
13197             error_at (id_loc, "invalid use of %<::%>");
13198             return error_mark_node;
13199           }
13200         else if (FUNC_OR_METHOD_TYPE_P (type) && unqualified_id)
13201           {
13202             int publicp = 0;
13203             tree function_context;
13204
13205             if (friendp == 0)
13206               {
13207                 /* This should never happen in pure C++ (the check
13208                    could be an assert).  It could happen in
13209                    Objective-C++ if someone writes invalid code that
13210                    uses a function declaration for an instance
13211                    variable or property (instance variables and
13212                    properties are parsed as FIELD_DECLs, but they are
13213                    part of an Objective-C class, not a C++ class).
13214                    That code is invalid and is caught by this
13215                    check.  */
13216                 if (!ctype)
13217                   {
13218                     error ("declaration of function %qD in invalid context",
13219                            unqualified_id);
13220                     return error_mark_node;
13221                   }
13222
13223                 /* ``A union may [ ... ] not [ have ] virtual functions.''
13224                    ARM 9.5 */
13225                 if (virtualp && TREE_CODE (ctype) == UNION_TYPE)
13226                   {
13227                     error_at (declspecs->locations[ds_virtual],
13228                               "function %qD declared %<virtual%> inside a union",
13229                               unqualified_id);
13230                     return error_mark_node;
13231                   }
13232
13233                 if (virtualp
13234                     && identifier_p (unqualified_id)
13235                     && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
13236                   {
13237                     error_at (declspecs->locations[ds_virtual],
13238                               "%qD cannot be declared %<virtual%>, since it "
13239                               "is always static", unqualified_id);
13240                     virtualp = 0;
13241                   }
13242               }
13243
13244             /* Check that the name used for a destructor makes sense.  */
13245             if (sfk == sfk_destructor)
13246               {
13247                 tree uqname = id_declarator->u.id.unqualified_name;
13248
13249                 if (!ctype)
13250                   {
13251                     gcc_assert (friendp);
13252                     error_at (id_loc, "expected qualified name in friend "
13253                               "declaration for destructor %qD", uqname);
13254                     return error_mark_node;
13255                   }
13256
13257                 if (!check_dtor_name (ctype, TREE_OPERAND (uqname, 0)))
13258                   {
13259                     error_at (id_loc, "declaration of %qD as member of %qT",
13260                               uqname, ctype);
13261                     return error_mark_node;
13262                   }
13263                 if (concept_p)
13264                   {
13265                     error_at (declspecs->locations[ds_concept],
13266                               "a destructor cannot be %qs", "concept");
13267                     return error_mark_node;
13268                   }
13269                 if (constexpr_p && cxx_dialect < cxx20)
13270                   {
13271                     error_at (declspecs->locations[ds_constexpr],
13272                               "%<constexpr%> destructors only available"
13273                               " with %<-std=c++20%> or %<-std=gnu++20%>");
13274                     return error_mark_node;
13275                   }
13276                 if (consteval_p)
13277                   {
13278                     error_at (declspecs->locations[ds_consteval],
13279                               "a destructor cannot be %qs", "consteval");
13280                     return error_mark_node;
13281                   }
13282               }
13283             else if (sfk == sfk_constructor && friendp && !ctype)
13284               {
13285                 error ("expected qualified name in friend declaration "
13286                        "for constructor %qD",
13287                        id_declarator->u.id.unqualified_name);
13288                 return error_mark_node;
13289               }
13290             if (sfk == sfk_constructor)
13291               if (concept_p)
13292                 {
13293                   error_at (declspecs->locations[ds_concept],
13294                             "a constructor cannot be %<concept%>");
13295                   return error_mark_node;
13296                 }
13297             if (concept_p)
13298               {
13299                 error_at (declspecs->locations[ds_concept],
13300                           "a concept cannot be a member function");
13301                 concept_p = false;
13302               }
13303             else if (consteval_p
13304                      && identifier_p (unqualified_id)
13305                      && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
13306               {
13307                 error_at (declspecs->locations[ds_consteval],
13308                           "%qD cannot be %qs", unqualified_id, "consteval");
13309                 consteval_p = false;
13310               }
13311
13312             if (TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
13313               {
13314                 tree tmpl = TREE_OPERAND (unqualified_id, 0);
13315                 if (variable_template_p (tmpl))
13316                   {
13317                     error_at (id_loc, "specialization of variable template "
13318                               "%qD declared as function", tmpl);
13319                     inform (DECL_SOURCE_LOCATION (tmpl),
13320                             "variable template declared here");
13321                     return error_mark_node;
13322                   }
13323               }
13324
13325             /* Tell grokfndecl if it needs to set TREE_PUBLIC on the node.  */
13326             function_context
13327               = (ctype != NULL_TREE
13328                  ? decl_function_context (TYPE_MAIN_DECL (ctype)) : NULL_TREE);
13329             publicp = ((! friendp || ! staticp)
13330                        && function_context == NULL_TREE);
13331
13332             decl = grokfndecl (ctype, type,
13333                                TREE_CODE (unqualified_id) != TEMPLATE_ID_EXPR
13334                                ? unqualified_id : dname,
13335                                parms,
13336                                unqualified_id,
13337                                declspecs,
13338                                reqs,
13339                                virtualp, flags, memfn_quals, rqual, raises,
13340                                friendp ? -1 : 0, friendp, publicp,
13341                                inlinep | (2 * constexpr_p) | (4 * concept_p)
13342                                        | (8 * consteval_p),
13343                                initialized == SD_DELETED, sfk,
13344                                funcdef_flag, late_return_type_p,
13345                                template_count, in_namespace,
13346                                attrlist, id_loc);
13347             decl = set_virt_specifiers (decl, virt_specifiers);
13348             if (decl == NULL_TREE)
13349               return error_mark_node;
13350 #if 0
13351             /* This clobbers the attrs stored in `decl' from `attrlist'.  */
13352             /* The decl and setting of decl_attr is also turned off.  */
13353             decl = build_decl_attribute_variant (decl, decl_attr);
13354 #endif
13355
13356             /* [class.conv.ctor]
13357
13358                A constructor declared without the function-specifier
13359                explicit that can be called with a single parameter
13360                specifies a conversion from the type of its first
13361                parameter to the type of its class.  Such a constructor
13362                is called a converting constructor.  */
13363             if (explicitp == 2)
13364               DECL_NONCONVERTING_P (decl) = 1;
13365
13366             if (declspecs->explicit_specifier)
13367               store_explicit_specifier (decl, declspecs->explicit_specifier);
13368           }
13369         else if (!staticp
13370                  && ((current_class_type
13371                       && same_type_p (type, current_class_type))
13372                      || (!dependent_type_p (type)
13373                          && !COMPLETE_TYPE_P (complete_type (type))
13374                          && (!complete_or_array_type_p (type)
13375                              || initialized == SD_UNINITIALIZED))))
13376           {
13377             if (TREE_CODE (type) != ARRAY_TYPE
13378                 || !COMPLETE_TYPE_P (TREE_TYPE (type)))
13379               {
13380                 if (unqualified_id)
13381                   {
13382                     error_at (id_loc, "field %qD has incomplete type %qT",
13383                               unqualified_id, type);
13384                     cxx_incomplete_type_inform (strip_array_types (type));
13385                   }
13386                 else
13387                   error ("name %qT has incomplete type", type);
13388
13389                 type = error_mark_node;
13390                 decl = NULL_TREE;
13391               }
13392           }
13393         else if (!verify_type_context (input_location,
13394                                        staticp
13395                                        ? TCTX_STATIC_STORAGE
13396                                        : TCTX_FIELD, type))
13397           {
13398             type = error_mark_node;
13399             decl = NULL_TREE;
13400           }
13401         else
13402           {
13403             if (friendp)
13404               {
13405                 if (unqualified_id)
13406                   error_at (id_loc,
13407                             "%qE is neither function nor member function; "
13408                             "cannot be declared friend", unqualified_id);
13409                 else
13410                   error ("unnamed field is neither function nor member "
13411                          "function; cannot be declared friend");
13412                 return error_mark_node;
13413               }
13414             decl = NULL_TREE;
13415           }
13416
13417         if (friendp)
13418           {
13419             /* Friends are treated specially.  */
13420             if (ctype == current_class_type)
13421               ;  /* We already issued a permerror.  */
13422             else if (decl && DECL_NAME (decl))
13423               {
13424                 if (initialized)
13425                   /* Kludge: We need funcdef_flag to be true in do_friend for
13426                      in-class defaulted functions, but that breaks grokfndecl.
13427                      So set it here.  */
13428                   funcdef_flag = true;
13429
13430                 if (template_class_depth (current_class_type) == 0)
13431                   {
13432                     decl = check_explicit_specialization
13433                       (unqualified_id, decl, template_count,
13434                        2 * funcdef_flag + 4);
13435                     if (decl == error_mark_node)
13436                       return error_mark_node;
13437                   }
13438
13439                 decl = do_friend (ctype, unqualified_id, decl,
13440                                   *attrlist, flags,
13441                                   funcdef_flag);
13442                 return decl;
13443               }
13444             else
13445               return error_mark_node;
13446           }
13447
13448         /* Structure field.  It may not be a function, except for C++.  */
13449
13450         if (decl == NULL_TREE)
13451           {
13452             if (staticp)
13453               {
13454                 /* C++ allows static class members.  All other work
13455                    for this is done by grokfield.  */
13456                 decl = build_lang_decl_loc (id_loc, VAR_DECL,
13457                                             unqualified_id, type);
13458                 set_linkage_for_static_data_member (decl);
13459                 if (concept_p)
13460                   error_at (declspecs->locations[ds_concept],
13461                             "static data member %qE declared %qs",
13462                             unqualified_id, "concept");
13463                 else if (constexpr_p && !initialized)
13464                   {
13465                     error_at (DECL_SOURCE_LOCATION (decl),
13466                               "%<constexpr%> static data member %qD must "
13467                               "have an initializer", decl);
13468                     constexpr_p = false;
13469                   }
13470                 if (consteval_p)
13471                   error_at (declspecs->locations[ds_consteval],
13472                             "static data member %qE declared %qs",
13473                             unqualified_id, "consteval");
13474
13475                 if (inlinep)
13476                   mark_inline_variable (decl, declspecs->locations[ds_inline]);
13477
13478                 if (!DECL_VAR_DECLARED_INLINE_P (decl)
13479                     && !(cxx_dialect >= cxx17 && constexpr_p))
13480                   /* Even if there is an in-class initialization, DECL
13481                      is considered undefined until an out-of-class
13482                      definition is provided, unless this is an inline
13483                      variable.  */
13484                   DECL_EXTERNAL (decl) = 1;
13485
13486                 if (thread_p)
13487                   {
13488                     CP_DECL_THREAD_LOCAL_P (decl) = true;
13489                     if (!processing_template_decl)
13490                       set_decl_tls_model (decl, decl_default_tls_model (decl));
13491                     if (declspecs->gnu_thread_keyword_p)
13492                       SET_DECL_GNU_TLS_P (decl);
13493                   }
13494               }
13495             else
13496               {
13497                 if (concept_p)
13498                   {
13499                     error_at (declspecs->locations[ds_concept],
13500                               "non-static data member %qE declared %qs",
13501                               unqualified_id, "concept");
13502                     concept_p = false;
13503                     constexpr_p = false;
13504                   }
13505                 else if (constexpr_p)
13506                   {
13507                     error_at (declspecs->locations[ds_constexpr],
13508                               "non-static data member %qE declared %qs",
13509                               unqualified_id, "constexpr");
13510                     constexpr_p = false;
13511                   }
13512                 if (constinit_p)
13513                   {
13514                     error_at (declspecs->locations[ds_constinit],
13515                               "non-static data member %qE declared %qs",
13516                               unqualified_id, "constinit");
13517                     constinit_p = false;
13518                   }
13519                 if (consteval_p)
13520                   {
13521                     error_at (declspecs->locations[ds_consteval],
13522                               "non-static data member %qE declared %qs",
13523                               unqualified_id, "consteval");
13524                     consteval_p = false;
13525                   }
13526                 decl = build_decl (id_loc, FIELD_DECL, unqualified_id, type);
13527                 DECL_NONADDRESSABLE_P (decl) = bitfield;
13528                 if (bitfield && !unqualified_id)
13529                   {
13530                     TREE_NO_WARNING (decl) = 1;
13531                     DECL_PADDING_P (decl) = 1;
13532                   }
13533
13534                 if (storage_class == sc_mutable)
13535                   {
13536                     DECL_MUTABLE_P (decl) = 1;
13537                     storage_class = sc_none;
13538                   }
13539
13540                 if (initialized)
13541                   {
13542                     /* An attempt is being made to initialize a non-static
13543                        member.  This is new in C++11.  */
13544                     maybe_warn_cpp0x (CPP0X_NSDMI);
13545
13546                     /* If this has been parsed with static storage class, but
13547                        errors forced staticp to be cleared, ensure NSDMI is
13548                        not present.  */
13549                     if (declspecs->storage_class == sc_static)
13550                       DECL_INITIAL (decl) = error_mark_node;
13551                   }
13552               }
13553
13554             bad_specifiers (decl, BSP_FIELD, virtualp,
13555                             memfn_quals != TYPE_UNQUALIFIED,
13556                             staticp ? false : inlinep, friendp,
13557                             raises != NULL_TREE,
13558                             declspecs->locations);
13559           }
13560       }
13561     else if (FUNC_OR_METHOD_TYPE_P (type))
13562       {
13563         tree original_name;
13564         int publicp = 0;
13565
13566         if (!unqualified_id)
13567           return error_mark_node;
13568
13569         if (TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
13570           original_name = dname;
13571         else
13572           original_name = unqualified_id;
13573         // FIXME:gcc_assert (original_name == dname);
13574
13575         if (storage_class == sc_auto)
13576           error_at (declspecs->locations[ds_storage_class],
13577                     "storage class %<auto%> invalid for function %qs", name);
13578         else if (storage_class == sc_register)
13579           error_at (declspecs->locations[ds_storage_class],
13580                     "storage class %<register%> invalid for function %qs",
13581                     name);
13582         else if (thread_p)
13583           {
13584             if (declspecs->gnu_thread_keyword_p)
13585               error_at (declspecs->locations[ds_thread],
13586                         "storage class %<__thread%> invalid for function %qs",
13587                         name);
13588             else
13589               error_at (declspecs->locations[ds_thread],
13590                         "storage class %<thread_local%> invalid for "
13591                         "function %qs", name);
13592           }
13593
13594         if (virt_specifiers)
13595           error ("virt-specifiers in %qs not allowed outside a class "
13596                  "definition", name);
13597         /* Function declaration not at top level.
13598            Storage classes other than `extern' are not allowed
13599            and `extern' makes no difference.  */
13600         if (! toplevel_bindings_p ()
13601             && (storage_class == sc_static
13602                 || decl_spec_seq_has_spec_p (declspecs, ds_inline))
13603             && pedantic)
13604           {
13605             if (storage_class == sc_static)
13606               pedwarn (declspecs->locations[ds_storage_class], OPT_Wpedantic, 
13607                        "%<static%> specifier invalid for function %qs "
13608                        "declared out of global scope", name);
13609             else
13610               pedwarn (declspecs->locations[ds_inline], OPT_Wpedantic, 
13611                        "%<inline%> specifier invalid for function %qs "
13612                        "declared out of global scope", name);
13613           }
13614
13615         if (ctype == NULL_TREE)
13616           {
13617             if (virtualp)
13618               {
13619                 error ("virtual non-class function %qs", name);
13620                 virtualp = 0;
13621               }
13622             else if (sfk == sfk_constructor
13623                      || sfk == sfk_destructor)
13624               {
13625                 error (funcdef_flag
13626                        ? G_("%qs defined in a non-class scope")
13627                        : G_("%qs declared in a non-class scope"), name);
13628                 sfk = sfk_none;
13629               }
13630           }
13631         if (consteval_p
13632             && identifier_p (unqualified_id)
13633             && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
13634           {
13635             error_at (declspecs->locations[ds_consteval],
13636                       "%qD cannot be %qs", unqualified_id, "consteval");
13637             consteval_p = false;
13638           }
13639
13640         /* Record whether the function is public.  */
13641         publicp = (ctype != NULL_TREE
13642                    || storage_class != sc_static);
13643
13644         decl = grokfndecl (ctype, type, original_name, parms, unqualified_id,
13645                            declspecs,
13646                            reqs, virtualp, flags, memfn_quals, rqual, raises,
13647                            1, friendp,
13648                            publicp,
13649                            inlinep | (2 * constexpr_p) | (4 * concept_p)
13650                                    | (8 * consteval_p),
13651                            initialized == SD_DELETED,
13652                            sfk,
13653                            funcdef_flag,
13654                            late_return_type_p,
13655                            template_count, in_namespace, attrlist,
13656                            id_loc);
13657         if (decl == NULL_TREE)
13658           return error_mark_node;
13659
13660         if (explicitp == 2)
13661           DECL_NONCONVERTING_P (decl) = 1;
13662         if (staticp == 1)
13663           {
13664             int invalid_static = 0;
13665
13666             /* Don't allow a static member function in a class, and forbid
13667                declaring main to be static.  */
13668             if (TREE_CODE (type) == METHOD_TYPE)
13669               {
13670                 permerror (input_location, "cannot declare member function %qD to have "
13671                            "static linkage", decl);
13672                 invalid_static = 1;
13673               }
13674             else if (current_function_decl)
13675               {
13676                 /* 7.1.1: There can be no static function declarations within a
13677                    block.  */
13678                 error_at (declspecs->locations[ds_storage_class],
13679                           "cannot declare static function inside another function");
13680                 invalid_static = 1;
13681               }
13682
13683             if (invalid_static)
13684               {
13685                 staticp = 0;
13686                 storage_class = sc_none;
13687               }
13688           }
13689       }
13690     else
13691       {
13692         /* It's a variable.  */
13693
13694         /* An uninitialized decl with `extern' is a reference.  */
13695         decl = grokvardecl (type, dname, unqualified_id,
13696                             declspecs,
13697                             initialized,
13698                             type_quals,
13699                             inlinep,
13700                             concept_p,
13701                             template_count,
13702                             ctype ? ctype : in_namespace,
13703                             id_loc);
13704         if (decl == NULL_TREE)
13705           return error_mark_node;
13706
13707         bad_specifiers (decl, BSP_VAR, virtualp,
13708                         memfn_quals != TYPE_UNQUALIFIED,
13709                         inlinep, friendp, raises != NULL_TREE,
13710                         declspecs->locations);
13711
13712         if (ctype)
13713           {
13714             DECL_CONTEXT (decl) = ctype;
13715             if (staticp == 1)
13716               {
13717                 permerror (declspecs->locations[ds_storage_class],
13718                            "%<static%> may not be used when defining "
13719                            "(as opposed to declaring) a static data member");
13720                 staticp = 0;
13721                 storage_class = sc_none;
13722               }
13723             if (storage_class == sc_register && TREE_STATIC (decl))
13724               {
13725                 error ("static member %qD declared %<register%>", decl);
13726                 storage_class = sc_none;
13727               }
13728             if (storage_class == sc_extern && pedantic)
13729               {
13730                 pedwarn (input_location, OPT_Wpedantic, 
13731                          "cannot explicitly declare member %q#D to have "
13732                          "extern linkage", decl);
13733                 storage_class = sc_none;
13734               }
13735           }
13736         else if (constexpr_p && DECL_EXTERNAL (decl))
13737           {
13738             error_at (DECL_SOURCE_LOCATION (decl),
13739                       "declaration of %<constexpr%> variable %qD "
13740                       "is not a definition", decl);
13741             constexpr_p = false;
13742           }
13743         if (consteval_p)
13744           {
13745             error_at (DECL_SOURCE_LOCATION (decl),
13746                       "a variable cannot be declared %<consteval%>");
13747             consteval_p = false;
13748           }
13749
13750         if (inlinep)
13751           mark_inline_variable (decl, declspecs->locations[ds_inline]);
13752         if (innermost_code == cdk_decomp)
13753           {
13754             gcc_assert (declarator && declarator->kind == cdk_decomp);
13755             DECL_SOURCE_LOCATION (decl) = id_loc;
13756             DECL_ARTIFICIAL (decl) = 1;
13757             fit_decomposition_lang_decl (decl, NULL_TREE);
13758           }
13759       }
13760
13761     if (VAR_P (decl) && !initialized)
13762       if (tree auto_node = type_uses_auto (type))
13763         if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
13764           {
13765             location_t loc = declspecs->locations[ds_type_spec];
13766             error_at (loc, "declaration of %q#D has no initializer", decl);
13767             TREE_TYPE (decl) = error_mark_node;
13768           }
13769
13770     if (storage_class == sc_extern && initialized && !funcdef_flag)
13771       {
13772         if (toplevel_bindings_p ())
13773           {
13774             /* It's common practice (and completely valid) to have a const
13775                be initialized and declared extern.  */
13776             if (!(type_quals & TYPE_QUAL_CONST))
13777               warning_at (DECL_SOURCE_LOCATION (decl), 0,
13778                           "%qs initialized and declared %<extern%>", name);
13779           }
13780         else
13781           {
13782             error_at (DECL_SOURCE_LOCATION (decl),
13783                       "%qs has both %<extern%> and initializer", name);
13784             return error_mark_node;
13785           }
13786       }
13787
13788     /* Record `register' declaration for warnings on &
13789        and in case doing stupid register allocation.  */
13790
13791     if (storage_class == sc_register)
13792       {
13793         DECL_REGISTER (decl) = 1;
13794         /* Warn about register storage specifiers on PARM_DECLs.  */
13795         if (TREE_CODE (decl) == PARM_DECL)
13796           {
13797             if (cxx_dialect >= cxx17)
13798               pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
13799                        "ISO C++17 does not allow %<register%> storage "
13800                        "class specifier");
13801             else
13802               warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
13803                           "%<register%> storage class specifier used");
13804           }
13805       }
13806     else if (storage_class == sc_extern)
13807       DECL_THIS_EXTERN (decl) = 1;
13808     else if (storage_class == sc_static)
13809       DECL_THIS_STATIC (decl) = 1;
13810
13811     if (VAR_P (decl))
13812       {
13813         /* Set constexpr flag on vars (functions got it in grokfndecl).  */
13814         if (constexpr_p)
13815           DECL_DECLARED_CONSTEXPR_P (decl) = true;
13816         /* And the constinit flag (which only applies to variables).  */
13817         else if (constinit_p)
13818           DECL_DECLARED_CONSTINIT_P (decl) = true;
13819       }
13820
13821     /* Record constancy and volatility on the DECL itself .  There's
13822        no need to do this when processing a template; we'll do this
13823        for the instantiated declaration based on the type of DECL.  */
13824     if (!processing_template_decl)
13825       cp_apply_type_quals_to_decl (type_quals, decl);
13826
13827     return decl;
13828   }
13829 }
13830 \f
13831 /* Subroutine of start_function.  Ensure that each of the parameter
13832    types (as listed in PARMS) is complete, as is required for a
13833    function definition.  */
13834
13835 static void
13836 require_complete_types_for_parms (tree parms)
13837 {
13838   for (; parms; parms = DECL_CHAIN (parms))
13839     {
13840       if (dependent_type_p (TREE_TYPE (parms)))
13841         continue;
13842       if (!VOID_TYPE_P (TREE_TYPE (parms))
13843           && complete_type_or_else (TREE_TYPE (parms), parms))
13844         {
13845           relayout_decl (parms);
13846           DECL_ARG_TYPE (parms) = type_passed_as (TREE_TYPE (parms));
13847
13848           maybe_warn_parm_abi (TREE_TYPE (parms),
13849                                DECL_SOURCE_LOCATION (parms));
13850         }
13851       else
13852         /* grokparms or complete_type_or_else will have already issued
13853            an error.  */
13854         TREE_TYPE (parms) = error_mark_node;
13855     }
13856 }
13857
13858 /* Returns nonzero if T is a local variable.  */
13859
13860 int
13861 local_variable_p (const_tree t)
13862 {
13863   if ((VAR_P (t)
13864        && (DECL_LOCAL_DECL_P (t)
13865            || !DECL_CONTEXT (t)
13866            || TREE_CODE (DECL_CONTEXT (t)) == FUNCTION_DECL))
13867       || (TREE_CODE (t) == PARM_DECL))
13868     return 1;
13869
13870   return 0;
13871 }
13872
13873 /* Like local_variable_p, but suitable for use as a tree-walking
13874    function.  */
13875
13876 static tree
13877 local_variable_p_walkfn (tree *tp, int *walk_subtrees,
13878                          void * /*data*/)
13879 {
13880   if (local_variable_p (*tp)
13881       && (!DECL_ARTIFICIAL (*tp) || DECL_NAME (*tp) == this_identifier))
13882     return *tp;
13883   else if (TYPE_P (*tp))
13884     *walk_subtrees = 0;
13885
13886   return NULL_TREE;
13887 }
13888
13889 /* Check that ARG, which is a default-argument expression for a
13890    parameter DECL, is valid.  Returns ARG, or ERROR_MARK_NODE, if
13891    something goes wrong.  DECL may also be a _TYPE node, rather than a
13892    DECL, if there is no DECL available.  */
13893
13894 tree
13895 check_default_argument (tree decl, tree arg, tsubst_flags_t complain)
13896 {
13897   tree var;
13898   tree decl_type;
13899
13900   if (TREE_CODE (arg) == DEFERRED_PARSE)
13901     /* We get a DEFERRED_PARSE when looking at an in-class declaration
13902        with a default argument.  Ignore the argument for now; we'll
13903        deal with it after the class is complete.  */
13904     return arg;
13905
13906   if (TYPE_P (decl))
13907     {
13908       decl_type = decl;
13909       decl = NULL_TREE;
13910     }
13911   else
13912     decl_type = TREE_TYPE (decl);
13913
13914   if (arg == error_mark_node
13915       || decl == error_mark_node
13916       || TREE_TYPE (arg) == error_mark_node
13917       || decl_type == error_mark_node)
13918     /* Something already went wrong.  There's no need to check
13919        further.  */
13920     return error_mark_node;
13921
13922   /* [dcl.fct.default]
13923
13924      A default argument expression is implicitly converted to the
13925      parameter type.  */
13926   ++cp_unevaluated_operand;
13927   /* Avoid digest_init clobbering the initializer.  */
13928   tree carg = BRACE_ENCLOSED_INITIALIZER_P (arg) ? unshare_expr (arg): arg;
13929   perform_implicit_conversion_flags (decl_type, carg, complain,
13930                                      LOOKUP_IMPLICIT);
13931   --cp_unevaluated_operand;
13932
13933   /* Avoid redundant -Wzero-as-null-pointer-constant warnings at
13934      the call sites.  */
13935   if (TYPE_PTR_OR_PTRMEM_P (decl_type)
13936       && null_ptr_cst_p (arg)
13937       /* Don't lose side-effects as in PR90473.  */
13938       && !TREE_SIDE_EFFECTS (arg))
13939     return nullptr_node;
13940
13941   /* [dcl.fct.default]
13942
13943      Local variables shall not be used in default argument
13944      expressions.
13945
13946      The keyword `this' shall not be used in a default argument of a
13947      member function.  */
13948   var = cp_walk_tree_without_duplicates (&arg, local_variable_p_walkfn, NULL);
13949   if (var)
13950     {
13951       if (complain & tf_warning_or_error)
13952         {
13953           if (DECL_NAME (var) == this_identifier)
13954             permerror (input_location, "default argument %qE uses %qD",
13955                        arg, var);
13956           else
13957             error ("default argument %qE uses local variable %qD", arg, var);
13958         }
13959       return error_mark_node;
13960     }
13961
13962   /* All is well.  */
13963   return arg;
13964 }
13965
13966 /* Returns a deprecated type used within TYPE, or NULL_TREE if none.  */
13967
13968 static tree
13969 type_is_deprecated (tree type)
13970 {
13971   enum tree_code code;
13972   if (TREE_DEPRECATED (type))
13973     return type;
13974   if (TYPE_NAME (type))
13975     {
13976       if (TREE_DEPRECATED (TYPE_NAME (type)))
13977         return type;
13978       else
13979         {
13980           cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (TYPE_NAME (type)));
13981           return NULL_TREE;
13982         }
13983     }
13984
13985   /* Do warn about using typedefs to a deprecated class.  */
13986   if (OVERLOAD_TYPE_P (type) && type != TYPE_MAIN_VARIANT (type))
13987     return type_is_deprecated (TYPE_MAIN_VARIANT (type));
13988
13989   code = TREE_CODE (type);
13990
13991   if (code == POINTER_TYPE || code == REFERENCE_TYPE
13992       || code == OFFSET_TYPE || code == FUNCTION_TYPE
13993       || code == METHOD_TYPE || code == ARRAY_TYPE)
13994     return type_is_deprecated (TREE_TYPE (type));
13995
13996   if (TYPE_PTRMEMFUNC_P (type))
13997     return type_is_deprecated
13998       (TREE_TYPE (TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (type))));
13999
14000   return NULL_TREE;
14001 }
14002
14003 /* Decode the list of parameter types for a function type.
14004    Given the list of things declared inside the parens,
14005    return a list of types.
14006
14007    If this parameter does not end with an ellipsis, we append
14008    void_list_node.
14009
14010    *PARMS is set to the chain of PARM_DECLs created.  */
14011
14012 tree
14013 grokparms (tree parmlist, tree *parms)
14014 {
14015   tree result = NULL_TREE;
14016   tree decls = NULL_TREE;
14017   tree parm;
14018   int any_error = 0;
14019
14020   for (parm = parmlist; parm != NULL_TREE; parm = TREE_CHAIN (parm))
14021     {
14022       tree type = NULL_TREE;
14023       tree init = TREE_PURPOSE (parm);
14024       tree decl = TREE_VALUE (parm);
14025
14026       if (parm == void_list_node)
14027         break;
14028
14029       if (! decl || TREE_TYPE (decl) == error_mark_node)
14030         {
14031           any_error = 1;
14032           continue;
14033         }
14034
14035       type = TREE_TYPE (decl);
14036       if (VOID_TYPE_P (type))
14037         {
14038           if (same_type_p (type, void_type_node)
14039               && !init
14040               && !DECL_NAME (decl) && !result
14041               && TREE_CHAIN (parm) == void_list_node)
14042             /* DR 577: A parameter list consisting of a single
14043                unnamed parameter of non-dependent type 'void'.  */
14044             break;
14045           else if (cv_qualified_p (type))
14046             error_at (DECL_SOURCE_LOCATION (decl),
14047                       "invalid use of cv-qualified type %qT in "
14048                       "parameter declaration", type);
14049           else
14050             error_at (DECL_SOURCE_LOCATION (decl),
14051                       "invalid use of type %<void%> in parameter "
14052                       "declaration");
14053           /* It's not a good idea to actually create parameters of
14054              type `void'; other parts of the compiler assume that a
14055              void type terminates the parameter list.  */
14056           type = error_mark_node;
14057           TREE_TYPE (decl) = error_mark_node;
14058         }
14059
14060       if (type != error_mark_node)
14061         {
14062           if (deprecated_state != DEPRECATED_SUPPRESS)
14063             {
14064               tree deptype = type_is_deprecated (type);
14065               if (deptype)
14066                 cp_warn_deprecated_use (deptype);
14067             }
14068
14069           /* [dcl.fct] "A parameter with volatile-qualified type is
14070              deprecated."  */
14071           if (CP_TYPE_VOLATILE_P (type))
14072             warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wvolatile,
14073                         "%<volatile%>-qualified parameter is "
14074                         "deprecated");
14075
14076           /* Top-level qualifiers on the parameters are
14077              ignored for function types.  */
14078           type = cp_build_qualified_type (type, 0);
14079           if (TREE_CODE (type) == METHOD_TYPE)
14080             {
14081               error ("parameter %qD invalidly declared method type", decl);
14082               type = build_pointer_type (type);
14083               TREE_TYPE (decl) = type;
14084             }
14085           else if (abstract_virtuals_error (decl, type))
14086             /* Ignore any default argument.  */
14087             init = NULL_TREE;
14088           else if (cxx_dialect < cxx17 && INDIRECT_TYPE_P (type))
14089             {
14090               /* Before C++17 DR 393:
14091                  [dcl.fct]/6, parameter types cannot contain pointers
14092                  (references) to arrays of unknown bound.  */
14093               tree t = TREE_TYPE (type);
14094               int ptr = TYPE_PTR_P (type);
14095
14096               while (1)
14097                 {
14098                   if (TYPE_PTR_P (t))
14099                     ptr = 1;
14100                   else if (TREE_CODE (t) != ARRAY_TYPE)
14101                     break;
14102                   else if (!TYPE_DOMAIN (t))
14103                     break;
14104                   t = TREE_TYPE (t);
14105                 }
14106               if (TREE_CODE (t) == ARRAY_TYPE)
14107                 pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wpedantic,
14108                          ptr
14109                          ? G_("parameter %qD includes pointer to array of "
14110                               "unknown bound %qT")
14111                          : G_("parameter %qD includes reference to array of "
14112                               "unknown bound %qT"),
14113                          decl, t);
14114             }
14115
14116           if (init && !processing_template_decl)
14117             init = check_default_argument (decl, init, tf_warning_or_error);
14118         }
14119
14120       DECL_CHAIN (decl) = decls;
14121       decls = decl;
14122       result = tree_cons (init, type, result);
14123     }
14124   decls = nreverse (decls);
14125   result = nreverse (result);
14126   if (parm)
14127     result = chainon (result, void_list_node);
14128   *parms = decls;
14129   if (any_error)
14130     result = NULL_TREE;
14131
14132   if (any_error)
14133     /* We had parm errors, recover by giving the function (...) type.  */
14134     result = NULL_TREE;
14135
14136   return result;
14137 }
14138
14139 \f
14140 /* D is a constructor or overloaded `operator='.
14141
14142    Let T be the class in which D is declared. Then, this function
14143    returns:
14144
14145    -1 if D's is an ill-formed constructor or copy assignment operator
14146       whose first parameter is of type `T'.
14147    0  if D is not a copy constructor or copy assignment
14148       operator.
14149    1  if D is a copy constructor or copy assignment operator whose
14150       first parameter is a reference to non-const qualified T.
14151    2  if D is a copy constructor or copy assignment operator whose
14152       first parameter is a reference to const qualified T.
14153
14154    This function can be used as a predicate. Positive values indicate
14155    a copy constructor and nonzero values indicate a copy assignment
14156    operator.  */
14157
14158 int
14159 copy_fn_p (const_tree d)
14160 {
14161   tree args;
14162   tree arg_type;
14163   int result = 1;
14164
14165   gcc_assert (DECL_FUNCTION_MEMBER_P (d));
14166
14167   if (TREE_CODE (d) == TEMPLATE_DECL
14168       || (DECL_TEMPLATE_INFO (d)
14169           && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (d))))
14170     /* Instantiations of template member functions are never copy
14171        functions.  Note that member functions of templated classes are
14172        represented as template functions internally, and we must
14173        accept those as copy functions.  */
14174     return 0;
14175
14176   args = FUNCTION_FIRST_USER_PARMTYPE (d);
14177   if (!args)
14178     return 0;
14179
14180   arg_type = TREE_VALUE (args);
14181   if (arg_type == error_mark_node)
14182     return 0;
14183
14184   if (TYPE_MAIN_VARIANT (arg_type) == DECL_CONTEXT (d))
14185     {
14186       /* Pass by value copy assignment operator.  */
14187       result = -1;
14188     }
14189   else if (TYPE_REF_P (arg_type)
14190            && !TYPE_REF_IS_RVALUE (arg_type)
14191            && TYPE_MAIN_VARIANT (TREE_TYPE (arg_type)) == DECL_CONTEXT (d))
14192     {
14193       if (CP_TYPE_CONST_P (TREE_TYPE (arg_type)))
14194         result = 2;
14195     }
14196   else
14197     return 0;
14198
14199   args = TREE_CHAIN (args);
14200
14201   if (args && args != void_list_node && !TREE_PURPOSE (args))
14202     /* There are more non-optional args.  */
14203     return 0;
14204
14205   return result;
14206 }
14207
14208 /* D is a constructor or overloaded `operator='.
14209
14210    Let T be the class in which D is declared. Then, this function
14211    returns true when D is a move constructor or move assignment
14212    operator, false otherwise.  */
14213
14214 bool
14215 move_fn_p (const_tree d)
14216 {
14217   gcc_assert (DECL_FUNCTION_MEMBER_P (d));
14218
14219   if (cxx_dialect == cxx98)
14220     /* There are no move constructors if we are in C++98 mode.  */
14221     return false;
14222
14223   if (TREE_CODE (d) == TEMPLATE_DECL
14224       || (DECL_TEMPLATE_INFO (d)
14225          && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (d))))
14226     /* Instantiations of template member functions are never move
14227        functions.  Note that member functions of templated classes are
14228        represented as template functions internally, and we must
14229        accept those as move functions.  */
14230     return 0;
14231
14232   return move_signature_fn_p (d);
14233 }
14234
14235 /* D is a constructor or overloaded `operator='.
14236
14237    Then, this function returns true when D has the same signature as a move
14238    constructor or move assignment operator (because either it is such a
14239    ctor/op= or it is a template specialization with the same signature),
14240    false otherwise.  */
14241
14242 bool
14243 move_signature_fn_p (const_tree d)
14244 {
14245   tree args;
14246   tree arg_type;
14247   bool result = false;
14248
14249   args = FUNCTION_FIRST_USER_PARMTYPE (d);
14250   if (!args)
14251     return 0;
14252
14253   arg_type = TREE_VALUE (args);
14254   if (arg_type == error_mark_node)
14255     return 0;
14256
14257   if (TYPE_REF_P (arg_type)
14258       && TYPE_REF_IS_RVALUE (arg_type)
14259       && same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (arg_type)),
14260                       DECL_CONTEXT (d)))
14261     result = true;
14262
14263   args = TREE_CHAIN (args);
14264
14265   if (args && args != void_list_node && !TREE_PURPOSE (args))
14266     /* There are more non-optional args.  */
14267     return false;
14268
14269   return result;
14270 }
14271
14272 /* Remember any special properties of member function DECL.  */
14273
14274 void
14275 grok_special_member_properties (tree decl)
14276 {
14277   tree class_type;
14278
14279   if (TREE_CODE (decl) == USING_DECL
14280       || !DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
14281     return;
14282
14283   class_type = DECL_CONTEXT (decl);
14284   if (IDENTIFIER_CTOR_P (DECL_NAME (decl)))
14285     {
14286       int ctor = copy_fn_p (decl);
14287
14288       if (!DECL_ARTIFICIAL (decl))
14289         TYPE_HAS_USER_CONSTRUCTOR (class_type) = 1;
14290
14291       if (ctor > 0)
14292         {
14293           /* [class.copy]
14294
14295              A non-template constructor for class X is a copy
14296              constructor if its first parameter is of type X&, const
14297              X&, volatile X& or const volatile X&, and either there
14298              are no other parameters or else all other parameters have
14299              default arguments.  */
14300           TYPE_HAS_COPY_CTOR (class_type) = 1;
14301           if (ctor > 1)
14302             TYPE_HAS_CONST_COPY_CTOR (class_type) = 1;
14303         }
14304       else if (sufficient_parms_p (FUNCTION_FIRST_USER_PARMTYPE (decl)))
14305         TYPE_HAS_DEFAULT_CONSTRUCTOR (class_type) = 1;
14306       else if (is_list_ctor (decl))
14307         TYPE_HAS_LIST_CTOR (class_type) = 1;
14308
14309       if (DECL_DECLARED_CONSTEXPR_P (decl)
14310           && !ctor && !move_fn_p (decl))
14311         TYPE_HAS_CONSTEXPR_CTOR (class_type) = 1;
14312     }
14313   else if (DECL_NAME (decl) == assign_op_identifier)
14314     {
14315       /* [class.copy]
14316
14317          A non-template assignment operator for class X is a copy
14318          assignment operator if its parameter is of type X, X&, const
14319          X&, volatile X& or const volatile X&.  */
14320
14321       int assop = copy_fn_p (decl);
14322
14323       if (assop)
14324         {
14325           TYPE_HAS_COPY_ASSIGN (class_type) = 1;
14326           if (assop != 1)
14327             TYPE_HAS_CONST_COPY_ASSIGN (class_type) = 1;
14328         }
14329     }
14330   else if (IDENTIFIER_CONV_OP_P (DECL_NAME (decl)))
14331     TYPE_HAS_CONVERSION (class_type) = true;
14332   
14333   /* Destructors are handled in check_methods.  */
14334 }
14335
14336 /* Check a constructor DECL has the correct form.  Complains
14337    if the class has a constructor of the form X(X).  */
14338
14339 bool
14340 grok_ctor_properties (const_tree ctype, const_tree decl)
14341 {
14342   int ctor_parm = copy_fn_p (decl);
14343
14344   if (ctor_parm < 0)
14345     {
14346       /* [class.copy]
14347
14348          A declaration of a constructor for a class X is ill-formed if
14349          its first parameter is of type (optionally cv-qualified) X
14350          and either there are no other parameters or else all other
14351          parameters have default arguments.
14352
14353          We *don't* complain about member template instantiations that
14354          have this form, though; they can occur as we try to decide
14355          what constructor to use during overload resolution.  Since
14356          overload resolution will never prefer such a constructor to
14357          the non-template copy constructor (which is either explicitly
14358          or implicitly defined), there's no need to worry about their
14359          existence.  Theoretically, they should never even be
14360          instantiated, but that's hard to forestall.  */
14361       error_at (DECL_SOURCE_LOCATION (decl),
14362                 "invalid constructor; you probably meant %<%T (const %T&)%>",
14363                 ctype, ctype);
14364       return false;
14365     }
14366
14367   return true;
14368 }
14369
14370 /* DECL is a declaration for an overloaded or conversion operator.  If
14371    COMPLAIN is true, errors are issued for invalid declarations.  */
14372
14373 bool
14374 grok_op_properties (tree decl, bool complain)
14375 {
14376   tree argtypes = TYPE_ARG_TYPES (TREE_TYPE (decl));
14377   bool methodp = TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE;
14378   tree name = DECL_NAME (decl);
14379   location_t loc = DECL_SOURCE_LOCATION (decl);
14380
14381   tree class_type = DECL_CONTEXT (decl);
14382   if (class_type && !CLASS_TYPE_P (class_type))
14383     class_type = NULL_TREE;
14384
14385   tree_code operator_code;
14386   unsigned op_flags;
14387   if (IDENTIFIER_CONV_OP_P (name))
14388     {
14389       /* Conversion operators are TYPE_EXPR for the purposes of this
14390          function.  */
14391       operator_code = TYPE_EXPR;
14392       op_flags = OVL_OP_FLAG_UNARY;
14393     }
14394   else
14395     {
14396       const ovl_op_info_t *ovl_op = IDENTIFIER_OVL_OP_INFO (name);
14397
14398       operator_code = ovl_op->tree_code;
14399       op_flags = ovl_op->flags;
14400       gcc_checking_assert (operator_code != ERROR_MARK);
14401       DECL_OVERLOADED_OPERATOR_CODE_RAW (decl) = ovl_op->ovl_op_code;
14402     }
14403
14404   if (op_flags & OVL_OP_FLAG_ALLOC)
14405     {
14406       /* operator new and operator delete are quite special.  */
14407       if (class_type)
14408         switch (op_flags)
14409           {
14410           case OVL_OP_FLAG_ALLOC:
14411             TYPE_HAS_NEW_OPERATOR (class_type) = 1;
14412             break;
14413
14414           case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_DELETE:
14415             TYPE_GETS_DELETE (class_type) |= 1;
14416             break;
14417
14418           case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_VEC:
14419             TYPE_HAS_ARRAY_NEW_OPERATOR (class_type) = 1;
14420             break;
14421
14422           case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_DELETE | OVL_OP_FLAG_VEC:
14423             TYPE_GETS_DELETE (class_type) |= 2;
14424             break;
14425
14426           default:
14427             gcc_unreachable ();
14428           }
14429
14430       /* [basic.std.dynamic.allocation]/1:
14431
14432          A program is ill-formed if an allocation function is declared
14433          in a namespace scope other than global scope or declared
14434          static in global scope.
14435
14436          The same also holds true for deallocation functions.  */
14437       if (DECL_NAMESPACE_SCOPE_P (decl))
14438         {
14439           if (CP_DECL_CONTEXT (decl) != global_namespace)
14440             {
14441               error_at (loc, "%qD may not be declared within a namespace",
14442                         decl);
14443               return false;
14444             }
14445
14446           if (!TREE_PUBLIC (decl))
14447             {
14448               error_at (loc, "%qD may not be declared as static", decl);
14449               return false;
14450             }
14451         }
14452
14453       if (op_flags & OVL_OP_FLAG_DELETE)
14454         {
14455           DECL_SET_IS_OPERATOR_DELETE (decl, true);
14456           coerce_delete_type (decl, loc);
14457         }
14458       else
14459         {
14460           DECL_SET_IS_OPERATOR_NEW (decl, true);
14461           TREE_TYPE (decl) = coerce_new_type (TREE_TYPE (decl), loc);
14462         }
14463
14464       return true;
14465     }
14466
14467   /* An operator function must either be a non-static member function
14468      or have at least one parameter of a class, a reference to a class,
14469      an enumeration, or a reference to an enumeration.  13.4.0.6 */
14470   if (! methodp || DECL_STATIC_FUNCTION_P (decl))
14471     {
14472       if (operator_code == TYPE_EXPR
14473           || operator_code == CALL_EXPR
14474           || operator_code == COMPONENT_REF
14475           || operator_code == ARRAY_REF
14476           || operator_code == NOP_EXPR)
14477         {
14478           error_at (loc, "%qD must be a non-static member function", decl);
14479           return false;
14480         }
14481
14482       if (DECL_STATIC_FUNCTION_P (decl))
14483         {
14484           error_at (loc, "%qD must be either a non-static member "
14485                     "function or a non-member function", decl);
14486           return false;
14487         }
14488
14489       for (tree arg = argtypes; ; arg = TREE_CHAIN (arg))
14490         {
14491           if (!arg || arg == void_list_node)
14492             {
14493               if (complain)
14494                 error_at(loc, "%qD must have an argument of class or "
14495                          "enumerated type", decl);
14496               return false;
14497             }
14498       
14499           tree type = non_reference (TREE_VALUE (arg));
14500           if (type == error_mark_node)
14501             return false;
14502           
14503           /* MAYBE_CLASS_TYPE_P, rather than CLASS_TYPE_P, is used
14504              because these checks are performed even on template
14505              functions.  */
14506           if (MAYBE_CLASS_TYPE_P (type)
14507               || TREE_CODE (type) == ENUMERAL_TYPE)
14508             break;
14509         }
14510     }
14511
14512   if (operator_code == CALL_EXPR)
14513     /* There are no further restrictions on the arguments to an overloaded
14514        "operator ()".  */
14515     return true;
14516
14517   if (operator_code == COND_EXPR)
14518     {
14519       /* 13.4.0.3 */
14520       error_at (loc, "ISO C++ prohibits overloading %<operator ?:%>");
14521       return false;
14522     }
14523
14524   /* Count the number of arguments and check for ellipsis.  */
14525   int arity = 0;
14526   for (tree arg = argtypes; arg != void_list_node; arg = TREE_CHAIN (arg))
14527     {
14528       if (!arg)
14529         {
14530           /* Variadic.  */
14531           error_at (loc, "%qD must not have variable number of arguments",
14532                     decl);
14533           return false;
14534         }
14535       ++arity;
14536     }
14537
14538   /* Verify correct number of arguments.  */
14539   switch (op_flags)
14540     {
14541     case OVL_OP_FLAG_AMBIARY:
14542       if (arity == 1)
14543         {
14544           /* We have a unary instance of an ambi-ary op.  Remap to the
14545              unary one.  */
14546           unsigned alt = ovl_op_alternate[ovl_op_mapping [operator_code]];
14547           const ovl_op_info_t *ovl_op = &ovl_op_info[false][alt];
14548           gcc_checking_assert (ovl_op->flags == OVL_OP_FLAG_UNARY);
14549           operator_code = ovl_op->tree_code;
14550           DECL_OVERLOADED_OPERATOR_CODE_RAW (decl) = ovl_op->ovl_op_code;
14551         }
14552       else if (arity != 2)
14553         {
14554           /* This was an ambiguous operator but is invalid. */
14555           error_at (loc,
14556                     methodp
14557                     ? G_("%qD must have either zero or one argument")
14558                     : G_("%qD must have either one or two arguments"), decl);
14559           return false;
14560         }
14561       else if ((operator_code == POSTINCREMENT_EXPR
14562                 || operator_code == POSTDECREMENT_EXPR)
14563                && ! processing_template_decl
14564                /* x++ and x--'s second argument must be an int.  */
14565                && ! same_type_p (TREE_VALUE (TREE_CHAIN (argtypes)),
14566                                  integer_type_node))
14567         {
14568           error_at (loc,
14569                     methodp
14570                     ? G_("postfix %qD must have %<int%> as its argument")
14571                     : G_("postfix %qD must have %<int%> as its second argument"),
14572                     decl);
14573           return false;
14574         }
14575       break;
14576
14577     case OVL_OP_FLAG_UNARY:
14578       if (arity != 1)
14579         {
14580           error_at (loc,
14581                     methodp
14582                     ? G_("%qD must have no arguments")
14583                     : G_("%qD must have exactly one argument"), decl);
14584           return false;
14585         }
14586       break;
14587
14588     case OVL_OP_FLAG_BINARY:
14589       if (arity != 2)
14590         {
14591           error_at (loc,
14592                     methodp
14593                     ? G_("%qD must have exactly one argument")
14594                     : G_("%qD must have exactly two arguments"), decl);
14595           return false;
14596         }
14597       break;
14598
14599     default:
14600       gcc_unreachable ();
14601     }
14602
14603   /* There can be no default arguments.  */
14604   for (tree arg = argtypes; arg != void_list_node; arg = TREE_CHAIN (arg))
14605     if (TREE_PURPOSE (arg))
14606       {
14607         TREE_PURPOSE (arg) = NULL_TREE;
14608         error_at (loc, "%qD cannot have default arguments", decl);
14609         return false;
14610       }
14611
14612   /* At this point the declaration is well-formed.  It may not be
14613      sensible though.  */
14614
14615   /* Check member function warnings only on the in-class declaration.
14616      There's no point warning on an out-of-class definition.  */
14617   if (class_type && class_type != current_class_type)
14618     return true;
14619
14620   /* Warn about conversion operators that will never be used.  */
14621   if (IDENTIFIER_CONV_OP_P (name)
14622       && ! DECL_TEMPLATE_INFO (decl)
14623       && warn_class_conversion)
14624     {
14625       tree t = TREE_TYPE (name);
14626       int ref = TYPE_REF_P (t);
14627
14628       if (ref)
14629         t = TYPE_MAIN_VARIANT (TREE_TYPE (t));
14630
14631       if (VOID_TYPE_P (t))
14632         warning_at (loc, OPT_Wclass_conversion, "converting %qT to %<void%> "
14633                     "will never use a type conversion operator", class_type);
14634       else if (class_type)
14635         {
14636           if (same_type_ignoring_top_level_qualifiers_p (t, class_type))
14637             warning_at (loc, OPT_Wclass_conversion,
14638                         ref
14639                         ? G_("converting %qT to a reference to the same type "
14640                              "will never use a type conversion operator")
14641                         : G_("converting %qT to the same type "
14642                              "will never use a type conversion operator"),
14643                         class_type);
14644           /* Don't force t to be complete here.  */
14645           else if (MAYBE_CLASS_TYPE_P (t)
14646                    && COMPLETE_TYPE_P (t)
14647                    && DERIVED_FROM_P (t, class_type))
14648             warning_at (loc, OPT_Wclass_conversion,
14649                         ref
14650                         ? G_("converting %qT to a reference to a base class "
14651                              "%qT will never use a type conversion operator")
14652                         : G_("converting %qT to a base class %qT "
14653                              "will never use a type conversion operator"),
14654                         class_type, t);
14655         }
14656     }
14657
14658   if (!warn_ecpp)
14659     return true;
14660
14661   /* Effective C++ rules below.  */
14662
14663   /* More Effective C++ rule 7.  */
14664   if (operator_code == TRUTH_ANDIF_EXPR
14665       || operator_code == TRUTH_ORIF_EXPR
14666       || operator_code == COMPOUND_EXPR)
14667     warning_at (loc, OPT_Weffc__,
14668                 "user-defined %qD always evaluates both arguments", decl);
14669   
14670   /* More Effective C++ rule 6.  */
14671   if (operator_code == POSTINCREMENT_EXPR
14672       || operator_code == POSTDECREMENT_EXPR
14673       || operator_code == PREINCREMENT_EXPR
14674       || operator_code == PREDECREMENT_EXPR)
14675     {
14676       tree arg = TREE_VALUE (argtypes);
14677       tree ret = TREE_TYPE (TREE_TYPE (decl));
14678       if (methodp || TYPE_REF_P (arg))
14679         arg = TREE_TYPE (arg);
14680       arg = TYPE_MAIN_VARIANT (arg);
14681
14682       if (operator_code == PREINCREMENT_EXPR
14683           || operator_code == PREDECREMENT_EXPR)
14684         {
14685           if (!TYPE_REF_P (ret)
14686               || !same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (ret)), arg))
14687             warning_at (loc, OPT_Weffc__, "prefix %qD should return %qT", decl,
14688                         build_reference_type (arg));
14689         }
14690       else
14691         {
14692           if (!same_type_p (TYPE_MAIN_VARIANT (ret), arg))
14693             warning_at (loc, OPT_Weffc__,
14694                         "postfix %qD should return %qT", decl, arg);
14695         }
14696     }
14697
14698   /* Effective C++ rule 23.  */
14699   if (!DECL_ASSIGNMENT_OPERATOR_P (decl)
14700       && (operator_code == PLUS_EXPR
14701           || operator_code == MINUS_EXPR
14702           || operator_code == TRUNC_DIV_EXPR
14703           || operator_code == MULT_EXPR
14704           || operator_code == TRUNC_MOD_EXPR)
14705       && TYPE_REF_P (TREE_TYPE (TREE_TYPE (decl))))
14706     warning_at (loc, OPT_Weffc__, "%qD should return by value", decl);
14707
14708   return true;
14709 }
14710 \f
14711 /* Return a string giving the keyword associate with CODE.  */
14712
14713 static const char *
14714 tag_name (enum tag_types code)
14715 {
14716   switch (code)
14717     {
14718     case record_type:
14719       return "struct";
14720     case class_type:
14721       return "class";
14722     case union_type:
14723       return "union";
14724     case enum_type:
14725       return "enum";
14726     case typename_type:
14727       return "typename";
14728     default:
14729       gcc_unreachable ();
14730     }
14731 }
14732
14733 /* Name lookup in an elaborated-type-specifier (after the keyword
14734    indicated by TAG_CODE) has found the TYPE_DECL DECL.  If the
14735    elaborated-type-specifier is invalid, issue a diagnostic and return
14736    error_mark_node; otherwise, return the *_TYPE to which it referred.
14737    If ALLOW_TEMPLATE_P is true, TYPE may be a class template.  */
14738
14739 tree
14740 check_elaborated_type_specifier (enum tag_types tag_code,
14741                                  tree decl,
14742                                  bool allow_template_p)
14743 {
14744   tree type;
14745
14746   /* In the case of:
14747
14748        struct S { struct S *p; };
14749
14750      name lookup will find the TYPE_DECL for the implicit "S::S"
14751      typedef.  Adjust for that here.  */
14752   if (DECL_SELF_REFERENCE_P (decl))
14753     decl = TYPE_NAME (TREE_TYPE (decl));
14754
14755   type = TREE_TYPE (decl);
14756
14757   /* Check TEMPLATE_TYPE_PARM first because DECL_IMPLICIT_TYPEDEF_P
14758      is false for this case as well.  */
14759   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
14760     {
14761       error ("using template type parameter %qT after %qs",
14762              type, tag_name (tag_code));
14763       return error_mark_node;
14764     }
14765   /* Accept template template parameters.  */
14766   else if (allow_template_p
14767            && (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM
14768                || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM))
14769     ;
14770   /*   [dcl.type.elab]
14771
14772        If the identifier resolves to a typedef-name or the
14773        simple-template-id resolves to an alias template
14774        specialization, the elaborated-type-specifier is ill-formed.
14775
14776      In other words, the only legitimate declaration to use in the
14777      elaborated type specifier is the implicit typedef created when
14778      the type is declared.  */
14779   else if (!DECL_IMPLICIT_TYPEDEF_P (decl)
14780            && !DECL_SELF_REFERENCE_P (decl)
14781            && tag_code != typename_type)
14782     {
14783       if (alias_template_specialization_p (type, nt_opaque))
14784         error ("using alias template specialization %qT after %qs",
14785                type, tag_name (tag_code));
14786       else
14787         error ("using typedef-name %qD after %qs", decl, tag_name (tag_code));
14788       inform (DECL_SOURCE_LOCATION (decl),
14789               "%qD has a previous declaration here", decl);
14790       return error_mark_node;
14791     }
14792   else if (TREE_CODE (type) != RECORD_TYPE
14793            && TREE_CODE (type) != UNION_TYPE
14794            && tag_code != enum_type
14795            && tag_code != typename_type)
14796     {
14797       error ("%qT referred to as %qs", type, tag_name (tag_code));
14798       inform (location_of (type), "%qT has a previous declaration here", type);
14799       return error_mark_node;
14800     }
14801   else if (TREE_CODE (type) != ENUMERAL_TYPE
14802            && tag_code == enum_type)
14803     {
14804       error ("%qT referred to as enum", type);
14805       inform (location_of (type), "%qT has a previous declaration here", type);
14806       return error_mark_node;
14807     }
14808   else if (!allow_template_p
14809            && TREE_CODE (type) == RECORD_TYPE
14810            && CLASSTYPE_IS_TEMPLATE (type))
14811     {
14812       /* If a class template appears as elaborated type specifier
14813          without a template header such as:
14814
14815            template <class T> class C {};
14816            void f(class C);             // No template header here
14817
14818          then the required template argument is missing.  */
14819       error ("template argument required for %<%s %T%>",
14820              tag_name (tag_code),
14821              DECL_NAME (CLASSTYPE_TI_TEMPLATE (type)));
14822       return error_mark_node;
14823     }
14824
14825   return type;
14826 }
14827
14828 /* Lookup NAME of an elaborated type specifier according to SCOPE and
14829    issue diagnostics if necessary.  Return *_TYPE node upon success,
14830    NULL_TREE when the NAME is not found, and ERROR_MARK_NODE for type
14831    error.  */
14832
14833 static tree
14834 lookup_and_check_tag (enum tag_types tag_code, tree name,
14835                       TAG_how how, bool template_header_p)
14836 {
14837   tree decl;
14838   if (how == TAG_how::GLOBAL)
14839     {
14840       /* First try ordinary name lookup, ignoring hidden class name
14841          injected via friend declaration.  */
14842       decl = lookup_name (name, LOOK_want::TYPE);
14843       decl = strip_using_decl (decl);
14844       /* If that fails, the name will be placed in the smallest
14845          non-class, non-function-prototype scope according to 3.3.1/5.
14846          We may already have a hidden name declared as friend in this
14847          scope.  So lookup again but not ignoring hidden names.
14848          If we find one, that name will be made visible rather than
14849          creating a new tag.  */
14850       if (!decl)
14851         decl = lookup_elaborated_type (name, TAG_how::INNERMOST_NON_CLASS);
14852     }
14853   else
14854     decl = lookup_elaborated_type (name, how);
14855
14856
14857   if (!decl)
14858     /* We found nothing.  */
14859     return NULL_TREE;
14860
14861   if (TREE_CODE (decl) == TREE_LIST)
14862     {
14863       error ("reference to %qD is ambiguous", name);
14864       print_candidates (decl);
14865       return error_mark_node;
14866     }
14867
14868   if (DECL_CLASS_TEMPLATE_P (decl)
14869       /* If scope is TAG_how::CURRENT_ONLY we're defining a class,
14870          so ignore a template template parameter.  */
14871       || (how != TAG_how::CURRENT_ONLY && DECL_TEMPLATE_TEMPLATE_PARM_P (decl)))
14872     decl = DECL_TEMPLATE_RESULT (decl);
14873
14874   if (TREE_CODE (decl) != TYPE_DECL)
14875     /* Found not-a-type.  */
14876     return NULL_TREE;
14877
14878     /* Look for invalid nested type:
14879      class C {
14880      class C {};
14881      };  */
14882   if (how == TAG_how::CURRENT_ONLY && DECL_SELF_REFERENCE_P (decl))
14883     {
14884       error ("%qD has the same name as the class in which it is "
14885              "declared", decl);
14886       return error_mark_node;
14887     }
14888
14889   /* Two cases we need to consider when deciding if a class
14890      template is allowed as an elaborated type specifier:
14891      1. It is a self reference to its own class.
14892      2. It comes with a template header.
14893
14894      For example:
14895
14896      template <class T> class C {
14897        class C *c1;             // DECL_SELF_REFERENCE_P is true
14898        class D;
14899      };
14900      template <class U> class C; // template_header_p is true
14901      template <class T> class C<T>::D {
14902        class C *c2;             // DECL_SELF_REFERENCE_P is true
14903      };  */
14904
14905   tree t = check_elaborated_type_specifier (tag_code, decl,
14906                                             template_header_p
14907                                             | DECL_SELF_REFERENCE_P (decl));
14908   if (template_header_p && t && CLASS_TYPE_P (t)
14909       && (!CLASSTYPE_TEMPLATE_INFO (t)
14910           || (!PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)))))
14911     {
14912       error ("%qT is not a template", t);
14913       inform (location_of (t), "previous declaration here");
14914       if (TYPE_CLASS_SCOPE_P (t)
14915           && CLASSTYPE_TEMPLATE_INFO (TYPE_CONTEXT (t)))
14916         inform (input_location,
14917                 "perhaps you want to explicitly add %<%T::%>",
14918                 TYPE_CONTEXT (t));
14919       return error_mark_node;
14920     }
14921
14922   return t;
14923 }
14924
14925 /* Get the struct, enum or union (TAG_CODE says which) with tag NAME.
14926    Define the tag as a forward-reference if it is not defined.
14927
14928    If a declaration is given, process it here, and report an error if
14929    multiple declarations are not identical.
14930
14931    SCOPE is TS_CURRENT when this is also a definition.  Only look in
14932    the current frame for the name (since C++ allows new names in any
14933    scope.)  It is TS_WITHIN_ENCLOSING_NON_CLASS if this is a friend
14934    declaration.  Only look beginning from the current scope outward up
14935    till the nearest non-class scope.  Otherwise it is TS_GLOBAL.
14936
14937    TEMPLATE_HEADER_P is true when this declaration is preceded by
14938    a set of template parameters.  */
14939
14940 static tree
14941 xref_tag_1 (enum tag_types tag_code, tree name,
14942             TAG_how how, bool template_header_p)
14943 {
14944   enum tree_code code;
14945   tree context = NULL_TREE;
14946
14947   gcc_assert (identifier_p (name));
14948
14949   switch (tag_code)
14950     {
14951     case record_type:
14952     case class_type:
14953       code = RECORD_TYPE;
14954       break;
14955     case union_type:
14956       code = UNION_TYPE;
14957       break;
14958     case enum_type:
14959       code = ENUMERAL_TYPE;
14960       break;
14961     default:
14962       gcc_unreachable ();
14963     }
14964
14965   /* In case of anonymous name, xref_tag is only called to
14966      make type node and push name.  Name lookup is not required.  */
14967   tree t = NULL_TREE;
14968   if (!IDENTIFIER_ANON_P (name))
14969     t = lookup_and_check_tag  (tag_code, name, how, template_header_p);
14970
14971   if (t == error_mark_node)
14972     return error_mark_node;
14973
14974   if (how != TAG_how::CURRENT_ONLY && t && current_class_type
14975       && template_class_depth (current_class_type)
14976       && template_header_p)
14977     {
14978       if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
14979         return t;
14980
14981       /* Since HOW is not TAG_how::CURRENT_ONLY, we are not looking at
14982          a definition of this tag.  Since, in addition, we are
14983          currently processing a (member) template declaration of a
14984          template class, we must be very careful; consider:
14985
14986            template <class X> struct S1
14987
14988            template <class U> struct S2
14989            {
14990              template <class V> friend struct S1;
14991            };
14992
14993          Here, the S2::S1 declaration should not be confused with the
14994          outer declaration.  In particular, the inner version should
14995          have a template parameter of level 2, not level 1.
14996
14997          On the other hand, when presented with:
14998
14999            template <class T> struct S1
15000            {
15001              template <class U> struct S2 {};
15002              template <class U> friend struct S2;
15003            };
15004
15005          the friend must find S1::S2 eventually.  We accomplish this
15006          by making sure that the new type we create to represent this
15007          declaration has the right TYPE_CONTEXT.  */
15008       context = TYPE_CONTEXT (t);
15009       t = NULL_TREE;
15010     }
15011
15012   if (! t)
15013     {
15014       /* If no such tag is yet defined, create a forward-reference node
15015          and record it as the "definition".
15016          When a real declaration of this type is found,
15017          the forward-reference will be altered into a real type.  */
15018       if (code == ENUMERAL_TYPE)
15019         {
15020           error ("use of enum %q#D without previous declaration", name);
15021           return error_mark_node;
15022         }
15023
15024       t = make_class_type (code);
15025       TYPE_CONTEXT (t) = context;
15026       if (IDENTIFIER_LAMBDA_P (name))
15027         /* Mark it as a lambda type right now.  Our caller will
15028            correct the value.  */
15029         CLASSTYPE_LAMBDA_EXPR (t) = error_mark_node;
15030       t = pushtag (name, t, how);
15031     }
15032   else
15033     {
15034       if (template_header_p && MAYBE_CLASS_TYPE_P (t))
15035         {
15036           /* Check that we aren't trying to overload a class with different
15037              constraints.  */
15038           tree constr = NULL_TREE;
15039           if (current_template_parms)
15040             {
15041               tree reqs = TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
15042               constr = build_constraints (reqs, NULL_TREE);
15043             }
15044           if (!redeclare_class_template (t, current_template_parms, constr))
15045             return error_mark_node;
15046         }
15047       else if (!processing_template_decl
15048                && CLASS_TYPE_P (t)
15049                && CLASSTYPE_IS_TEMPLATE (t))
15050         {
15051           error ("redeclaration of %qT as a non-template", t);
15052           inform (location_of (t), "previous declaration %qD", t);
15053           return error_mark_node;
15054         }
15055     }
15056
15057   return t;
15058 }
15059
15060 /* Wrapper for xref_tag_1.  */
15061
15062 tree
15063 xref_tag (enum tag_types tag_code, tree name,
15064           TAG_how how, bool template_header_p)
15065 {
15066   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
15067   tree ret = xref_tag_1 (tag_code, name, how, template_header_p);
15068   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
15069   return ret;
15070 }
15071
15072 /* Create the binfo hierarchy for REF with (possibly NULL) base list
15073    BASE_LIST.  For each element on BASE_LIST the TREE_PURPOSE is an
15074    access_* node, and the TREE_VALUE is the type of the base-class.
15075    Non-NULL TREE_TYPE indicates virtual inheritance.  */
15076
15077 void
15078 xref_basetypes (tree ref, tree base_list)
15079 {
15080   tree *basep;
15081   tree binfo, base_binfo;
15082   unsigned max_vbases = 0; /* Maximum direct & indirect virtual bases.  */
15083   unsigned max_bases = 0;  /* Maximum direct bases.  */
15084   unsigned max_dvbases = 0; /* Maximum direct virtual bases.  */
15085   int i;
15086   tree default_access;
15087   tree igo_prev; /* Track Inheritance Graph Order.  */
15088
15089   if (ref == error_mark_node)
15090     return;
15091
15092   /* The base of a derived class is private by default, all others are
15093      public.  */
15094   default_access = (TREE_CODE (ref) == RECORD_TYPE
15095                     && CLASSTYPE_DECLARED_CLASS (ref)
15096                     ? access_private_node : access_public_node);
15097
15098   /* First, make sure that any templates in base-classes are
15099      instantiated.  This ensures that if we call ourselves recursively
15100      we do not get confused about which classes are marked and which
15101      are not.  */
15102   basep = &base_list;
15103   while (*basep)
15104     {
15105       tree basetype = TREE_VALUE (*basep);
15106
15107       /* The dependent_type_p call below should really be dependent_scope_p
15108          so that we give a hard error about using an incomplete type as a
15109          base, but we allow it with a pedwarn for backward
15110          compatibility.  */
15111       if (processing_template_decl
15112           && CLASS_TYPE_P (basetype) && TYPE_BEING_DEFINED (basetype))
15113         cxx_incomplete_type_diagnostic (NULL_TREE, basetype, DK_PEDWARN);
15114       if (!dependent_type_p (basetype)
15115           && !complete_type_or_else (basetype, NULL))
15116         /* An incomplete type.  Remove it from the list.  */
15117         *basep = TREE_CHAIN (*basep);
15118       else
15119         {
15120           max_bases++;
15121           if (TREE_TYPE (*basep))
15122             max_dvbases++;
15123           if (CLASS_TYPE_P (basetype))
15124             max_vbases += vec_safe_length (CLASSTYPE_VBASECLASSES (basetype));
15125           basep = &TREE_CHAIN (*basep);
15126         }
15127     }
15128   max_vbases += max_dvbases;
15129
15130   TYPE_MARKED_P (ref) = 1;
15131
15132   /* The binfo slot should be empty, unless this is an (ill-formed)
15133      redefinition.  */
15134   gcc_assert (!TYPE_BINFO (ref) || TYPE_SIZE (ref));
15135
15136   gcc_assert (TYPE_MAIN_VARIANT (ref) == ref);
15137
15138   binfo = make_tree_binfo (max_bases);
15139
15140   TYPE_BINFO (ref) = binfo;
15141   BINFO_OFFSET (binfo) = size_zero_node;
15142   BINFO_TYPE (binfo) = ref;
15143
15144   /* Apply base-class info set up to the variants of this type.  */
15145   fixup_type_variants (ref);
15146
15147   if (max_bases)
15148     {
15149       vec_alloc (BINFO_BASE_ACCESSES (binfo), max_bases);
15150       /* A C++98 POD cannot have base classes.  */
15151       CLASSTYPE_NON_LAYOUT_POD_P (ref) = true;
15152
15153       if (TREE_CODE (ref) == UNION_TYPE)
15154         {
15155           error ("derived union %qT invalid", ref);
15156           return;
15157         }
15158     }
15159
15160   if (max_bases > 1)
15161     warning (OPT_Wmultiple_inheritance,
15162              "%qT defined with multiple direct bases", ref);
15163
15164   if (max_vbases)
15165     {
15166       /* An aggregate can't have virtual base classes.  */
15167       CLASSTYPE_NON_AGGREGATE (ref) = true;
15168
15169       vec_alloc (CLASSTYPE_VBASECLASSES (ref), max_vbases);
15170
15171       if (max_dvbases)
15172         warning (OPT_Wvirtual_inheritance,
15173                  "%qT defined with direct virtual base", ref);
15174     }
15175
15176   for (igo_prev = binfo; base_list; base_list = TREE_CHAIN (base_list))
15177     {
15178       tree access = TREE_PURPOSE (base_list);
15179       int via_virtual = TREE_TYPE (base_list) != NULL_TREE;
15180       tree basetype = TREE_VALUE (base_list);
15181
15182       if (access == access_default_node)
15183         access = default_access;
15184
15185       /* Before C++17, an aggregate cannot have base classes.  In C++17, an
15186          aggregate can't have virtual, private, or protected base classes.  */
15187       if (cxx_dialect < cxx17
15188           || access != access_public_node
15189           || via_virtual)
15190         CLASSTYPE_NON_AGGREGATE (ref) = true;
15191
15192       if (PACK_EXPANSION_P (basetype))
15193         basetype = PACK_EXPANSION_PATTERN (basetype);
15194       if (TREE_CODE (basetype) == TYPE_DECL)
15195         basetype = TREE_TYPE (basetype);
15196       if (!MAYBE_CLASS_TYPE_P (basetype) || TREE_CODE (basetype) == UNION_TYPE)
15197         {
15198           error ("base type %qT fails to be a struct or class type",
15199                  basetype);
15200           goto dropped_base;
15201         }
15202
15203       base_binfo = NULL_TREE;
15204       if (CLASS_TYPE_P (basetype) && !dependent_scope_p (basetype))
15205         {
15206           base_binfo = TYPE_BINFO (basetype);
15207           /* The original basetype could have been a typedef'd type.  */
15208           basetype = BINFO_TYPE (base_binfo);
15209
15210           /* Inherit flags from the base.  */
15211           TYPE_HAS_NEW_OPERATOR (ref)
15212             |= TYPE_HAS_NEW_OPERATOR (basetype);
15213           TYPE_HAS_ARRAY_NEW_OPERATOR (ref)
15214             |= TYPE_HAS_ARRAY_NEW_OPERATOR (basetype);
15215           TYPE_GETS_DELETE (ref) |= TYPE_GETS_DELETE (basetype);
15216           TYPE_HAS_CONVERSION (ref) |= TYPE_HAS_CONVERSION (basetype);
15217           CLASSTYPE_DIAMOND_SHAPED_P (ref)
15218             |= CLASSTYPE_DIAMOND_SHAPED_P (basetype);
15219           CLASSTYPE_REPEATED_BASE_P (ref)
15220             |= CLASSTYPE_REPEATED_BASE_P (basetype);
15221         }
15222
15223       /* We must do this test after we've seen through a typedef
15224          type.  */
15225       if (TYPE_MARKED_P (basetype))
15226         {
15227           if (basetype == ref)
15228             error ("recursive type %qT undefined", basetype);
15229           else
15230             error ("duplicate base type %qT invalid", basetype);
15231           goto dropped_base;
15232         }
15233
15234       if (PACK_EXPANSION_P (TREE_VALUE (base_list)))
15235         /* Regenerate the pack expansion for the bases. */
15236         basetype = make_pack_expansion (basetype);
15237
15238       TYPE_MARKED_P (basetype) = 1;
15239
15240       base_binfo = copy_binfo (base_binfo, basetype, ref,
15241                                &igo_prev, via_virtual);
15242       if (!BINFO_INHERITANCE_CHAIN (base_binfo))
15243         BINFO_INHERITANCE_CHAIN (base_binfo) = binfo;
15244
15245       BINFO_BASE_APPEND (binfo, base_binfo);
15246       BINFO_BASE_ACCESS_APPEND (binfo, access);
15247       continue;
15248
15249     dropped_base:
15250       /* Update max_vbases to reflect the reality that we are dropping
15251          this base:  if it reaches zero we want to undo the vec_alloc
15252          above to avoid inconsistencies during error-recovery: eg, in
15253          build_special_member_call, CLASSTYPE_VBASECLASSES non null
15254          and vtt null (c++/27952).  */
15255       if (via_virtual)
15256         max_vbases--;
15257       if (CLASS_TYPE_P (basetype))
15258         max_vbases
15259           -= vec_safe_length (CLASSTYPE_VBASECLASSES (basetype));
15260     }
15261
15262   if (CLASSTYPE_VBASECLASSES (ref)
15263       && max_vbases == 0)
15264     vec_free (CLASSTYPE_VBASECLASSES (ref));
15265
15266   if (vec_safe_length (CLASSTYPE_VBASECLASSES (ref)) < max_vbases)
15267     /* If we didn't get max_vbases vbases, we must have shared at
15268        least one of them, and are therefore diamond shaped.  */
15269     CLASSTYPE_DIAMOND_SHAPED_P (ref) = 1;
15270
15271   /* Unmark all the types.  */
15272   for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
15273     TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 0;
15274   TYPE_MARKED_P (ref) = 0;
15275
15276   /* Now see if we have a repeated base type.  */
15277   if (!CLASSTYPE_REPEATED_BASE_P (ref))
15278     {
15279       for (base_binfo = binfo; base_binfo;
15280            base_binfo = TREE_CHAIN (base_binfo))
15281         {
15282           if (TYPE_MARKED_P (BINFO_TYPE (base_binfo)))
15283             {
15284               CLASSTYPE_REPEATED_BASE_P (ref) = 1;
15285               break;
15286             }
15287           TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 1;
15288         }
15289       for (base_binfo = binfo; base_binfo;
15290            base_binfo = TREE_CHAIN (base_binfo))
15291         if (TYPE_MARKED_P (BINFO_TYPE (base_binfo)))
15292           TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 0;
15293         else
15294           break;
15295     }
15296 }
15297
15298 \f
15299 /* Copies the enum-related properties from type SRC to type DST.
15300    Used with the underlying type of an enum and the enum itself.  */
15301 static void
15302 copy_type_enum (tree dst, tree src)
15303 {
15304   tree t;
15305   for (t = dst; t; t = TYPE_NEXT_VARIANT (t))
15306     {
15307       TYPE_MIN_VALUE (t) = TYPE_MIN_VALUE (src);
15308       TYPE_MAX_VALUE (t) = TYPE_MAX_VALUE (src);
15309       TYPE_SIZE (t) = TYPE_SIZE (src);
15310       TYPE_SIZE_UNIT (t) = TYPE_SIZE_UNIT (src);
15311       SET_TYPE_MODE (dst, TYPE_MODE (src));
15312       TYPE_PRECISION (t) = TYPE_PRECISION (src);
15313       unsigned valign = TYPE_ALIGN (src);
15314       if (TYPE_USER_ALIGN (t))
15315         valign = MAX (valign, TYPE_ALIGN (t));
15316       else
15317         TYPE_USER_ALIGN (t) = TYPE_USER_ALIGN (src);
15318       SET_TYPE_ALIGN (t, valign);
15319       TYPE_UNSIGNED (t) = TYPE_UNSIGNED (src);
15320     }
15321 }
15322
15323 /* Begin compiling the definition of an enumeration type.
15324    NAME is its name, 
15325
15326    if ENUMTYPE is not NULL_TREE then the type has alredy been found.
15327
15328    UNDERLYING_TYPE is the type that will be used as the storage for
15329    the enumeration type. This should be NULL_TREE if no storage type
15330    was specified.
15331
15332    ATTRIBUTES are any attributes specified after the enum-key.
15333
15334    SCOPED_ENUM_P is true if this is a scoped enumeration type.
15335
15336    if IS_NEW is not NULL, gets TRUE iff a new type is created.
15337
15338    Returns the type object, as yet incomplete.
15339    Also records info about it so that build_enumerator
15340    may be used to declare the individual values as they are read.  */
15341
15342 tree
15343 start_enum (tree name, tree enumtype, tree underlying_type,
15344             tree attributes, bool scoped_enum_p, bool *is_new)
15345 {
15346   tree prevtype = NULL_TREE;
15347   gcc_assert (identifier_p (name));
15348
15349   if (is_new)
15350     *is_new = false;
15351   /* [C++0x dcl.enum]p5:
15352
15353     If not explicitly specified, the underlying type of a scoped
15354     enumeration type is int.  */
15355   if (!underlying_type && scoped_enum_p)
15356     underlying_type = integer_type_node;
15357
15358   if (underlying_type)
15359     underlying_type = cv_unqualified (underlying_type);
15360
15361   /* If this is the real definition for a previous forward reference,
15362      fill in the contents in the same object that used to be the
15363      forward reference.  */
15364   if (!enumtype)
15365     enumtype = lookup_and_check_tag (enum_type, name,
15366                                      /*tag_scope=*/TAG_how::CURRENT_ONLY,
15367                                      /*template_header_p=*/false);
15368
15369   /* In case of a template_decl, the only check that should be deferred
15370      to instantiation time is the comparison of underlying types.  */
15371   if (enumtype && TREE_CODE (enumtype) == ENUMERAL_TYPE)
15372     {
15373       if (scoped_enum_p != SCOPED_ENUM_P (enumtype))
15374         {
15375           error_at (input_location, "scoped/unscoped mismatch "
15376                     "in enum %q#T", enumtype);
15377           inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
15378                   "previous definition here");
15379           enumtype = error_mark_node;
15380         }
15381       else if (ENUM_FIXED_UNDERLYING_TYPE_P (enumtype) != !! underlying_type)
15382         {
15383           error_at (input_location, "underlying type mismatch "
15384                     "in enum %q#T", enumtype);
15385           inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
15386                   "previous definition here");
15387           enumtype = error_mark_node;
15388         }
15389       else if (underlying_type && ENUM_UNDERLYING_TYPE (enumtype)
15390                && !same_type_p (underlying_type,
15391                                 ENUM_UNDERLYING_TYPE (enumtype)))
15392         {
15393           error_at (input_location, "different underlying type "
15394                     "in enum %q#T", enumtype);
15395           inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
15396                   "previous definition here");
15397           underlying_type = NULL_TREE;
15398         }
15399     }
15400
15401   if (!enumtype || TREE_CODE (enumtype) != ENUMERAL_TYPE
15402       || processing_template_decl)
15403     {
15404       /* In case of error, make a dummy enum to allow parsing to
15405          continue.  */
15406       if (enumtype == error_mark_node)
15407         {
15408           name = make_anon_name ();
15409           enumtype = NULL_TREE;
15410         }
15411
15412       /* enumtype may be an ENUMERAL_TYPE if this is a redefinition
15413          of an opaque enum, or an opaque enum of an already defined
15414          enumeration (C++11).
15415          In any other case, it'll be NULL_TREE. */
15416       if (!enumtype)
15417         {
15418           if (is_new)
15419             *is_new = true;
15420         }
15421       prevtype = enumtype;
15422
15423       /* Do not push the decl more than once.  */
15424       if (!enumtype
15425           || TREE_CODE (enumtype) != ENUMERAL_TYPE)
15426         {
15427           enumtype = cxx_make_type (ENUMERAL_TYPE);
15428           enumtype = pushtag (name, enumtype);
15429
15430           /* std::byte aliases anything.  */
15431           if (enumtype != error_mark_node
15432               && TYPE_CONTEXT (enumtype) == std_node
15433               && !strcmp ("byte", TYPE_NAME_STRING (enumtype)))
15434             TYPE_ALIAS_SET (enumtype) = 0;
15435         }
15436       else
15437           enumtype = xref_tag (enum_type, name);
15438
15439       if (enumtype == error_mark_node)
15440         return error_mark_node;
15441
15442       /* The enum is considered opaque until the opening '{' of the
15443          enumerator list.  */
15444       SET_OPAQUE_ENUM_P (enumtype, true);
15445       ENUM_FIXED_UNDERLYING_TYPE_P (enumtype) = !! underlying_type;
15446     }
15447
15448   SET_SCOPED_ENUM_P (enumtype, scoped_enum_p);
15449
15450   cplus_decl_attributes (&enumtype, attributes, (int)ATTR_FLAG_TYPE_IN_PLACE);
15451
15452   if (underlying_type)
15453     {
15454       if (ENUM_UNDERLYING_TYPE (enumtype))
15455         /* We already checked that it matches, don't change it to a different
15456            typedef variant.  */;
15457       else if (CP_INTEGRAL_TYPE_P (underlying_type))
15458         {
15459           copy_type_enum (enumtype, underlying_type);
15460           ENUM_UNDERLYING_TYPE (enumtype) = underlying_type;
15461         }
15462       else if (dependent_type_p (underlying_type))
15463         ENUM_UNDERLYING_TYPE (enumtype) = underlying_type;
15464       else
15465         error ("underlying type %qT of %qT must be an integral type", 
15466                underlying_type, enumtype);
15467     }
15468
15469   /* If into a template class, the returned enum is always the first
15470      declaration (opaque or not) seen. This way all the references to
15471      this type will be to the same declaration. The following ones are used
15472      only to check for definition errors.  */
15473   if (prevtype && processing_template_decl)
15474     return prevtype;
15475   else
15476     return enumtype;
15477 }
15478
15479 /* After processing and defining all the values of an enumeration type,
15480    install their decls in the enumeration type.
15481    ENUMTYPE is the type object.  */
15482
15483 void
15484 finish_enum_value_list (tree enumtype)
15485 {
15486   tree values;
15487   tree underlying_type;
15488   tree decl;
15489   tree value;
15490   tree minnode, maxnode;
15491   tree t;
15492
15493   bool fixed_underlying_type_p 
15494     = ENUM_UNDERLYING_TYPE (enumtype) != NULL_TREE;
15495
15496   /* We built up the VALUES in reverse order.  */
15497   TYPE_VALUES (enumtype) = nreverse (TYPE_VALUES (enumtype));
15498
15499   /* For an enum defined in a template, just set the type of the values;
15500      all further processing is postponed until the template is
15501      instantiated.  We need to set the type so that tsubst of a CONST_DECL
15502      works.  */
15503   if (processing_template_decl)
15504     {
15505       for (values = TYPE_VALUES (enumtype);
15506            values;
15507            values = TREE_CHAIN (values))
15508         TREE_TYPE (TREE_VALUE (values)) = enumtype;
15509       return;
15510     }
15511
15512   /* Determine the minimum and maximum values of the enumerators.  */
15513   if (TYPE_VALUES (enumtype))
15514     {
15515       minnode = maxnode = NULL_TREE;
15516
15517       for (values = TYPE_VALUES (enumtype);
15518            values;
15519            values = TREE_CHAIN (values))
15520         {
15521           decl = TREE_VALUE (values);
15522
15523           /* [dcl.enum]: Following the closing brace of an enum-specifier,
15524              each enumerator has the type of its enumeration.  Prior to the
15525              closing brace, the type of each enumerator is the type of its
15526              initializing value.  */
15527           TREE_TYPE (decl) = enumtype;
15528
15529           /* Update the minimum and maximum values, if appropriate.  */
15530           value = DECL_INITIAL (decl);
15531           if (value == error_mark_node)
15532             value = integer_zero_node;
15533           /* Figure out what the minimum and maximum values of the
15534              enumerators are.  */
15535           if (!minnode)
15536             minnode = maxnode = value;
15537           else if (tree_int_cst_lt (maxnode, value))
15538             maxnode = value;
15539           else if (tree_int_cst_lt (value, minnode))
15540             minnode = value;
15541         }
15542     }
15543   else
15544     /* [dcl.enum]
15545
15546        If the enumerator-list is empty, the underlying type is as if
15547        the enumeration had a single enumerator with value 0.  */
15548     minnode = maxnode = integer_zero_node;
15549
15550   if (!fixed_underlying_type_p)
15551     {
15552       /* Compute the number of bits require to represent all values of the
15553          enumeration.  We must do this before the type of MINNODE and
15554          MAXNODE are transformed, since tree_int_cst_min_precision relies
15555          on the TREE_TYPE of the value it is passed.  */
15556       signop sgn = tree_int_cst_sgn (minnode) >= 0 ? UNSIGNED : SIGNED;
15557       int lowprec = tree_int_cst_min_precision (minnode, sgn);
15558       int highprec = tree_int_cst_min_precision (maxnode, sgn);
15559       int precision = MAX (lowprec, highprec);
15560       unsigned int itk;
15561       bool use_short_enum;
15562
15563       /* Determine the underlying type of the enumeration.
15564
15565          [dcl.enum]
15566
15567          The underlying type of an enumeration is an integral type that
15568          can represent all the enumerator values defined in the
15569          enumeration.  It is implementation-defined which integral type is
15570          used as the underlying type for an enumeration except that the
15571          underlying type shall not be larger than int unless the value of
15572          an enumerator cannot fit in an int or unsigned int.
15573
15574          We use "int" or an "unsigned int" as the underlying type, even if
15575          a smaller integral type would work, unless the user has
15576          explicitly requested that we use the smallest possible type.  The
15577          user can request that for all enumerations with a command line
15578          flag, or for just one enumeration with an attribute.  */
15579
15580       use_short_enum = flag_short_enums
15581         || lookup_attribute ("packed", TYPE_ATTRIBUTES (enumtype));
15582
15583       /* If the precision of the type was specified with an attribute and it
15584          was too small, give an error.  Otherwise, use it.  */
15585       if (TYPE_PRECISION (enumtype))
15586         {
15587           if (precision > TYPE_PRECISION (enumtype))
15588             error ("specified mode too small for enumerated values");
15589           else
15590             {
15591               use_short_enum = true;
15592               precision = TYPE_PRECISION (enumtype);
15593             }
15594         }
15595
15596       for (itk = (use_short_enum ? itk_char : itk_int);
15597            itk != itk_none;
15598            itk++)
15599         {
15600           underlying_type = integer_types[itk];
15601           if (underlying_type != NULL_TREE
15602               && TYPE_PRECISION (underlying_type) >= precision
15603               && TYPE_SIGN (underlying_type) == sgn)
15604             break;
15605         }
15606       if (itk == itk_none)
15607         {
15608           /* DR 377
15609
15610              IF no integral type can represent all the enumerator values, the
15611              enumeration is ill-formed.  */
15612           error ("no integral type can represent all of the enumerator values "
15613                  "for %qT", enumtype);
15614           precision = TYPE_PRECISION (long_long_integer_type_node);
15615           underlying_type = integer_types[itk_unsigned_long_long];
15616         }
15617
15618       /* [dcl.enum]
15619
15620          The value of sizeof() applied to an enumeration type, an object
15621          of an enumeration type, or an enumerator, is the value of sizeof()
15622          applied to the underlying type.  */
15623       copy_type_enum (enumtype, underlying_type);
15624
15625       /* Compute the minimum and maximum values for the type.
15626
15627          [dcl.enum]
15628
15629          For an enumeration where emin is the smallest enumerator and emax
15630          is the largest, the values of the enumeration are the values of the
15631          underlying type in the range bmin to bmax, where bmin and bmax are,
15632          respectively, the smallest and largest values of the smallest bit-
15633          field that can store emin and emax.  */
15634
15635       /* The middle-end currently assumes that types with TYPE_PRECISION
15636          narrower than their underlying type are suitably zero or sign
15637          extended to fill their mode.  Similarly, it assumes that the front
15638          end assures that a value of a particular type must be within
15639          TYPE_MIN_VALUE and TYPE_MAX_VALUE.
15640
15641          We used to set these fields based on bmin and bmax, but that led
15642          to invalid assumptions like optimizing away bounds checking.  So
15643          now we just set the TYPE_PRECISION, TYPE_MIN_VALUE, and
15644          TYPE_MAX_VALUE to the values for the mode above and only restrict
15645          the ENUM_UNDERLYING_TYPE for the benefit of diagnostics.  */
15646       ENUM_UNDERLYING_TYPE (enumtype)
15647         = build_distinct_type_copy (underlying_type);
15648       TYPE_PRECISION (ENUM_UNDERLYING_TYPE (enumtype)) = precision;
15649       set_min_and_max_values_for_integral_type
15650         (ENUM_UNDERLYING_TYPE (enumtype), precision, sgn);
15651
15652       /* If -fstrict-enums, still constrain TYPE_MIN/MAX_VALUE.  */
15653       if (flag_strict_enums)
15654         set_min_and_max_values_for_integral_type (enumtype, precision, sgn);
15655     }
15656   else
15657     underlying_type = ENUM_UNDERLYING_TYPE (enumtype);
15658
15659   /* Convert each of the enumerators to the type of the underlying
15660      type of the enumeration.  */
15661   for (values = TYPE_VALUES (enumtype); values; values = TREE_CHAIN (values))
15662     {
15663       decl = TREE_VALUE (values);
15664       iloc_sentinel ils (DECL_SOURCE_LOCATION (decl));
15665       if (fixed_underlying_type_p)
15666         /* If the enumeration type has a fixed underlying type, we
15667            already checked all of the enumerator values.  */
15668         value = DECL_INITIAL (decl);
15669       else
15670         value = perform_implicit_conversion (underlying_type,
15671                                              DECL_INITIAL (decl),
15672                                              tf_warning_or_error);
15673       /* Do not clobber shared ints.  */
15674       if (value != error_mark_node)
15675         {
15676           value = copy_node (value);
15677
15678           TREE_TYPE (value) = enumtype;
15679         }
15680       DECL_INITIAL (decl) = value;
15681     }
15682
15683   /* Fix up all variant types of this enum type.  */
15684   for (t = TYPE_MAIN_VARIANT (enumtype); t; t = TYPE_NEXT_VARIANT (t))
15685     TYPE_VALUES (t) = TYPE_VALUES (enumtype);
15686
15687   if (at_class_scope_p ()
15688       && COMPLETE_TYPE_P (current_class_type)
15689       && UNSCOPED_ENUM_P (enumtype))
15690     {
15691       insert_late_enum_def_bindings (current_class_type, enumtype);
15692       /* TYPE_FIELDS needs fixup.  */
15693       fixup_type_variants (current_class_type);
15694     }
15695
15696   /* Finish debugging output for this type.  */
15697   rest_of_type_compilation (enumtype, namespace_bindings_p ());
15698
15699   /* Each enumerator now has the type of its enumeration.  Clear the cache
15700      so that this change in types doesn't confuse us later on.  */
15701   clear_cv_and_fold_caches ();
15702 }
15703
15704 /* Finishes the enum type. This is called only the first time an
15705    enumeration is seen, be it opaque or odinary.
15706    ENUMTYPE is the type object.  */
15707
15708 void
15709 finish_enum (tree enumtype)
15710 {
15711   if (processing_template_decl)
15712     {
15713       if (at_function_scope_p ())
15714         add_stmt (build_min (TAG_DEFN, enumtype));
15715       return;
15716     }
15717
15718   /* If this is a forward declaration, there should not be any variants,
15719      though we can get a variant in the middle of an enum-specifier with
15720      wacky code like 'enum E { e = sizeof(const E*) };'  */
15721   gcc_assert (enumtype == TYPE_MAIN_VARIANT (enumtype)
15722               && (TYPE_VALUES (enumtype)
15723                   || !TYPE_NEXT_VARIANT (enumtype)));
15724 }
15725
15726 /* Build and install a CONST_DECL for an enumeration constant of the
15727    enumeration type ENUMTYPE whose NAME and VALUE (if any) are provided.
15728    Apply ATTRIBUTES if available.  LOC is the location of NAME.
15729    Assignment of sequential values by default is handled here.  */
15730
15731 void
15732 build_enumerator (tree name, tree value, tree enumtype, tree attributes,
15733                   location_t loc)
15734 {
15735   tree decl;
15736   tree context;
15737   tree type;
15738
15739   /* scalar_constant_value will pull out this expression, so make sure
15740      it's folded as appropriate.  */
15741   if (processing_template_decl)
15742     value = fold_non_dependent_expr (value);
15743
15744   /* If the VALUE was erroneous, pretend it wasn't there; that will
15745      result in the enum being assigned the next value in sequence.  */
15746   if (value == error_mark_node)
15747     value = NULL_TREE;
15748
15749   /* Remove no-op casts from the value.  */
15750   if (value)
15751     STRIP_TYPE_NOPS (value);
15752
15753   if (! processing_template_decl)
15754     {
15755       /* Validate and default VALUE.  */
15756       if (value != NULL_TREE)
15757         {
15758           if (!ENUM_UNDERLYING_TYPE (enumtype))
15759             {
15760               tree tmp_value = build_expr_type_conversion (WANT_INT | WANT_ENUM,
15761                                                            value, true);
15762               if (tmp_value)
15763                 value = tmp_value;
15764             }
15765           else if (! INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P
15766                    (TREE_TYPE (value)))
15767             value = perform_implicit_conversion_flags
15768               (ENUM_UNDERLYING_TYPE (enumtype), value, tf_warning_or_error,
15769                LOOKUP_IMPLICIT | LOOKUP_NO_NARROWING);
15770
15771           if (value == error_mark_node)
15772             value = NULL_TREE;
15773
15774           if (value != NULL_TREE)
15775             {
15776               if (! INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P
15777                   (TREE_TYPE (value)))
15778                 {
15779                   error_at (cp_expr_loc_or_input_loc (value),
15780                             "enumerator value for %qD must have integral or "
15781                             "unscoped enumeration type", name);
15782                   value = NULL_TREE;
15783                 }
15784               else
15785                 {
15786                   value = cxx_constant_value (value);
15787
15788                   if (TREE_CODE (value) != INTEGER_CST)
15789                     {
15790                       error ("enumerator value for %qD is not an integer "
15791                              "constant", name);
15792                       value = NULL_TREE;
15793                     }
15794                 }
15795             }
15796         }
15797
15798       /* Default based on previous value.  */
15799       if (value == NULL_TREE)
15800         {
15801           if (TYPE_VALUES (enumtype))
15802             {
15803               tree prev_value;
15804
15805               /* C++03 7.2/4: If no initializer is specified for the first
15806                  enumerator, the type is an unspecified integral
15807                  type. Otherwise the type is the same as the type of the
15808                  initializing value of the preceding enumerator unless the
15809                  incremented value is not representable in that type, in
15810                  which case the type is an unspecified integral type
15811                  sufficient to contain the incremented value.  */
15812               prev_value = DECL_INITIAL (TREE_VALUE (TYPE_VALUES (enumtype)));
15813               if (error_operand_p (prev_value))
15814                 value = error_mark_node;
15815               else
15816                 {
15817                   wi::overflow_type overflowed;
15818                   tree type = TREE_TYPE (prev_value);
15819                   signop sgn = TYPE_SIGN (type);
15820                   widest_int wi = wi::add (wi::to_widest (prev_value), 1, sgn,
15821                                            &overflowed);
15822                   if (!overflowed)
15823                     {
15824                       bool pos = !wi::neg_p (wi, sgn);
15825                       if (!wi::fits_to_tree_p (wi, type))
15826                         {
15827                           unsigned int itk;
15828                           for (itk = itk_int; itk != itk_none; itk++)
15829                             {
15830                               type = integer_types[itk];
15831                               if (type != NULL_TREE
15832                                   && (pos || !TYPE_UNSIGNED (type))
15833                                   && wi::fits_to_tree_p (wi, type))
15834                                 break;
15835                             }
15836                           if (type && cxx_dialect < cxx11
15837                               && itk > itk_unsigned_long)
15838                             pedwarn (input_location, OPT_Wlong_long,
15839                                      pos ? G_("\
15840 incremented enumerator value is too large for %<unsigned long%>") : G_("\
15841 incremented enumerator value is too large for %<long%>"));
15842                         }
15843                       if (type == NULL_TREE)
15844                         overflowed = wi::OVF_UNKNOWN;
15845                       else
15846                         value = wide_int_to_tree (type, wi);
15847                     }
15848
15849                   if (overflowed)
15850                     {
15851                       error ("overflow in enumeration values at %qD", name);
15852                       value = error_mark_node;
15853                     }
15854                 }
15855             }
15856           else
15857             value = integer_zero_node;
15858         }
15859
15860       /* Remove no-op casts from the value.  */
15861       STRIP_TYPE_NOPS (value);
15862
15863       /* If the underlying type of the enum is fixed, check whether
15864          the enumerator values fits in the underlying type.  If it
15865          does not fit, the program is ill-formed [C++0x dcl.enum].  */
15866       if (ENUM_UNDERLYING_TYPE (enumtype)
15867           && value
15868           && TREE_CODE (value) == INTEGER_CST)
15869         {
15870           if (!int_fits_type_p (value, ENUM_UNDERLYING_TYPE (enumtype)))
15871             error ("enumerator value %qE is outside the range of underlying "
15872                    "type %qT", value, ENUM_UNDERLYING_TYPE (enumtype));
15873
15874           /* Convert the value to the appropriate type.  */
15875           value = fold_convert (ENUM_UNDERLYING_TYPE (enumtype), value);
15876         }
15877     }
15878
15879   /* C++ associates enums with global, function, or class declarations.  */
15880   context = current_scope ();
15881
15882   /* Build the actual enumeration constant.  Note that the enumeration
15883      constants have the underlying type of the enum (if it is fixed)
15884      or the type of their initializer (if the underlying type of the
15885      enum is not fixed):
15886
15887       [ C++0x dcl.enum ]
15888
15889         If the underlying type is fixed, the type of each enumerator
15890         prior to the closing brace is the underlying type; if the
15891         initializing value of an enumerator cannot be represented by
15892         the underlying type, the program is ill-formed. If the
15893         underlying type is not fixed, the type of each enumerator is
15894         the type of its initializing value.
15895
15896     If the underlying type is not fixed, it will be computed by
15897     finish_enum and we will reset the type of this enumerator.  Of
15898     course, if we're processing a template, there may be no value.  */
15899   type = value ? TREE_TYPE (value) : NULL_TREE;
15900
15901   decl = build_decl (loc, CONST_DECL, name, type);
15902   
15903   DECL_CONTEXT (decl) = enumtype;
15904   TREE_CONSTANT (decl) = 1;
15905   TREE_READONLY (decl) = 1;
15906   DECL_INITIAL (decl) = value;
15907
15908   if (attributes)
15909     cplus_decl_attributes (&decl, attributes, 0);
15910
15911   if (context && context == current_class_type && !SCOPED_ENUM_P (enumtype))
15912     {
15913       /* In something like `struct S { enum E { i = 7 }; };' we put `i'
15914          on the TYPE_FIELDS list for `S'.  (That's so that you can say
15915          things like `S::i' later.)  */
15916
15917       /* The enumerator may be getting declared outside of its enclosing
15918          class, like so:
15919
15920            class S { public: enum E : int; }; enum S::E : int { i = 7; };
15921
15922          For which case we need to make sure that the access of `S::i'
15923          matches the access of `S::E'.  */
15924       tree saved_cas = current_access_specifier;
15925       if (TREE_PRIVATE (TYPE_NAME (enumtype)))
15926         current_access_specifier = access_private_node;
15927       else if (TREE_PROTECTED (TYPE_NAME (enumtype)))
15928         current_access_specifier = access_protected_node;
15929       else
15930         current_access_specifier = access_public_node;
15931
15932       finish_member_declaration (decl);
15933
15934       current_access_specifier = saved_cas;
15935     }
15936   else
15937     pushdecl (decl);
15938
15939   /* Add this enumeration constant to the list for this type.  */
15940   TYPE_VALUES (enumtype) = tree_cons (name, decl, TYPE_VALUES (enumtype));
15941 }
15942
15943 /* Look for an enumerator with the given NAME within the enumeration
15944    type ENUMTYPE.  This routine is used primarily for qualified name
15945    lookup into an enumerator in C++0x, e.g.,
15946
15947      enum class Color { Red, Green, Blue };
15948
15949      Color color = Color::Red;
15950
15951    Returns the value corresponding to the enumerator, or
15952    NULL_TREE if no such enumerator was found.  */
15953 tree
15954 lookup_enumerator (tree enumtype, tree name)
15955 {
15956   tree e;
15957   gcc_assert (enumtype && TREE_CODE (enumtype) == ENUMERAL_TYPE);
15958
15959   e = purpose_member (name, TYPE_VALUES (enumtype));
15960   return e? TREE_VALUE (e) : NULL_TREE;
15961 }
15962
15963 /* Implement LANG_HOOKS_SIMULATE_ENUM_DECL.  */
15964
15965 tree
15966 cxx_simulate_enum_decl (location_t loc, const char *name,
15967                         vec<string_int_pair> values)
15968 {
15969   location_t saved_loc = input_location;
15970   input_location = loc;
15971
15972   tree enumtype = start_enum (get_identifier (name), NULL_TREE, NULL_TREE,
15973                               NULL_TREE, false, NULL);
15974   if (!OPAQUE_ENUM_P (enumtype))
15975     {
15976       error_at (loc, "multiple definition of %q#T", enumtype);
15977       inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
15978               "previous definition here");
15979       return enumtype;
15980     }
15981   SET_OPAQUE_ENUM_P (enumtype, false);
15982   DECL_SOURCE_LOCATION (TYPE_NAME (enumtype)) = loc;
15983
15984   string_int_pair *value;
15985   unsigned int i;
15986   FOR_EACH_VEC_ELT (values, i, value)
15987     build_enumerator (get_identifier (value->first),
15988                       build_int_cst (integer_type_node, value->second),
15989                       enumtype, NULL_TREE, loc);
15990
15991   finish_enum_value_list (enumtype);
15992   finish_enum (enumtype);
15993
15994   input_location = saved_loc;
15995   return enumtype;
15996 }
15997 \f
15998 /* We're defining DECL.  Make sure that its type is OK.  */
15999
16000 static void
16001 check_function_type (tree decl, tree current_function_parms)
16002 {
16003   tree fntype = TREE_TYPE (decl);
16004   tree return_type = complete_type (TREE_TYPE (fntype));
16005
16006   /* In a function definition, arg types must be complete.  */
16007   require_complete_types_for_parms (current_function_parms);
16008
16009   if (dependent_type_p (return_type)
16010       || type_uses_auto (return_type))
16011     return;
16012   if (!COMPLETE_OR_VOID_TYPE_P (return_type))
16013     {
16014       tree args = TYPE_ARG_TYPES (fntype);
16015
16016       error ("return type %q#T is incomplete", return_type);
16017
16018       /* Make it return void instead.  */
16019       if (TREE_CODE (fntype) == METHOD_TYPE)
16020         fntype = build_method_type_directly (TREE_TYPE (TREE_VALUE (args)),
16021                                              void_type_node,
16022                                              TREE_CHAIN (args));
16023       else
16024         fntype = build_function_type (void_type_node, args);
16025       fntype = (cp_build_type_attribute_variant
16026                 (fntype, TYPE_ATTRIBUTES (TREE_TYPE (decl))));
16027       fntype = cxx_copy_lang_qualifiers (fntype, TREE_TYPE (decl));
16028       TREE_TYPE (decl) = fntype;
16029     }
16030   else
16031     {
16032       abstract_virtuals_error (decl, TREE_TYPE (fntype));
16033       maybe_warn_parm_abi (TREE_TYPE (fntype),
16034                            DECL_SOURCE_LOCATION (decl));
16035     }
16036 }
16037
16038 /* True iff FN is an implicitly-defined default constructor.  */
16039
16040 static bool
16041 implicit_default_ctor_p (tree fn)
16042 {
16043   return (DECL_CONSTRUCTOR_P (fn)
16044           && !user_provided_p (fn)
16045           && sufficient_parms_p (FUNCTION_FIRST_USER_PARMTYPE (fn)));
16046 }
16047
16048 /* Clobber the contents of *this to let the back end know that the object
16049    storage is dead when we enter the constructor or leave the destructor.  */
16050
16051 static tree
16052 build_clobber_this ()
16053 {
16054   /* Clobbering an empty base is pointless, and harmful if its one byte
16055      TYPE_SIZE overlays real data.  */
16056   if (is_empty_class (current_class_type))
16057     return void_node;
16058
16059   /* If we have virtual bases, clobber the whole object, but only if we're in
16060      charge.  If we don't have virtual bases, clobber the as-base type so we
16061      don't mess with tail padding.  */
16062   bool vbases = CLASSTYPE_VBASECLASSES (current_class_type);
16063
16064   tree ctype = current_class_type;
16065   if (!vbases)
16066     ctype = CLASSTYPE_AS_BASE (ctype);
16067
16068   tree clobber = build_clobber (ctype);
16069
16070   tree thisref = current_class_ref;
16071   if (ctype != current_class_type)
16072     {
16073       thisref = build_nop (build_reference_type (ctype), current_class_ptr);
16074       thisref = convert_from_reference (thisref);
16075     }
16076
16077   tree exprstmt = build2 (MODIFY_EXPR, void_type_node, thisref, clobber);
16078   if (vbases)
16079     exprstmt = build_if_in_charge (exprstmt);
16080
16081   return exprstmt;
16082 }
16083
16084 /* Create the FUNCTION_DECL for a function definition.
16085    DECLSPECS and DECLARATOR are the parts of the declaration;
16086    they describe the function's name and the type it returns,
16087    but twisted together in a fashion that parallels the syntax of C.
16088
16089    FLAGS is a bitwise or of SF_PRE_PARSED (indicating that the
16090    DECLARATOR is really the DECL for the function we are about to
16091    process and that DECLSPECS should be ignored), SF_INCLASS_INLINE
16092    indicating that the function is an inline defined in-class.
16093
16094    This function creates a binding context for the function body
16095    as well as setting up the FUNCTION_DECL in current_function_decl.
16096
16097    For C++, we must first check whether that datum makes any sense.
16098    For example, "class A local_a(1,2);" means that variable local_a
16099    is an aggregate of type A, which should have a constructor
16100    applied to it with the argument list [1, 2].
16101
16102    On entry, DECL_INITIAL (decl1) should be NULL_TREE or error_mark_node,
16103    or may be a BLOCK if the function has been defined previously
16104    in this translation unit.  On exit, DECL_INITIAL (decl1) will be
16105    error_mark_node if the function has never been defined, or
16106    a BLOCK if the function has been defined somewhere.  */
16107
16108 bool
16109 start_preparsed_function (tree decl1, tree attrs, int flags)
16110 {
16111   tree ctype = NULL_TREE;
16112   tree fntype;
16113   tree restype;
16114   int doing_friend = 0;
16115   cp_binding_level *bl;
16116   tree current_function_parms;
16117   struct c_fileinfo *finfo
16118     = get_fileinfo (LOCATION_FILE (DECL_SOURCE_LOCATION (decl1)));
16119   bool honor_interface;
16120
16121   /* Sanity check.  */
16122   gcc_assert (VOID_TYPE_P (TREE_VALUE (void_list_node)));
16123   gcc_assert (TREE_CHAIN (void_list_node) == NULL_TREE);
16124
16125   fntype = TREE_TYPE (decl1);
16126   if (TREE_CODE (fntype) == METHOD_TYPE)
16127     ctype = TYPE_METHOD_BASETYPE (fntype);
16128
16129   /* ISO C++ 11.4/5.  A friend function defined in a class is in
16130      the (lexical) scope of the class in which it is defined.  */
16131   if (!ctype && DECL_FRIEND_P (decl1))
16132     {
16133       ctype = DECL_FRIEND_CONTEXT (decl1);
16134
16135       /* CTYPE could be null here if we're dealing with a template;
16136          for example, `inline friend float foo()' inside a template
16137          will have no CTYPE set.  */
16138       if (ctype && TREE_CODE (ctype) != RECORD_TYPE)
16139         ctype = NULL_TREE;
16140       else
16141         doing_friend = 1;
16142     }
16143
16144   if (DECL_DECLARED_INLINE_P (decl1)
16145       && lookup_attribute ("noinline", attrs))
16146     warning_at (DECL_SOURCE_LOCATION (decl1), 0,
16147                 "inline function %qD given attribute %qs", decl1, "noinline");
16148
16149   /* Handle gnu_inline attribute.  */
16150   if (GNU_INLINE_P (decl1))
16151     {
16152       DECL_EXTERNAL (decl1) = 1;
16153       DECL_NOT_REALLY_EXTERN (decl1) = 0;
16154       DECL_INTERFACE_KNOWN (decl1) = 1;
16155       DECL_DISREGARD_INLINE_LIMITS (decl1) = 1;
16156     }
16157
16158   if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (decl1))
16159     /* This is a constructor, we must ensure that any default args
16160        introduced by this definition are propagated to the clones
16161        now. The clones are used directly in overload resolution.  */
16162     adjust_clone_args (decl1);
16163
16164   /* Sometimes we don't notice that a function is a static member, and
16165      build a METHOD_TYPE for it.  Fix that up now.  */
16166   gcc_assert (!(ctype != NULL_TREE && DECL_STATIC_FUNCTION_P (decl1)
16167                 && TREE_CODE (TREE_TYPE (decl1)) == METHOD_TYPE));
16168
16169   /* Set up current_class_type, and enter the scope of the class, if
16170      appropriate.  */
16171   if (ctype)
16172     push_nested_class (ctype);
16173   else if (DECL_STATIC_FUNCTION_P (decl1))
16174     push_nested_class (DECL_CONTEXT (decl1));
16175
16176   /* Now that we have entered the scope of the class, we must restore
16177      the bindings for any template parameters surrounding DECL1, if it
16178      is an inline member template.  (Order is important; consider the
16179      case where a template parameter has the same name as a field of
16180      the class.)  It is not until after this point that
16181      PROCESSING_TEMPLATE_DECL is guaranteed to be set up correctly.  */
16182   if (flags & SF_INCLASS_INLINE)
16183     maybe_begin_member_template_processing (decl1);
16184
16185   /* Effective C++ rule 15.  */
16186   if (warn_ecpp
16187       && DECL_ASSIGNMENT_OPERATOR_P (decl1)
16188       && DECL_OVERLOADED_OPERATOR_IS (decl1, NOP_EXPR)
16189       && VOID_TYPE_P (TREE_TYPE (fntype)))
16190     warning (OPT_Weffc__,
16191              "%<operator=%> should return a reference to %<*this%>");
16192
16193   /* Make the init_value nonzero so pushdecl knows this is not tentative.
16194      error_mark_node is replaced below (in poplevel) with the BLOCK.  */
16195   if (!DECL_INITIAL (decl1))
16196     DECL_INITIAL (decl1) = error_mark_node;
16197
16198   /* This function exists in static storage.
16199      (This does not mean `static' in the C sense!)  */
16200   TREE_STATIC (decl1) = 1;
16201
16202   /* We must call push_template_decl after current_class_type is set
16203      up.  (If we are processing inline definitions after exiting a
16204      class scope, current_class_type will be NULL_TREE until set above
16205      by push_nested_class.)  */
16206   if (processing_template_decl)
16207     {
16208       tree newdecl1 = push_template_decl (decl1, DECL_FRIEND_P (decl1));
16209       if (newdecl1 == error_mark_node)
16210         {
16211           if (ctype || DECL_STATIC_FUNCTION_P (decl1))
16212             pop_nested_class ();
16213           return false;
16214         }
16215       decl1 = newdecl1;
16216     }
16217
16218   /* Make sure the parameter and return types are reasonable.  When
16219      you declare a function, these types can be incomplete, but they
16220      must be complete when you define the function.  */
16221   check_function_type (decl1, DECL_ARGUMENTS (decl1));
16222
16223   /* Build the return declaration for the function.  */
16224   restype = TREE_TYPE (fntype);
16225
16226   if (DECL_RESULT (decl1) == NULL_TREE)
16227     {
16228       tree resdecl;
16229
16230       resdecl = build_decl (input_location, RESULT_DECL, 0, restype);
16231       DECL_ARTIFICIAL (resdecl) = 1;
16232       DECL_IGNORED_P (resdecl) = 1;
16233       DECL_RESULT (decl1) = resdecl;
16234
16235       cp_apply_type_quals_to_decl (cp_type_quals (restype), resdecl);
16236     }
16237
16238   /* Record the decl so that the function name is defined.
16239      If we already have a decl for this name, and it is a FUNCTION_DECL,
16240      use the old decl.  */
16241   if (!processing_template_decl && !(flags & SF_PRE_PARSED))
16242     {
16243       /* A specialization is not used to guide overload resolution.  */
16244       if (!DECL_FUNCTION_MEMBER_P (decl1)
16245           && !(DECL_USE_TEMPLATE (decl1) &&
16246                PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl1))))
16247         {
16248           tree olddecl = pushdecl (decl1);
16249
16250           if (olddecl == error_mark_node)
16251             /* If something went wrong when registering the declaration,
16252                use DECL1; we have to have a FUNCTION_DECL to use when
16253                parsing the body of the function.  */
16254             ;
16255           else
16256             {
16257               /* Otherwise, OLDDECL is either a previous declaration
16258                  of the same function or DECL1 itself.  */
16259
16260               if (warn_missing_declarations
16261                   && olddecl == decl1
16262                   && !DECL_MAIN_P (decl1)
16263                   && TREE_PUBLIC (decl1)
16264                   && !DECL_DECLARED_INLINE_P (decl1))
16265                 {
16266                   tree context;
16267
16268                   /* Check whether DECL1 is in an anonymous
16269                      namespace.  */
16270                   for (context = DECL_CONTEXT (decl1);
16271                        context;
16272                        context = DECL_CONTEXT (context))
16273                     {
16274                       if (TREE_CODE (context) == NAMESPACE_DECL
16275                           && DECL_NAME (context) == NULL_TREE)
16276                         break;
16277                     }
16278
16279                   if (context == NULL)
16280                     warning_at (DECL_SOURCE_LOCATION (decl1),
16281                                 OPT_Wmissing_declarations,
16282                                 "no previous declaration for %qD", decl1);
16283                 }
16284
16285               decl1 = olddecl;
16286             }
16287         }
16288       else
16289         {
16290           /* We need to set the DECL_CONTEXT.  */
16291           if (!DECL_CONTEXT (decl1) && DECL_TEMPLATE_INFO (decl1))
16292             DECL_CONTEXT (decl1) = DECL_CONTEXT (DECL_TI_TEMPLATE (decl1));
16293         }
16294       fntype = TREE_TYPE (decl1);
16295       restype = TREE_TYPE (fntype);
16296
16297       /* If #pragma weak applies, mark the decl appropriately now.
16298          The pragma only applies to global functions.  Because
16299          determining whether or not the #pragma applies involves
16300          computing the mangled name for the declaration, we cannot
16301          apply the pragma until after we have merged this declaration
16302          with any previous declarations; if the original declaration
16303          has a linkage specification, that specification applies to
16304          the definition as well, and may affect the mangled name.  */
16305       if (DECL_FILE_SCOPE_P (decl1))
16306         maybe_apply_pragma_weak (decl1);
16307     }
16308
16309   /* We are now in the scope of the function being defined.  */
16310   current_function_decl = decl1;
16311
16312   /* Save the parm names or decls from this function's declarator
16313      where store_parm_decls will find them.  */
16314   current_function_parms = DECL_ARGUMENTS (decl1);
16315
16316   /* Let the user know we're compiling this function.  */
16317   announce_function (decl1);
16318
16319   gcc_assert (DECL_INITIAL (decl1));
16320
16321   /* This function may already have been parsed, in which case just
16322      return; our caller will skip over the body without parsing.  */
16323   if (DECL_INITIAL (decl1) != error_mark_node)
16324     return true;
16325
16326   /* Initialize RTL machinery.  We cannot do this until
16327      CURRENT_FUNCTION_DECL and DECL_RESULT are set up.  We do this
16328      even when processing a template; this is how we get
16329      CFUN set up, and our per-function variables initialized.
16330      FIXME factor out the non-RTL stuff.  */
16331   bl = current_binding_level;
16332   allocate_struct_function (decl1, processing_template_decl);
16333
16334   /* Initialize the language data structures.  Whenever we start
16335      a new function, we destroy temporaries in the usual way.  */
16336   cfun->language = ggc_cleared_alloc<language_function> ();
16337   current_stmt_tree ()->stmts_are_full_exprs_p = 1;
16338   current_binding_level = bl;
16339
16340   /* If we are (erroneously) defining a function that we have already
16341      defined before, wipe out what we knew before.  */
16342   gcc_checking_assert (!DECL_PENDING_INLINE_P (decl1));
16343   FNDECL_USED_AUTO (decl1) = false;
16344   DECL_SAVED_AUTO_RETURN_TYPE (decl1) = NULL;
16345
16346   if (!processing_template_decl && type_uses_auto (restype))
16347     {
16348       FNDECL_USED_AUTO (decl1) = true;
16349       DECL_SAVED_AUTO_RETURN_TYPE (decl1) = restype;
16350     }
16351
16352   /* Start the statement-tree, start the tree now.  */
16353   DECL_SAVED_TREE (decl1) = push_stmt_list ();
16354
16355   if (ctype && !doing_friend && !DECL_STATIC_FUNCTION_P (decl1))
16356     {
16357       /* We know that this was set up by `grokclassfn'.  We do not
16358          wait until `store_parm_decls', since evil parse errors may
16359          never get us to that point.  Here we keep the consistency
16360          between `current_class_type' and `current_class_ptr'.  */
16361       tree t = DECL_ARGUMENTS (decl1);
16362
16363       gcc_assert (t != NULL_TREE && TREE_CODE (t) == PARM_DECL);
16364       gcc_assert (TYPE_PTR_P (TREE_TYPE (t)));
16365
16366       cp_function_chain->x_current_class_ref
16367         = cp_build_fold_indirect_ref (t);
16368       /* Set this second to avoid shortcut in cp_build_indirect_ref.  */
16369       cp_function_chain->x_current_class_ptr = t;
16370
16371       /* Constructors and destructors need to know whether they're "in
16372          charge" of initializing virtual base classes.  */
16373       t = DECL_CHAIN (t);
16374       if (DECL_HAS_IN_CHARGE_PARM_P (decl1))
16375         {
16376           current_in_charge_parm = t;
16377           t = DECL_CHAIN (t);
16378         }
16379       if (DECL_HAS_VTT_PARM_P (decl1))
16380         {
16381           gcc_assert (DECL_NAME (t) == vtt_parm_identifier);
16382           current_vtt_parm = t;
16383         }
16384     }
16385
16386   honor_interface = (!DECL_TEMPLATE_INSTANTIATION (decl1)
16387                      /* Implicitly-defined methods (like the
16388                         destructor for a class in which no destructor
16389                         is explicitly declared) must not be defined
16390                         until their definition is needed.  So, we
16391                         ignore interface specifications for
16392                         compiler-generated functions.  */
16393                      && !DECL_ARTIFICIAL (decl1));
16394
16395   if (processing_template_decl)
16396     /* Don't mess with interface flags.  */;
16397   else if (DECL_INTERFACE_KNOWN (decl1))
16398     {
16399       tree ctx = decl_function_context (decl1);
16400
16401       if (DECL_NOT_REALLY_EXTERN (decl1))
16402         DECL_EXTERNAL (decl1) = 0;
16403
16404       if (ctx != NULL_TREE && vague_linkage_p (ctx))
16405         /* This is a function in a local class in an extern inline
16406            or template function.  */
16407         comdat_linkage (decl1);
16408     }
16409   /* If this function belongs to an interface, it is public.
16410      If it belongs to someone else's interface, it is also external.
16411      This only affects inlines and template instantiations.  */
16412   else if (!finfo->interface_unknown && honor_interface)
16413     {
16414       if (DECL_DECLARED_INLINE_P (decl1)
16415           || DECL_TEMPLATE_INSTANTIATION (decl1))
16416         {
16417           DECL_EXTERNAL (decl1)
16418             = (finfo->interface_only
16419                || (DECL_DECLARED_INLINE_P (decl1)
16420                    && ! flag_implement_inlines
16421                    && !DECL_VINDEX (decl1)));
16422
16423           /* For WIN32 we also want to put these in linkonce sections.  */
16424           maybe_make_one_only (decl1);
16425         }
16426       else
16427         DECL_EXTERNAL (decl1) = 0;
16428       DECL_INTERFACE_KNOWN (decl1) = 1;
16429       /* If this function is in an interface implemented in this file,
16430          make sure that the back end knows to emit this function
16431          here.  */
16432       if (!DECL_EXTERNAL (decl1))
16433         mark_needed (decl1);
16434     }
16435   else if (finfo->interface_unknown && finfo->interface_only
16436            && honor_interface)
16437     {
16438       /* If MULTIPLE_SYMBOL_SPACES is defined and we saw a #pragma
16439          interface, we will have both finfo->interface_unknown and
16440          finfo->interface_only set.  In that case, we don't want to
16441          use the normal heuristics because someone will supply a
16442          #pragma implementation elsewhere, and deducing it here would
16443          produce a conflict.  */
16444       comdat_linkage (decl1);
16445       DECL_EXTERNAL (decl1) = 0;
16446       DECL_INTERFACE_KNOWN (decl1) = 1;
16447       DECL_DEFER_OUTPUT (decl1) = 1;
16448     }
16449   else
16450     {
16451       /* This is a definition, not a reference.
16452          So clear DECL_EXTERNAL, unless this is a GNU extern inline.  */
16453       if (!GNU_INLINE_P (decl1))
16454         DECL_EXTERNAL (decl1) = 0;
16455
16456       if ((DECL_DECLARED_INLINE_P (decl1)
16457            || DECL_TEMPLATE_INSTANTIATION (decl1))
16458           && ! DECL_INTERFACE_KNOWN (decl1))
16459         DECL_DEFER_OUTPUT (decl1) = 1;
16460       else
16461         DECL_INTERFACE_KNOWN (decl1) = 1;
16462     }
16463
16464   /* Determine the ELF visibility attribute for the function.  We must not
16465      do this before calling "pushdecl", as we must allow "duplicate_decls"
16466      to merge any attributes appropriately.  We also need to wait until
16467      linkage is set.  */
16468   if (!DECL_CLONED_FUNCTION_P (decl1))
16469     determine_visibility (decl1);
16470
16471   if (!processing_template_decl)
16472     maybe_instantiate_noexcept (decl1);
16473
16474   begin_scope (sk_function_parms, decl1);
16475
16476   ++function_depth;
16477
16478   if (DECL_DESTRUCTOR_P (decl1)
16479       || (DECL_CONSTRUCTOR_P (decl1)
16480           && targetm.cxx.cdtor_returns_this ()))
16481     {
16482       cdtor_label = create_artificial_label (input_location);
16483       LABEL_DECL_CDTOR (cdtor_label) = true;
16484     }
16485
16486   start_fname_decls ();
16487
16488   store_parm_decls (current_function_parms);
16489
16490   push_operator_bindings ();
16491
16492   if (!processing_template_decl
16493       && (flag_lifetime_dse > 1)
16494       && DECL_CONSTRUCTOR_P (decl1)
16495       && !DECL_CLONED_FUNCTION_P (decl1)
16496       /* Clobbering an empty base is harmful if it overlays real data.  */
16497       && !is_empty_class (current_class_type)
16498       /* We can't clobber safely for an implicitly-defined default constructor
16499          because part of the initialization might happen before we enter the
16500          constructor, via AGGR_INIT_ZERO_FIRST (c++/68006).  */
16501       && !implicit_default_ctor_p (decl1))
16502     finish_expr_stmt (build_clobber_this ());
16503
16504   if (!processing_template_decl
16505       && DECL_CONSTRUCTOR_P (decl1)
16506       && sanitize_flags_p (SANITIZE_VPTR)
16507       && !DECL_CLONED_FUNCTION_P (decl1)
16508       && !implicit_default_ctor_p (decl1))
16509     cp_ubsan_maybe_initialize_vtbl_ptrs (current_class_ptr);
16510
16511   if (!DECL_OMP_DECLARE_REDUCTION_P (decl1))
16512     start_lambda_scope (decl1);
16513
16514   return true;
16515 }
16516
16517
16518 /* Like start_preparsed_function, except that instead of a
16519    FUNCTION_DECL, this function takes DECLSPECS and DECLARATOR.
16520
16521    Returns true on success.  If the DECLARATOR is not suitable
16522    for a function, we return false, which tells the parser to
16523    skip the entire function.  */
16524
16525 bool
16526 start_function (cp_decl_specifier_seq *declspecs,
16527                 const cp_declarator *declarator,
16528                 tree attrs)
16529 {
16530   tree decl1;
16531
16532   decl1 = grokdeclarator (declarator, declspecs, FUNCDEF, 1, &attrs);
16533   invoke_plugin_callbacks (PLUGIN_START_PARSE_FUNCTION, decl1);
16534   if (decl1 == error_mark_node)
16535     return false;
16536
16537   if (DECL_MAIN_P (decl1))
16538     /* main must return int.  grokfndecl should have corrected it
16539        (and issued a diagnostic) if the user got it wrong.  */
16540     gcc_assert (same_type_p (TREE_TYPE (TREE_TYPE (decl1)),
16541                              integer_type_node));
16542
16543   return start_preparsed_function (decl1, attrs, /*flags=*/SF_DEFAULT);
16544 }
16545 \f
16546 /* Returns true iff an EH_SPEC_BLOCK should be created in the body of
16547    FN.  */
16548
16549 static bool
16550 use_eh_spec_block (tree fn)
16551 {
16552   return (flag_exceptions && flag_enforce_eh_specs
16553           && !processing_template_decl
16554           /* We insert the EH_SPEC_BLOCK only in the original
16555              function; then, it is copied automatically to the
16556              clones.  */
16557           && !DECL_CLONED_FUNCTION_P (fn)
16558           /* Implicitly-generated constructors and destructors have
16559              exception specifications.  However, those specifications
16560              are the union of the possible exceptions specified by the
16561              constructors/destructors for bases and members, so no
16562              unallowed exception will ever reach this function.  By
16563              not creating the EH_SPEC_BLOCK we save a little memory,
16564              and we avoid spurious warnings about unreachable
16565              code.  */
16566           && !DECL_DEFAULTED_FN (fn)
16567           && !type_throw_all_p (TREE_TYPE (fn)));
16568 }
16569
16570 /* Helper function to push ARGS into the current lexical scope.  DECL
16571    is the function declaration.  NONPARMS is used to handle enum
16572    constants.  */
16573
16574 void
16575 do_push_parm_decls (tree decl, tree args, tree *nonparms)
16576 {
16577   /* If we're doing semantic analysis, then we'll call pushdecl
16578      for each of these.  We must do them in reverse order so that
16579      they end in the correct forward order.  */
16580   args = nreverse (args);
16581
16582   tree next;
16583   for (tree parm = args; parm; parm = next)
16584     {
16585       next = DECL_CHAIN (parm);
16586       if (TREE_CODE (parm) == PARM_DECL)
16587         pushdecl (parm);
16588       else if (nonparms)
16589         {
16590           /* If we find an enum constant or a type tag, put it aside for
16591              the moment.  */
16592           TREE_CHAIN (parm) = NULL_TREE;
16593           *nonparms = chainon (*nonparms, parm);
16594         }
16595     }
16596
16597   /* Get the decls in their original chain order and record in the
16598      function.  This is all and only the PARM_DECLs that were
16599      pushed into scope by the loop above.  */
16600   DECL_ARGUMENTS (decl) = get_local_decls ();
16601 }
16602
16603 /* Store the parameter declarations into the current function declaration.
16604    This is called after parsing the parameter declarations, before
16605    digesting the body of the function.
16606
16607    Also install to binding contour return value identifier, if any.  */
16608
16609 static void
16610 store_parm_decls (tree current_function_parms)
16611 {
16612   tree fndecl = current_function_decl;
16613
16614   /* This is a chain of any other decls that came in among the parm
16615      declarations.  If a parm is declared with  enum {foo, bar} x;
16616      then CONST_DECLs for foo and bar are put here.  */
16617   tree nonparms = NULL_TREE;
16618
16619   if (current_function_parms)
16620     {
16621       /* This case is when the function was defined with an ANSI prototype.
16622          The parms already have decls, so we need not do anything here
16623          except record them as in effect
16624          and complain if any redundant old-style parm decls were written.  */
16625
16626       tree specparms = current_function_parms;
16627
16628       /* Must clear this because it might contain TYPE_DECLs declared
16629              at class level.  */
16630       current_binding_level->names = NULL;
16631
16632       do_push_parm_decls (fndecl, specparms, &nonparms);
16633     }
16634   else
16635     DECL_ARGUMENTS (fndecl) = NULL_TREE;
16636
16637   /* Now store the final chain of decls for the arguments
16638      as the decl-chain of the current lexical scope.
16639      Put the enumerators in as well, at the front so that
16640      DECL_ARGUMENTS is not modified.  */
16641   current_binding_level->names = chainon (nonparms, DECL_ARGUMENTS (fndecl));
16642
16643   if (use_eh_spec_block (current_function_decl))
16644     current_eh_spec_block = begin_eh_spec_block ();
16645 }
16646
16647 \f
16648 /* Set the return value of the constructor (if present).  */
16649
16650 static void
16651 finish_constructor_body (void)
16652 {
16653   tree val;
16654   tree exprstmt;
16655
16656   if (targetm.cxx.cdtor_returns_this ())
16657     {
16658       /* Any return from a constructor will end up here.  */
16659       add_stmt (build_stmt (input_location, LABEL_EXPR, cdtor_label));
16660
16661       val = DECL_ARGUMENTS (current_function_decl);
16662       val = build2 (MODIFY_EXPR, TREE_TYPE (val),
16663                     DECL_RESULT (current_function_decl), val);
16664       /* Return the address of the object.  */
16665       exprstmt = build_stmt (input_location, RETURN_EXPR, val);
16666       add_stmt (exprstmt);
16667     }
16668 }
16669
16670 /* Do all the processing for the beginning of a destructor; set up the
16671    vtable pointers and cleanups for bases and members.  */
16672
16673 static void
16674 begin_destructor_body (void)
16675 {
16676   tree compound_stmt;
16677
16678   /* If the CURRENT_CLASS_TYPE is incomplete, we will have already
16679      issued an error message.  We still want to try to process the
16680      body of the function, but initialize_vtbl_ptrs will crash if
16681      TYPE_BINFO is NULL.  */
16682   if (COMPLETE_TYPE_P (current_class_type))
16683     {
16684       compound_stmt = begin_compound_stmt (0);
16685       /* Make all virtual function table pointers in non-virtual base
16686          classes point to CURRENT_CLASS_TYPE's virtual function
16687          tables.  */
16688       initialize_vtbl_ptrs (current_class_ptr);
16689       finish_compound_stmt (compound_stmt);
16690
16691       if (flag_lifetime_dse
16692           /* Clobbering an empty base is harmful if it overlays real data.  */
16693           && !is_empty_class (current_class_type))
16694       {
16695         if (sanitize_flags_p (SANITIZE_VPTR)
16696             && (flag_sanitize_recover & SANITIZE_VPTR) == 0
16697             && TYPE_CONTAINS_VPTR_P (current_class_type))
16698           {
16699             tree binfo = TYPE_BINFO (current_class_type);
16700             tree ref
16701               = cp_build_fold_indirect_ref (current_class_ptr);
16702
16703             tree vtbl_ptr = build_vfield_ref (ref, TREE_TYPE (binfo));
16704             tree vtbl = build_zero_cst (TREE_TYPE (vtbl_ptr));
16705             tree stmt = cp_build_modify_expr (input_location, vtbl_ptr,
16706                                               NOP_EXPR, vtbl,
16707                                               tf_warning_or_error);
16708             /* If the vptr is shared with some virtual nearly empty base,
16709                don't clear it if not in charge, the dtor of the virtual
16710                nearly empty base will do that later.  */
16711             if (CLASSTYPE_VBASECLASSES (current_class_type))
16712               {
16713                 tree c = current_class_type;
16714                 while (CLASSTYPE_PRIMARY_BINFO (c))
16715                   {
16716                     if (BINFO_VIRTUAL_P (CLASSTYPE_PRIMARY_BINFO (c)))
16717                       {
16718                         stmt = convert_to_void (stmt, ICV_STATEMENT,
16719                                                 tf_warning_or_error);
16720                         stmt = build_if_in_charge (stmt);
16721                         break;
16722                       }
16723                     c = BINFO_TYPE (CLASSTYPE_PRIMARY_BINFO (c));
16724                   }
16725               }
16726             finish_decl_cleanup (NULL_TREE, stmt);
16727           }
16728         else
16729           finish_decl_cleanup (NULL_TREE, build_clobber_this ());
16730       }
16731
16732       /* And insert cleanups for our bases and members so that they
16733          will be properly destroyed if we throw.  */
16734       push_base_cleanups ();
16735     }
16736 }
16737
16738 /* At the end of every destructor we generate code to delete the object if
16739    necessary.  Do that now.  */
16740
16741 static void
16742 finish_destructor_body (void)
16743 {
16744   tree exprstmt;
16745
16746   /* Any return from a destructor will end up here; that way all base
16747      and member cleanups will be run when the function returns.  */
16748   add_stmt (build_stmt (input_location, LABEL_EXPR, cdtor_label));
16749
16750   if (targetm.cxx.cdtor_returns_this ())
16751     {
16752       tree val;
16753
16754       val = DECL_ARGUMENTS (current_function_decl);
16755       val = build2 (MODIFY_EXPR, TREE_TYPE (val),
16756                     DECL_RESULT (current_function_decl), val);
16757       /* Return the address of the object.  */
16758       exprstmt = build_stmt (input_location, RETURN_EXPR, val);
16759       add_stmt (exprstmt);
16760     }
16761 }
16762
16763 /* Do the necessary processing for the beginning of a function body, which
16764    in this case includes member-initializers, but not the catch clauses of
16765    a function-try-block.  Currently, this means opening a binding level
16766    for the member-initializers (in a ctor), member cleanups (in a dtor),
16767    and capture proxies (in a lambda operator()).  */
16768
16769 tree
16770 begin_function_body (void)
16771 {
16772   if (! FUNCTION_NEEDS_BODY_BLOCK (current_function_decl))
16773     return NULL_TREE;
16774
16775   if (processing_template_decl)
16776     /* Do nothing now.  */;
16777   else
16778     /* Always keep the BLOCK node associated with the outermost pair of
16779        curly braces of a function.  These are needed for correct
16780        operation of dwarfout.c.  */
16781     keep_next_level (true);
16782
16783   tree stmt = begin_compound_stmt (BCS_FN_BODY);
16784
16785   if (processing_template_decl)
16786     /* Do nothing now.  */;
16787   else if (DECL_DESTRUCTOR_P (current_function_decl))
16788     begin_destructor_body ();
16789
16790   return stmt;
16791 }
16792
16793 /* Do the processing for the end of a function body.  Currently, this means
16794    closing out the cleanups for fully-constructed bases and members, and in
16795    the case of the destructor, deleting the object if desired.  Again, this
16796    is only meaningful for [cd]tors, since they are the only functions where
16797    there is a significant distinction between the main body and any
16798    function catch clauses.  Handling, say, main() return semantics here
16799    would be wrong, as flowing off the end of a function catch clause for
16800    main() would also need to return 0.  */
16801
16802 void
16803 finish_function_body (tree compstmt)
16804 {
16805   if (compstmt == NULL_TREE)
16806     return;
16807
16808   /* Close the block.  */
16809   finish_compound_stmt (compstmt);
16810
16811   if (processing_template_decl)
16812     /* Do nothing now.  */;
16813   else if (DECL_CONSTRUCTOR_P (current_function_decl))
16814     finish_constructor_body ();
16815   else if (DECL_DESTRUCTOR_P (current_function_decl))
16816     finish_destructor_body ();
16817 }
16818
16819 /* Given a function, returns the BLOCK corresponding to the outermost level
16820    of curly braces, skipping the artificial block created for constructor
16821    initializers.  */
16822
16823 tree
16824 outer_curly_brace_block (tree fndecl)
16825 {
16826   tree block = DECL_INITIAL (fndecl);
16827   if (BLOCK_OUTER_CURLY_BRACE_P (block))
16828     return block;
16829   block = BLOCK_SUBBLOCKS (block);
16830   if (BLOCK_OUTER_CURLY_BRACE_P (block))
16831     return block;
16832   block = BLOCK_SUBBLOCKS (block);
16833   gcc_assert (BLOCK_OUTER_CURLY_BRACE_P (block));
16834   return block;
16835 }
16836
16837 /* If FNDECL is a class's key method, add the class to the list of
16838    keyed classes that should be emitted.  */
16839
16840 static void
16841 record_key_method_defined (tree fndecl)
16842 {
16843   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
16844       && DECL_VIRTUAL_P (fndecl)
16845       && !processing_template_decl)
16846     {
16847       tree fnclass = DECL_CONTEXT (fndecl);
16848       if (fndecl == CLASSTYPE_KEY_METHOD (fnclass))
16849         vec_safe_push (keyed_classes, fnclass);
16850     }
16851 }
16852
16853 /* Subroutine of finish_function.
16854    Save the body of constexpr functions for possible
16855    future compile time evaluation.  */
16856
16857 static void
16858 maybe_save_function_definition (tree fun)
16859 {
16860   if (!processing_template_decl
16861       && DECL_DECLARED_CONSTEXPR_P (fun)
16862       && !cp_function_chain->invalid_constexpr
16863       && !DECL_CLONED_FUNCTION_P (fun))
16864     register_constexpr_fundef (fun, DECL_SAVED_TREE (fun));
16865 }
16866
16867 /* Attempt to add a fix-it hint to RICHLOC suggesting the insertion
16868    of "return *this;" immediately before its location, using FNDECL's
16869    first statement (if any) to give the indentation, if appropriate.  */
16870
16871 static void
16872 add_return_star_this_fixit (gcc_rich_location *richloc, tree fndecl)
16873 {
16874   location_t indent = UNKNOWN_LOCATION;
16875   tree stmts = expr_first (DECL_SAVED_TREE (fndecl));
16876   if (stmts)
16877     indent = EXPR_LOCATION (stmts);
16878   richloc->add_fixit_insert_formatted ("return *this;",
16879                                        richloc->get_loc (),
16880                                        indent);
16881 }
16882
16883 /* This function carries out the subset of finish_function operations needed
16884    to emit the compiler-generated outlined helper functions used by the
16885    coroutines implementation.  */
16886
16887 static void
16888 emit_coro_helper (tree helper)
16889 {
16890   /* This is a partial set of the operations done by finish_function()
16891      plus emitting the result.  */
16892   set_cfun (NULL);
16893   current_function_decl = helper;
16894   begin_scope (sk_function_parms, NULL);
16895   store_parm_decls (DECL_ARGUMENTS (helper));
16896   announce_function (helper);
16897   allocate_struct_function (helper, false);
16898   cfun->language = ggc_cleared_alloc<language_function> ();
16899   poplevel (1, 0, 1);
16900   maybe_save_function_definition (helper);
16901   /* We must start each function with a clear fold cache.  */
16902   clear_fold_cache ();
16903   cp_fold_function (helper);
16904   DECL_CONTEXT (DECL_RESULT (helper)) = helper;
16905   BLOCK_SUPERCONTEXT (DECL_INITIAL (helper)) = helper;
16906   /* This function has coroutine IFNs that we should handle in middle
16907      end lowering.  */
16908   cfun->coroutine_component = true;
16909   cp_genericize (helper);
16910   expand_or_defer_fn (helper);
16911 }
16912
16913 /* Finish up a function declaration and compile that function
16914    all the way to assembler language output.  The free the storage
16915    for the function definition. INLINE_P is TRUE if we just
16916    finished processing the body of an in-class inline function
16917    definition.  (This processing will have taken place after the
16918    class definition is complete.)  */
16919
16920 tree
16921 finish_function (bool inline_p)
16922 {
16923   tree fndecl = current_function_decl;
16924   tree fntype, ctype = NULL_TREE;
16925   tree resumer = NULL_TREE, destroyer = NULL_TREE;
16926   bool coro_p = flag_coroutines
16927                 && !processing_template_decl
16928                 && DECL_COROUTINE_P (fndecl);
16929   bool coro_emit_helpers = false;
16930
16931   /* When we get some parse errors, we can end up without a
16932      current_function_decl, so cope.  */
16933   if (fndecl == NULL_TREE)
16934     return error_mark_node;
16935
16936   if (!DECL_OMP_DECLARE_REDUCTION_P (fndecl))
16937     finish_lambda_scope ();
16938
16939   if (c_dialect_objc ())
16940     objc_finish_function ();
16941
16942   record_key_method_defined (fndecl);
16943
16944   fntype = TREE_TYPE (fndecl);
16945
16946   /*  TREE_READONLY (fndecl) = 1;
16947       This caused &foo to be of type ptr-to-const-function
16948       which then got a warning when stored in a ptr-to-function variable.  */
16949
16950   gcc_assert (building_stmt_list_p ());
16951   /* The current function is being defined, so its DECL_INITIAL should
16952      be set, and unless there's a multiple definition, it should be
16953      error_mark_node.  */
16954   gcc_assert (DECL_INITIAL (fndecl) == error_mark_node);
16955
16956   if (coro_p)
16957     {
16958       /* Only try to emit the coroutine outlined helper functions if the
16959          transforms succeeded.  Otherwise, treat errors in the same way as
16960          a regular function.  */
16961       coro_emit_helpers = morph_fn_to_coro (fndecl, &resumer, &destroyer);
16962
16963       /* We should handle coroutine IFNs in middle end lowering.  */
16964       cfun->coroutine_component = true;
16965
16966       /* Do not try to process the ramp's EH unless outlining succeeded.  */
16967       if (coro_emit_helpers && use_eh_spec_block (fndecl))
16968         finish_eh_spec_block (TYPE_RAISES_EXCEPTIONS
16969                               (TREE_TYPE (fndecl)),
16970                               current_eh_spec_block);
16971     }
16972   else
16973   /* For a cloned function, we've already got all the code we need;
16974      there's no need to add any extra bits.  */
16975   if (!DECL_CLONED_FUNCTION_P (fndecl))
16976     {
16977       /* Make it so that `main' always returns 0 by default.  */
16978       if (DECL_MAIN_P (current_function_decl))
16979         finish_return_stmt (integer_zero_node);
16980
16981       if (use_eh_spec_block (current_function_decl))
16982         finish_eh_spec_block (TYPE_RAISES_EXCEPTIONS
16983                               (TREE_TYPE (current_function_decl)),
16984                               current_eh_spec_block);
16985     }
16986
16987   /* If we're saving up tree structure, tie off the function now.  */
16988   DECL_SAVED_TREE (fndecl) = pop_stmt_list (DECL_SAVED_TREE (fndecl));
16989
16990   finish_fname_decls ();
16991
16992   /* If this function can't throw any exceptions, remember that.  */
16993   if (!processing_template_decl
16994       && !cp_function_chain->can_throw
16995       && !flag_non_call_exceptions
16996       && !decl_replaceable_p (fndecl))
16997     TREE_NOTHROW (fndecl) = 1;
16998
16999   /* This must come after expand_function_end because cleanups might
17000      have declarations (from inline functions) that need to go into
17001      this function's blocks.  */
17002
17003   /* If the current binding level isn't the outermost binding level
17004      for this function, either there is a bug, or we have experienced
17005      syntax errors and the statement tree is malformed.  */
17006   if (current_binding_level->kind != sk_function_parms)
17007     {
17008       /* Make sure we have already experienced errors.  */
17009       gcc_assert (errorcount);
17010
17011       /* Throw away the broken statement tree and extra binding
17012          levels.  */
17013       DECL_SAVED_TREE (fndecl) = alloc_stmt_list ();
17014
17015       while (current_binding_level->kind != sk_function_parms)
17016         {
17017           if (current_binding_level->kind == sk_class)
17018             pop_nested_class ();
17019           else
17020             poplevel (0, 0, 0);
17021         }
17022     }
17023   poplevel (1, 0, 1);
17024
17025   /* Statements should always be full-expressions at the outermost set
17026      of curly braces for a function.  */
17027   gcc_assert (stmts_are_full_exprs_p ());
17028
17029   /* If there are no return statements in a function with auto return type,
17030      the return type is void.  But if the declared type is something like
17031      auto*, this is an error.  */
17032   if (!processing_template_decl && FNDECL_USED_AUTO (fndecl)
17033       && TREE_TYPE (fntype) == DECL_SAVED_AUTO_RETURN_TYPE (fndecl))
17034     {
17035       if (is_auto (DECL_SAVED_AUTO_RETURN_TYPE (fndecl))
17036           && !current_function_returns_value
17037           && !current_function_returns_null)
17038         {
17039           /* We haven't applied return type deduction because we haven't
17040              seen any return statements. Do that now.  */
17041           tree node = type_uses_auto (DECL_SAVED_AUTO_RETURN_TYPE (fndecl));
17042           do_auto_deduction (DECL_SAVED_AUTO_RETURN_TYPE (fndecl),
17043                              void_node, node, tf_warning_or_error,
17044                              adc_return_type);
17045
17046           apply_deduced_return_type (fndecl, void_type_node);
17047           fntype = TREE_TYPE (fndecl);
17048         }
17049       else if (!current_function_returns_value
17050                && !current_function_returns_null)
17051         {
17052           error ("no return statements in function returning %qT",
17053                  DECL_SAVED_AUTO_RETURN_TYPE (fndecl));
17054           inform (input_location, "only plain %<auto%> return type can be "
17055                   "deduced to %<void%>");
17056         }
17057     }
17058
17059   /* Remember that we were in class scope.  */
17060   if (current_class_name)
17061     ctype = current_class_type;
17062
17063   if (DECL_DELETED_FN (fndecl))
17064     {
17065       DECL_INITIAL (fndecl) = error_mark_node;
17066       DECL_SAVED_TREE (fndecl) = NULL_TREE;
17067       goto cleanup;
17068     }
17069
17070   // If this is a concept, check that the definition is reasonable.
17071   if (DECL_DECLARED_CONCEPT_P (fndecl))
17072     check_function_concept (fndecl);
17073
17074   if (flag_openmp)
17075     if (tree attr = lookup_attribute ("omp declare variant base",
17076                                       DECL_ATTRIBUTES (fndecl)))
17077       omp_declare_variant_finalize (fndecl, attr);
17078
17079   /* Complain if there's just no return statement.  */
17080   if ((warn_return_type
17081        || (cxx_dialect >= cxx14
17082            && DECL_DECLARED_CONSTEXPR_P (fndecl)))
17083       && !VOID_TYPE_P (TREE_TYPE (fntype))
17084       && !dependent_type_p (TREE_TYPE (fntype))
17085       && !current_function_returns_value && !current_function_returns_null
17086       /* Don't complain if we abort or throw.  */
17087       && !current_function_returns_abnormally
17088       /* Don't complain if there's an infinite loop.  */
17089       && !current_function_infinite_loop
17090       /* Don't complain if we are declared noreturn.  */
17091       && !TREE_THIS_VOLATILE (fndecl)
17092       && !DECL_NAME (DECL_RESULT (fndecl))
17093       && !TREE_NO_WARNING (fndecl)
17094       /* Structor return values (if any) are set by the compiler.  */
17095       && !DECL_CONSTRUCTOR_P (fndecl)
17096       && !DECL_DESTRUCTOR_P (fndecl)
17097       && targetm.warn_func_return (fndecl))
17098     {
17099       gcc_rich_location richloc (input_location);
17100       /* Potentially add a "return *this;" fix-it hint for
17101          assignment operators.  */
17102       if (IDENTIFIER_ASSIGN_OP_P (DECL_NAME (fndecl)))
17103         {
17104           tree valtype = TREE_TYPE (DECL_RESULT (fndecl));
17105           if (TREE_CODE (valtype) == REFERENCE_TYPE
17106               && current_class_ref
17107               && same_type_ignoring_top_level_qualifiers_p
17108                   (TREE_TYPE (valtype), TREE_TYPE (current_class_ref))
17109               && global_dc->option_enabled (OPT_Wreturn_type,
17110                                             global_dc->lang_mask,
17111                                             global_dc->option_state))
17112             add_return_star_this_fixit (&richloc, fndecl);
17113         }
17114       if (cxx_dialect >= cxx14
17115           && DECL_DECLARED_CONSTEXPR_P (fndecl))
17116         error_at (&richloc, "no return statement in %<constexpr%> function "
17117                             "returning non-void");
17118       else if (warning_at (&richloc, OPT_Wreturn_type,
17119                            "no return statement in function returning "
17120                            "non-void"))
17121         TREE_NO_WARNING (fndecl) = 1;
17122     }
17123
17124   /* Lambda closure members are implicitly constexpr if possible.  */
17125   if (cxx_dialect >= cxx17
17126       && LAMBDA_TYPE_P (CP_DECL_CONTEXT (fndecl)))
17127     DECL_DECLARED_CONSTEXPR_P (fndecl)
17128       = ((processing_template_decl
17129           || is_valid_constexpr_fn (fndecl, /*complain*/false))
17130          && potential_constant_expression (DECL_SAVED_TREE (fndecl)));
17131
17132   /* Save constexpr function body before it gets munged by
17133      the NRV transformation.   */
17134   maybe_save_function_definition (fndecl);
17135
17136   /* Invoke the pre-genericize plugin before we start munging things.  */
17137   if (!processing_template_decl)
17138     invoke_plugin_callbacks (PLUGIN_PRE_GENERICIZE, fndecl);
17139
17140   /* Perform delayed folding before NRV transformation.  */
17141   if (!processing_template_decl
17142       && !DECL_IMMEDIATE_FUNCTION_P (fndecl)
17143       && !DECL_OMP_DECLARE_REDUCTION_P (fndecl))
17144     cp_fold_function (fndecl);
17145
17146   /* Set up the named return value optimization, if we can.  Candidate
17147      variables are selected in check_return_expr.  */
17148   if (current_function_return_value)
17149     {
17150       tree r = current_function_return_value;
17151       tree outer;
17152
17153       if (r != error_mark_node
17154           /* This is only worth doing for fns that return in memory--and
17155              simpler, since we don't have to worry about promoted modes.  */
17156           && aggregate_value_p (TREE_TYPE (TREE_TYPE (fndecl)), fndecl)
17157           /* Only allow this for variables declared in the outer scope of
17158              the function so we know that their lifetime always ends with a
17159              return; see g++.dg/opt/nrv6.C.  We could be more flexible if
17160              we were to do this optimization in tree-ssa.  */
17161           && (outer = outer_curly_brace_block (fndecl))
17162           && chain_member (r, BLOCK_VARS (outer)))
17163         finalize_nrv (&DECL_SAVED_TREE (fndecl), r, DECL_RESULT (fndecl));
17164
17165       current_function_return_value = NULL_TREE;
17166     }
17167
17168   /* Must mark the RESULT_DECL as being in this function.  */
17169   DECL_CONTEXT (DECL_RESULT (fndecl)) = fndecl;
17170
17171   /* Set the BLOCK_SUPERCONTEXT of the outermost function scope to point
17172      to the FUNCTION_DECL node itself.  */
17173   BLOCK_SUPERCONTEXT (DECL_INITIAL (fndecl)) = fndecl;
17174
17175   /* Store the end of the function, so that we get good line number
17176      info for the epilogue.  */
17177   cfun->function_end_locus = input_location;
17178
17179   /* Complain about parameters that are only set, but never otherwise used.  */
17180   if (warn_unused_but_set_parameter
17181       && !processing_template_decl
17182       && errorcount == unused_but_set_errorcount
17183       && !DECL_CLONED_FUNCTION_P (fndecl))
17184     {
17185       tree decl;
17186
17187       for (decl = DECL_ARGUMENTS (fndecl);
17188            decl;
17189            decl = DECL_CHAIN (decl))
17190         if (TREE_USED (decl)
17191             && TREE_CODE (decl) == PARM_DECL
17192             && !DECL_READ_P (decl)
17193             && DECL_NAME (decl)
17194             && !DECL_ARTIFICIAL (decl)
17195             && !TREE_NO_WARNING (decl)
17196             && !DECL_IN_SYSTEM_HEADER (decl)
17197             && TREE_TYPE (decl) != error_mark_node
17198             && !TYPE_REF_P (TREE_TYPE (decl))
17199             && (!CLASS_TYPE_P (TREE_TYPE (decl))
17200                 || !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (decl))))
17201           warning_at (DECL_SOURCE_LOCATION (decl),
17202                       OPT_Wunused_but_set_parameter,
17203                       "parameter %qD set but not used", decl);
17204       unused_but_set_errorcount = errorcount;
17205     }
17206
17207   /* Complain about locally defined typedefs that are not used in this
17208      function.  */
17209   maybe_warn_unused_local_typedefs ();
17210
17211   /* Possibly warn about unused parameters.  */
17212   if (warn_unused_parameter
17213       && !processing_template_decl 
17214       && !DECL_CLONED_FUNCTION_P (fndecl))
17215     do_warn_unused_parameter (fndecl);
17216
17217   /* Genericize before inlining.  */
17218   if (!processing_template_decl
17219       && !DECL_IMMEDIATE_FUNCTION_P (fndecl)
17220       && !DECL_OMP_DECLARE_REDUCTION_P (fndecl))
17221     cp_genericize (fndecl);
17222
17223   /* Emit the resumer and destroyer functions now, providing that we have
17224      not encountered some fatal error.  */
17225   if (coro_emit_helpers)
17226     {
17227       emit_coro_helper (resumer);
17228       emit_coro_helper (destroyer);
17229     }
17230
17231  cleanup:
17232   /* We're leaving the context of this function, so zap cfun.  It's still in
17233      DECL_STRUCT_FUNCTION, and we'll restore it in tree_rest_of_compilation.  */
17234   set_cfun (NULL);
17235   current_function_decl = NULL;
17236
17237   /* If this is an in-class inline definition, we may have to pop the
17238      bindings for the template parameters that we added in
17239      maybe_begin_member_template_processing when start_function was
17240      called.  */
17241   if (inline_p)
17242     maybe_end_member_template_processing ();
17243
17244   /* Leave the scope of the class.  */
17245   if (ctype)
17246     pop_nested_class ();
17247
17248   --function_depth;
17249
17250   /* Clean up.  */
17251   current_function_decl = NULL_TREE;
17252
17253   invoke_plugin_callbacks (PLUGIN_FINISH_PARSE_FUNCTION, fndecl);
17254   return fndecl;
17255 }
17256 \f
17257 /* Create the FUNCTION_DECL for a function definition.
17258    DECLSPECS and DECLARATOR are the parts of the declaration;
17259    they describe the return type and the name of the function,
17260    but twisted together in a fashion that parallels the syntax of C.
17261
17262    This function creates a binding context for the function body
17263    as well as setting up the FUNCTION_DECL in current_function_decl.
17264
17265    Returns a FUNCTION_DECL on success.
17266
17267    If the DECLARATOR is not suitable for a function (it defines a datum
17268    instead), we return 0, which tells yyparse to report a parse error.
17269
17270    May return void_type_node indicating that this method is actually
17271    a friend.  See grokfield for more details.
17272
17273    Came here with a `.pushlevel' .
17274
17275    DO NOT MAKE ANY CHANGES TO THIS CODE WITHOUT MAKING CORRESPONDING
17276    CHANGES TO CODE IN `grokfield'.  */
17277
17278 tree
17279 grokmethod (cp_decl_specifier_seq *declspecs,
17280             const cp_declarator *declarator, tree attrlist)
17281 {
17282   tree fndecl = grokdeclarator (declarator, declspecs, MEMFUNCDEF, 0,
17283                                 &attrlist);
17284
17285   if (fndecl == error_mark_node)
17286     return error_mark_node;
17287
17288   if (attrlist)
17289     cplus_decl_attributes (&fndecl, attrlist, 0);
17290
17291   /* Pass friends other than inline friend functions back.  */
17292   if (fndecl == void_type_node)
17293     return fndecl;
17294
17295   if (DECL_IN_AGGR_P (fndecl))
17296     {
17297       if (DECL_CLASS_SCOPE_P (fndecl))
17298         error ("%qD is already defined in class %qT", fndecl,
17299                DECL_CONTEXT (fndecl));
17300       return error_mark_node;
17301     }
17302
17303   check_template_shadow (fndecl);
17304
17305   if (TREE_PUBLIC (fndecl))
17306     DECL_COMDAT (fndecl) = 1;
17307   DECL_DECLARED_INLINE_P (fndecl) = 1;
17308   DECL_NO_INLINE_WARNING_P (fndecl) = 1;
17309
17310   /* We process method specializations in finish_struct_1.  */
17311   if (processing_template_decl && !DECL_TEMPLATE_SPECIALIZATION (fndecl))
17312     {
17313       fndecl = push_template_decl (fndecl, DECL_FRIEND_P (fndecl));
17314       if (fndecl == error_mark_node)
17315         return fndecl;
17316     }
17317
17318   if (! DECL_FRIEND_P (fndecl))
17319     {
17320       if (DECL_CHAIN (fndecl))
17321         {
17322           fndecl = copy_node (fndecl);
17323           TREE_CHAIN (fndecl) = NULL_TREE;
17324         }
17325     }
17326
17327   cp_finish_decl (fndecl, NULL_TREE, false, NULL_TREE, 0);
17328
17329   DECL_IN_AGGR_P (fndecl) = 1;
17330   return fndecl;
17331 }
17332 \f
17333
17334 /* VAR is a VAR_DECL.  If its type is incomplete, remember VAR so that
17335    we can lay it out later, when and if its type becomes complete.
17336
17337    Also handle constexpr variables where the initializer involves
17338    an unlowered PTRMEM_CST because the class isn't complete yet.  */
17339
17340 void
17341 maybe_register_incomplete_var (tree var)
17342 {
17343   gcc_assert (VAR_P (var));
17344
17345   /* Keep track of variables with incomplete types.  */
17346   if (!processing_template_decl && TREE_TYPE (var) != error_mark_node
17347       && DECL_EXTERNAL (var))
17348     {
17349       tree inner_type = TREE_TYPE (var);
17350
17351       while (TREE_CODE (inner_type) == ARRAY_TYPE)
17352         inner_type = TREE_TYPE (inner_type);
17353       inner_type = TYPE_MAIN_VARIANT (inner_type);
17354
17355       if ((!COMPLETE_TYPE_P (inner_type) && CLASS_TYPE_P (inner_type))
17356           /* RTTI TD entries are created while defining the type_info.  */
17357           || (TYPE_LANG_SPECIFIC (inner_type)
17358               && TYPE_BEING_DEFINED (inner_type)))
17359         {
17360           incomplete_var iv = {var, inner_type};
17361           vec_safe_push (incomplete_vars, iv);
17362         }
17363       else if (!(DECL_LANG_SPECIFIC (var) && DECL_TEMPLATE_INFO (var))
17364                && decl_constant_var_p (var)
17365                && (TYPE_PTRMEM_P (inner_type) || CLASS_TYPE_P (inner_type)))
17366         {
17367           /* When the outermost open class is complete we can resolve any
17368              pointers-to-members.  */
17369           tree context = outermost_open_class ();
17370           incomplete_var iv = {var, context};
17371           vec_safe_push (incomplete_vars, iv);
17372         }
17373     }
17374 }
17375
17376 /* Called when a class type (given by TYPE) is defined.  If there are
17377    any existing VAR_DECLs whose type has been completed by this
17378    declaration, update them now.  */
17379
17380 void
17381 complete_vars (tree type)
17382 {
17383   unsigned ix;
17384   incomplete_var *iv;
17385
17386   for (ix = 0; vec_safe_iterate (incomplete_vars, ix, &iv); )
17387     {
17388       if (same_type_p (type, iv->incomplete_type))
17389         {
17390           tree var = iv->decl;
17391           tree type = TREE_TYPE (var);
17392
17393           if (type != error_mark_node
17394               && (TYPE_MAIN_VARIANT (strip_array_types (type))
17395                   == iv->incomplete_type))
17396             {
17397               /* Complete the type of the variable.  */
17398               complete_type (type);
17399               cp_apply_type_quals_to_decl (cp_type_quals (type), var);
17400               if (COMPLETE_TYPE_P (type))
17401                 layout_var_decl (var);
17402             }
17403
17404           /* Remove this entry from the list.  */
17405           incomplete_vars->unordered_remove (ix);
17406         }
17407       else
17408         ix++;
17409     }
17410
17411   /* Check for pending declarations which may have abstract type.  */
17412   complete_type_check_abstract (type);
17413 }
17414
17415 /* If DECL is of a type which needs a cleanup, build and return an
17416    expression to perform that cleanup here.  Return NULL_TREE if no
17417    cleanup need be done.  DECL can also be a _REF when called from
17418    split_nonconstant_init_1.  */
17419
17420 tree
17421 cxx_maybe_build_cleanup (tree decl, tsubst_flags_t complain)
17422 {
17423   tree type;
17424   tree attr;
17425   tree cleanup;
17426
17427   /* Assume no cleanup is required.  */
17428   cleanup = NULL_TREE;
17429
17430   if (error_operand_p (decl))
17431     return cleanup;
17432
17433   /* Handle "__attribute__((cleanup))".  We run the cleanup function
17434      before the destructor since the destructor is what actually
17435      terminates the lifetime of the object.  */
17436   if (DECL_P (decl))
17437     attr = lookup_attribute ("cleanup", DECL_ATTRIBUTES (decl));
17438   else
17439     attr = NULL_TREE;
17440   if (attr)
17441     {
17442       tree id;
17443       tree fn;
17444       tree arg;
17445
17446       /* Get the name specified by the user for the cleanup function.  */
17447       id = TREE_VALUE (TREE_VALUE (attr));
17448       /* Look up the name to find the cleanup function to call.  It is
17449          important to use lookup_name here because that is what is
17450          used in c-common.c:handle_cleanup_attribute when performing
17451          initial checks on the attribute.  Note that those checks
17452          include ensuring that the function found is not an overloaded
17453          function, or an object with an overloaded call operator,
17454          etc.; we can rely on the fact that the function found is an
17455          ordinary FUNCTION_DECL.  */
17456       fn = lookup_name (id);
17457       arg = build_address (decl);
17458       if (!mark_used (decl, complain) && !(complain & tf_error))
17459         return error_mark_node;
17460       cleanup = cp_build_function_call_nary (fn, complain, arg, NULL_TREE);
17461       if (cleanup == error_mark_node)
17462         return error_mark_node;
17463     }
17464   /* Handle ordinary C++ destructors.  */
17465   type = TREE_TYPE (decl);
17466   if (type_build_dtor_call (type))
17467     {
17468       int flags = LOOKUP_NORMAL|LOOKUP_NONVIRTUAL|LOOKUP_DESTRUCTOR;
17469       tree addr;
17470       tree call;
17471
17472       if (TREE_CODE (type) == ARRAY_TYPE)
17473         addr = decl;
17474       else
17475         addr = build_address (decl);
17476
17477       call = build_delete (input_location, TREE_TYPE (addr), addr,
17478                            sfk_complete_destructor, flags, 0, complain);
17479       if (call == error_mark_node)
17480         cleanup = error_mark_node;
17481       else if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
17482         /* Discard the call.  */;
17483       else if (decl_maybe_constant_destruction (decl, type)
17484                && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
17485         cxx_constant_dtor (call, decl);
17486       else if (cleanup)
17487         cleanup = cp_build_compound_expr (cleanup, call, complain);
17488       else
17489         cleanup = call;
17490     }
17491
17492   /* build_delete sets the location of the destructor call to the
17493      current location, even though the destructor is going to be
17494      called later, at the end of the current scope.  This can lead to
17495      a "jumpy" behavior for users of debuggers when they step around
17496      the end of the block.  So let's unset the location of the
17497      destructor call instead.  */
17498   protected_set_expr_location (cleanup, UNKNOWN_LOCATION);
17499   if (cleanup && CONVERT_EXPR_P (cleanup))
17500     protected_set_expr_location (TREE_OPERAND (cleanup, 0), UNKNOWN_LOCATION);
17501
17502   if (cleanup
17503       && DECL_P (decl)
17504       && !lookup_attribute ("warn_unused", TYPE_ATTRIBUTES (TREE_TYPE (decl)))
17505       /* Treat objects with destructors as used; the destructor may do
17506          something substantive.  */
17507       && !mark_used (decl, complain) && !(complain & tf_error))
17508     return error_mark_node;
17509
17510   if (cleanup && cfun && !processing_template_decl
17511       && !expr_noexcept_p (cleanup, tf_none))
17512     cp_function_chain->throwing_cleanup = true;
17513
17514   return cleanup;
17515 }
17516
17517 \f
17518 /* Return the FUNCTION_TYPE that corresponds to MEMFNTYPE, which can be a
17519    FUNCTION_DECL, METHOD_TYPE, FUNCTION_TYPE, pointer or reference to
17520    METHOD_TYPE or FUNCTION_TYPE, or pointer to member function.  */
17521
17522 tree
17523 static_fn_type (tree memfntype)
17524 {
17525   tree fntype;
17526   tree args;
17527
17528   if (TYPE_PTRMEMFUNC_P (memfntype))
17529     memfntype = TYPE_PTRMEMFUNC_FN_TYPE (memfntype);
17530   if (INDIRECT_TYPE_P (memfntype)
17531       || TREE_CODE (memfntype) == FUNCTION_DECL)
17532     memfntype = TREE_TYPE (memfntype);
17533   if (TREE_CODE (memfntype) == FUNCTION_TYPE)
17534     return memfntype;
17535   gcc_assert (TREE_CODE (memfntype) == METHOD_TYPE);
17536   args = TYPE_ARG_TYPES (memfntype);
17537   fntype = build_function_type (TREE_TYPE (memfntype), TREE_CHAIN (args));
17538   fntype = apply_memfn_quals (fntype, type_memfn_quals (memfntype));
17539   fntype = (cp_build_type_attribute_variant
17540             (fntype, TYPE_ATTRIBUTES (memfntype)));
17541   fntype = cxx_copy_lang_qualifiers (fntype, memfntype);
17542   return fntype;
17543 }
17544
17545 /* DECL was originally constructed as a non-static member function,
17546    but turned out to be static.  Update it accordingly.  */
17547
17548 void
17549 revert_static_member_fn (tree decl)
17550 {
17551   tree stype = static_fn_type (decl);
17552   cp_cv_quals quals = type_memfn_quals (stype);
17553   cp_ref_qualifier rqual = type_memfn_rqual (stype);
17554
17555   if (quals != TYPE_UNQUALIFIED || rqual != REF_QUAL_NONE)
17556     stype = apply_memfn_quals (stype, TYPE_UNQUALIFIED, REF_QUAL_NONE);
17557
17558   TREE_TYPE (decl) = stype;
17559
17560   if (DECL_ARGUMENTS (decl))
17561     DECL_ARGUMENTS (decl) = DECL_CHAIN (DECL_ARGUMENTS (decl));
17562   DECL_STATIC_FUNCTION_P (decl) = 1;
17563 }
17564
17565 /* Return which tree structure is used by T, or TS_CP_GENERIC if T is
17566    one of the language-independent trees.  */
17567
17568 enum cp_tree_node_structure_enum
17569 cp_tree_node_structure (union lang_tree_node * t)
17570 {
17571   switch (TREE_CODE (&t->generic))
17572     {
17573     case ARGUMENT_PACK_SELECT:  return TS_CP_ARGUMENT_PACK_SELECT;
17574     case BASELINK:              return TS_CP_BASELINK;
17575     case CONSTRAINT_INFO:       return TS_CP_CONSTRAINT_INFO;
17576     case DEFERRED_NOEXCEPT:     return TS_CP_DEFERRED_NOEXCEPT;
17577     case DEFERRED_PARSE:        return TS_CP_DEFERRED_PARSE;
17578     case IDENTIFIER_NODE:       return TS_CP_IDENTIFIER;
17579     case LAMBDA_EXPR:           return TS_CP_LAMBDA_EXPR;
17580     case OVERLOAD:              return TS_CP_OVERLOAD;
17581     case PTRMEM_CST:            return TS_CP_PTRMEM;
17582     case STATIC_ASSERT:         return TS_CP_STATIC_ASSERT;
17583     case TEMPLATE_DECL:         return TS_CP_TEMPLATE_DECL;
17584     case TEMPLATE_INFO:         return TS_CP_TEMPLATE_INFO;
17585     case TEMPLATE_PARM_INDEX:   return TS_CP_TPI;
17586     case TRAIT_EXPR:            return TS_CP_TRAIT_EXPR;
17587     case USERDEF_LITERAL:       return TS_CP_USERDEF_LITERAL;
17588     default:                    return TS_CP_GENERIC;
17589     }
17590 }
17591
17592 /* Build the void_list_node (void_type_node having been created).  */
17593 tree
17594 build_void_list_node (void)
17595 {
17596   tree t = build_tree_list (NULL_TREE, void_type_node);
17597   return t;
17598 }
17599
17600 bool
17601 cp_missing_noreturn_ok_p (tree decl)
17602 {
17603   /* A missing noreturn is ok for the `main' function.  */
17604   return DECL_MAIN_P (decl);
17605 }
17606
17607 /* Return the decl used to identify the COMDAT group into which DECL should
17608    be placed.  */
17609
17610 tree
17611 cxx_comdat_group (tree decl)
17612 {
17613   /* Virtual tables, construction virtual tables, and virtual table
17614      tables all go in a single COMDAT group, named after the primary
17615      virtual table.  */
17616   if (VAR_P (decl) && DECL_VTABLE_OR_VTT_P (decl))
17617     decl = CLASSTYPE_VTABLES (DECL_CONTEXT (decl));
17618   /* For all other DECLs, the COMDAT group is the mangled name of the
17619      declaration itself.  */
17620   else
17621     {
17622       while (DECL_THUNK_P (decl))
17623         {
17624           /* If TARGET_USE_LOCAL_THUNK_ALIAS_P, use_thunk puts the thunk
17625              into the same section as the target function.  In that case
17626              we must return target's name.  */
17627           tree target = THUNK_TARGET (decl);
17628           if (TARGET_USE_LOCAL_THUNK_ALIAS_P (target)
17629               && DECL_SECTION_NAME (target) != NULL
17630               && DECL_ONE_ONLY (target))
17631             decl = target;
17632           else
17633             break;
17634         }
17635     }
17636
17637   return decl;
17638 }
17639
17640 /* Returns the return type for FN as written by the user, which may include
17641    a placeholder for a deduced return type.  */
17642
17643 tree
17644 fndecl_declared_return_type (tree fn)
17645 {
17646   fn = STRIP_TEMPLATE (fn);
17647   if (FNDECL_USED_AUTO (fn))
17648     return DECL_SAVED_AUTO_RETURN_TYPE (fn);
17649
17650   return TREE_TYPE (TREE_TYPE (fn));
17651 }
17652
17653 /* Returns true iff DECL is a variable or function declared with an auto type
17654    that has not yet been deduced to a real type.  */
17655
17656 bool
17657 undeduced_auto_decl (tree decl)
17658 {
17659   if (cxx_dialect < cxx11)
17660     return false;
17661   STRIP_ANY_LOCATION_WRAPPER (decl);
17662   return ((VAR_OR_FUNCTION_DECL_P (decl)
17663            || TREE_CODE (decl) == TEMPLATE_DECL)
17664           && type_uses_auto (TREE_TYPE (decl)));
17665 }
17666
17667 /* Complain if DECL has an undeduced return type.  */
17668
17669 bool
17670 require_deduced_type (tree decl, tsubst_flags_t complain)
17671 {
17672   if (undeduced_auto_decl (decl))
17673     {
17674       if (TREE_NO_WARNING (decl) && seen_error ())
17675         /* We probably already complained about deduction failure.  */;
17676       else if (complain & tf_error)
17677         error ("use of %qD before deduction of %<auto%>", decl);
17678       return false;
17679     }
17680   return true;
17681 }
17682
17683 /* Create a representation of the explicit-specifier with
17684    constant-expression of EXPR.  COMPLAIN is as for tsubst.  */
17685
17686 tree
17687 build_explicit_specifier (tree expr, tsubst_flags_t complain)
17688 {
17689   if (instantiation_dependent_expression_p (expr))
17690     /* Wait for instantiation, tsubst_function_decl will handle it.  */
17691     return expr;
17692
17693   expr = build_converted_constant_bool_expr (expr, complain);
17694   expr = instantiate_non_dependent_expr_sfinae (expr, complain);
17695   expr = cxx_constant_value (expr);
17696   return expr;
17697 }
17698
17699 #include "gt-cp-decl.h"