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_scope, 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 
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 
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 
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
current_tmpl_spec_kind(int n_class_scopes)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
finish_scope(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
check_label_used(tree label)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
sort_labels(const void * a,const void * b)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
pop_labels(tree block)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
pop_local_label(tree id,tree label)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 *
objc_get_current_scope(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
objc_mark_locals_volatile(void * enclosing_blk)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
level_for_constexpr_if(cp_binding_level * b)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
poplevel_named_label_1(named_label_entry ** slot,cp_binding_level * bl)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
poplevel(int keep,int reverse,int functionbody)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       decl = TREE_CODE (link) == TREE_LIST ? TREE_VALUE (link) : link;
696       tree name = OVL_NAME (decl);
697 
698       /* Remove the binding.  */
699       if (TREE_CODE (decl) == LABEL_DECL)
700 	pop_local_label (name, decl);
701       else
702 	pop_local_binding (name, decl);
703     }
704 
705   /* Restore the IDENTIFIER_TYPE_VALUEs.  */
706   for (link = current_binding_level->type_shadowed;
707        link; link = TREE_CHAIN (link))
708     SET_IDENTIFIER_TYPE_VALUE (TREE_PURPOSE (link), TREE_VALUE (link));
709 
710   /* There may be OVERLOADs (wrapped in TREE_LISTs) on the BLOCK_VARs
711      list if a `using' declaration put them there.  The debugging
712      back ends won't understand OVERLOAD, so we remove them here.
713      Because the BLOCK_VARS are (temporarily) shared with
714      CURRENT_BINDING_LEVEL->NAMES we must do this fixup after we have
715      popped all the bindings.  Also remove undeduced 'auto' decls,
716      which LTO doesn't understand, and can't have been used by anything.  */
717   if (block)
718     {
719       tree* d;
720 
721       for (d = &BLOCK_VARS (block); *d; )
722 	{
723 	  if (TREE_CODE (*d) == TREE_LIST
724 	      || (!processing_template_decl
725 		  && undeduced_auto_decl (*d)))
726 	    *d = TREE_CHAIN (*d);
727 	  else
728 	    d = &DECL_CHAIN (*d);
729 	}
730     }
731 
732   /* If the level being exited is the top level of a function,
733      check over all the labels.  */
734   if (functionbody)
735     {
736       if (block)
737 	{
738 	  /* Since this is the top level block of a function, the vars are
739 	     the function's parameters.  Don't leave them in the BLOCK
740 	     because they are found in the FUNCTION_DECL instead.  */
741 	  BLOCK_VARS (block) = 0;
742 	  pop_labels (block);
743 	}
744       else
745 	pop_labels (subblocks);
746     }
747 
748   kind = current_binding_level->kind;
749   if (kind == sk_cleanup)
750     {
751       tree stmt;
752 
753       /* If this is a temporary binding created for a cleanup, then we'll
754 	 have pushed a statement list level.  Pop that, create a new
755 	 BIND_EXPR for the block, and insert it into the stream.  */
756       stmt = pop_stmt_list (current_binding_level->statement_list);
757       stmt = c_build_bind_expr (input_location, block, stmt);
758       add_stmt (stmt);
759     }
760 
761   leave_scope ();
762   if (functionbody)
763     {
764       /* The current function is being defined, so its DECL_INITIAL
765 	 should be error_mark_node.  */
766       gcc_assert (DECL_INITIAL (current_function_decl) == error_mark_node);
767       DECL_INITIAL (current_function_decl) = block ? block : subblocks;
768       if (subblocks)
769 	{
770 	  if (FUNCTION_NEEDS_BODY_BLOCK (current_function_decl))
771 	    {
772 	      if (BLOCK_SUBBLOCKS (subblocks))
773 		BLOCK_OUTER_CURLY_BRACE_P (BLOCK_SUBBLOCKS (subblocks)) = 1;
774 	    }
775 	  else
776 	    BLOCK_OUTER_CURLY_BRACE_P (subblocks) = 1;
777 	}
778     }
779   else if (block)
780     current_binding_level->blocks
781       = block_chainon (current_binding_level->blocks, block);
782 
783   /* If we did not make a block for the level just exited,
784      any blocks made for inner levels
785      (since they cannot be recorded as subblocks in that level)
786      must be carried forward so they will later become subblocks
787      of something else.  */
788   else if (subblocks)
789     current_binding_level->blocks
790       = block_chainon (current_binding_level->blocks, subblocks);
791 
792   /* Each and every BLOCK node created here in `poplevel' is important
793      (e.g. for proper debugging information) so if we created one
794      earlier, mark it as "used".  */
795   if (block)
796     TREE_USED (block) = 1;
797 
798   /* All temporary bindings created for cleanups are popped silently.  */
799   if (kind == sk_cleanup)
800     goto restart;
801 
802   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
803   return block;
804 }
805 
806 /* Call wrapup_globals_declarations for the globals in NAMESPACE.  */
807 /* Diagnose odr-used extern inline variables without definitions
808    in the current TU.  */
809 
810 int
wrapup_namespace_globals()811 wrapup_namespace_globals ()
812 {
813   if (vec<tree, va_gc> *statics = static_decls)
814     {
815       tree decl;
816       unsigned int i;
817       FOR_EACH_VEC_ELT (*statics, i, decl)
818 	{
819 	  if (warn_unused_function
820 	      && TREE_CODE (decl) == FUNCTION_DECL
821 	      && DECL_INITIAL (decl) == 0
822 	      && DECL_EXTERNAL (decl)
823 	      && !TREE_PUBLIC (decl)
824 	      && !DECL_ARTIFICIAL (decl)
825 	      && !DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (decl)
826 	      && !TREE_NO_WARNING (decl))
827 	    warning_at (DECL_SOURCE_LOCATION (decl),
828 			OPT_Wunused_function,
829 			"%qF declared %<static%> but never defined", decl);
830 
831 	  if (VAR_P (decl)
832 	      && DECL_EXTERNAL (decl)
833 	      && DECL_INLINE_VAR_P (decl)
834 	      && DECL_ODR_USED (decl))
835 	    error_at (DECL_SOURCE_LOCATION (decl),
836 		      "odr-used inline variable %qD is not defined", decl);
837 	}
838 
839       /* Clear out the list, so we don't rescan next time.  */
840       static_decls = NULL;
841 
842       /* Write out any globals that need to be output.  */
843       return wrapup_global_declarations (statics->address (),
844 					 statics->length ());
845     }
846   return 0;
847 }
848 
849 /* In C++, you don't have to write `struct S' to refer to `S'; you
850    can just use `S'.  We accomplish this by creating a TYPE_DECL as
851    if the user had written `typedef struct S S'.  Create and return
852    the TYPE_DECL for TYPE.  */
853 
854 tree
create_implicit_typedef(tree name,tree type)855 create_implicit_typedef (tree name, tree type)
856 {
857   tree decl;
858 
859   decl = build_decl (input_location, TYPE_DECL, name, type);
860   DECL_ARTIFICIAL (decl) = 1;
861   /* There are other implicit type declarations, like the one *within*
862      a class that allows you to write `S::S'.  We must distinguish
863      amongst these.  */
864   SET_DECL_IMPLICIT_TYPEDEF_P (decl);
865   TYPE_NAME (type) = decl;
866   TYPE_STUB_DECL (type) = decl;
867 
868   return decl;
869 }
870 
871 /* Function-scope local entities that need discriminators.  Each entry
872    is a {decl,name} pair.  VAR_DECLs for anon unions get their name
873    smashed, so we cannot rely on DECL_NAME.  */
874 
875 static GTY((deletable)) vec<tree, va_gc> *local_entities;
876 
877 /* Determine the mangling discriminator of local DECL.  There are
878    generally very few of these in any particular function.  */
879 
880 void
determine_local_discriminator(tree decl)881 determine_local_discriminator (tree decl)
882 {
883   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
884   retrofit_lang_decl (decl);
885   tree ctx = DECL_CONTEXT (decl);
886   tree name = (TREE_CODE (decl) == TYPE_DECL
887 	       && TYPE_UNNAMED_P (TREE_TYPE (decl))
888 	       ? NULL_TREE : DECL_NAME (decl));
889   size_t nelts = vec_safe_length (local_entities);
890   for (size_t i = 0; i < nelts; i += 2)
891     {
892       tree *pair = &(*local_entities)[i];
893       tree d = pair[0];
894       tree n = pair[1];
895       gcc_checking_assert (d != decl);
896       if (name == n
897 	  && TREE_CODE (decl) == TREE_CODE (d)
898 	  && ctx == DECL_CONTEXT (d))
899 	{
900 	  tree disc = integer_one_node;
901 	  if (DECL_DISCRIMINATOR (d))
902 	    disc = build_int_cst (TREE_TYPE (disc),
903 				  TREE_INT_CST_LOW (DECL_DISCRIMINATOR (d)) + 1);
904 	  DECL_DISCRIMINATOR (decl) = disc;
905 	  /* Replace the saved decl.  */
906 	  pair[0] = decl;
907 	  decl = NULL_TREE;
908 	  break;
909 	}
910     }
911 
912   if (decl)
913     {
914       vec_safe_reserve (local_entities, 2);
915       local_entities->quick_push (decl);
916       local_entities->quick_push (name);
917     }
918 
919   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
920 }
921 
922 
923 
924 /* Returns true if functions FN1 and FN2 have equivalent trailing
925    requires clauses.  */
926 
927 static bool
function_requirements_equivalent_p(tree newfn,tree oldfn)928 function_requirements_equivalent_p (tree newfn, tree oldfn)
929 {
930   /* In the concepts TS, the combined constraints are compared.  */
931   if (cxx_dialect < cxx2a)
932     {
933       tree ci1 = get_constraints (oldfn);
934       tree ci2 = get_constraints (newfn);
935       tree req1 = ci1 ? CI_ASSOCIATED_CONSTRAINTS (ci1) : NULL_TREE;
936       tree req2 = ci2 ? CI_ASSOCIATED_CONSTRAINTS (ci2) : NULL_TREE;
937       return cp_tree_equal (req1, req2);
938     }
939 
940   /* Compare only trailing requirements.  */
941   tree reqs1 = get_trailing_function_requirements (newfn);
942   tree reqs2 = get_trailing_function_requirements (oldfn);
943   if ((reqs1 != NULL_TREE) != (reqs2 != NULL_TREE))
944     return false;
945   reqs1 = maybe_substitute_reqs_for (reqs1, newfn);
946   reqs2 = maybe_substitute_reqs_for (reqs2, oldfn);
947   return cp_tree_equal (reqs1, reqs2);
948 }
949 
950 /* Subroutine of duplicate_decls: return truthvalue of whether
951    or not types of these decls match.
952 
953    For C++, we must compare the parameter list so that `int' can match
954    `int&' in a parameter position, but `int&' is not confused with
955    `const int&'.  */
956 
957 int
decls_match(tree newdecl,tree olddecl,bool record_versions)958 decls_match (tree newdecl, tree olddecl, bool record_versions /* = true */)
959 {
960   int types_match;
961 
962   if (newdecl == olddecl)
963     return 1;
964 
965   if (TREE_CODE (newdecl) != TREE_CODE (olddecl))
966     /* If the two DECLs are not even the same kind of thing, we're not
967        interested in their types.  */
968     return 0;
969 
970   gcc_assert (DECL_P (newdecl));
971 
972   if (TREE_CODE (newdecl) == FUNCTION_DECL)
973     {
974       tree f1 = TREE_TYPE (newdecl);
975       tree f2 = TREE_TYPE (olddecl);
976       tree p1 = TYPE_ARG_TYPES (f1);
977       tree p2 = TYPE_ARG_TYPES (f2);
978       tree r2;
979 
980       /* Specializations of different templates are different functions
981 	 even if they have the same type.  */
982       tree t1 = (DECL_USE_TEMPLATE (newdecl)
983 		 ? DECL_TI_TEMPLATE (newdecl)
984 		 : NULL_TREE);
985       tree t2 = (DECL_USE_TEMPLATE (olddecl)
986 		 ? DECL_TI_TEMPLATE (olddecl)
987 		 : NULL_TREE);
988       if (t1 != t2)
989 	return 0;
990 
991       if (CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl)
992 	  && ! (DECL_EXTERN_C_P (newdecl)
993 		&& DECL_EXTERN_C_P (olddecl)))
994 	return 0;
995 
996       /* A new declaration doesn't match a built-in one unless it
997 	 is also extern "C".  */
998       if (DECL_IS_BUILTIN (olddecl)
999 	  && DECL_EXTERN_C_P (olddecl) && !DECL_EXTERN_C_P (newdecl))
1000 	return 0;
1001 
1002       if (TREE_CODE (f1) != TREE_CODE (f2))
1003 	return 0;
1004 
1005       /* A declaration with deduced return type should use its pre-deduction
1006 	 type for declaration matching.  */
1007       r2 = fndecl_declared_return_type (olddecl);
1008 
1009       if (same_type_p (TREE_TYPE (f1), r2))
1010 	{
1011 	  if (!prototype_p (f2) && DECL_EXTERN_C_P (olddecl)
1012 	      && fndecl_built_in_p (olddecl))
1013 	    {
1014 	      types_match = self_promoting_args_p (p1);
1015 	      if (p1 == void_list_node)
1016 		TREE_TYPE (newdecl) = TREE_TYPE (olddecl);
1017 	    }
1018 	  else
1019 	    types_match =
1020 	      compparms (p1, p2)
1021 	      && type_memfn_rqual (f1) == type_memfn_rqual (f2)
1022 	      && (TYPE_ATTRIBUTES (TREE_TYPE (newdecl)) == NULL_TREE
1023 	          || comp_type_attributes (TREE_TYPE (newdecl),
1024 					   TREE_TYPE (olddecl)) != 0);
1025 	}
1026       else
1027 	types_match = 0;
1028 
1029       /* Two function declarations match if either has a requires-clause
1030          then both have a requires-clause and their constraints-expressions
1031          are equivalent.  */
1032       if (types_match && flag_concepts)
1033 	types_match = function_requirements_equivalent_p (newdecl, olddecl);
1034 
1035       /* The decls dont match if they correspond to two different versions
1036 	 of the same function.   Disallow extern "C" functions to be
1037 	 versions for now.  */
1038       if (types_match
1039 	  && !DECL_EXTERN_C_P (newdecl)
1040 	  && !DECL_EXTERN_C_P (olddecl)
1041 	  && record_versions
1042 	  && maybe_version_functions (newdecl, olddecl,
1043 				      (!DECL_FUNCTION_VERSIONED (newdecl)
1044 				       || !DECL_FUNCTION_VERSIONED (olddecl))))
1045 	return 0;
1046     }
1047   else if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1048     {
1049       if (!template_heads_equivalent_p (newdecl, olddecl))
1050 	return 0;
1051 
1052       tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1053       tree newres = DECL_TEMPLATE_RESULT (newdecl);
1054 
1055       if (TREE_CODE (newres) != TREE_CODE (oldres))
1056 	return 0;
1057 
1058       /* Two template types match if they are the same. Otherwise, compare
1059          the underlying declarations.  */
1060       if (TREE_CODE (newres) == TYPE_DECL)
1061         types_match = same_type_p (TREE_TYPE (newres), TREE_TYPE (oldres));
1062       else
1063 	types_match = decls_match (newres, oldres);
1064     }
1065   else
1066     {
1067       /* Need to check scope for variable declaration (VAR_DECL).
1068 	 For typedef (TYPE_DECL), scope is ignored.  */
1069       if (VAR_P (newdecl)
1070 	  && CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl)
1071 	  /* [dcl.link]
1072 	     Two declarations for an object with C language linkage
1073 	     with the same name (ignoring the namespace that qualify
1074 	     it) that appear in different namespace scopes refer to
1075 	     the same object.  */
1076 	  && !(DECL_EXTERN_C_P (olddecl) && DECL_EXTERN_C_P (newdecl)))
1077 	return 0;
1078 
1079       if (TREE_TYPE (newdecl) == error_mark_node)
1080 	types_match = TREE_TYPE (olddecl) == error_mark_node;
1081       else if (TREE_TYPE (olddecl) == NULL_TREE)
1082 	types_match = TREE_TYPE (newdecl) == NULL_TREE;
1083       else if (TREE_TYPE (newdecl) == NULL_TREE)
1084 	types_match = 0;
1085       else
1086 	types_match = comptypes (TREE_TYPE (newdecl),
1087 				 TREE_TYPE (olddecl),
1088 				 COMPARE_REDECLARATION);
1089     }
1090 
1091   return types_match;
1092 }
1093 
1094 /* NEWDECL and OLDDECL have identical signatures.  If they are
1095    different versions adjust them and return true.
1096    If RECORD is set to true, record function versions.  */
1097 
1098 bool
maybe_version_functions(tree newdecl,tree olddecl,bool record)1099 maybe_version_functions (tree newdecl, tree olddecl, bool record)
1100 {
1101   if (!targetm.target_option.function_versions (newdecl, olddecl))
1102     return false;
1103 
1104   if (!DECL_FUNCTION_VERSIONED (olddecl))
1105     {
1106       DECL_FUNCTION_VERSIONED (olddecl) = 1;
1107       if (DECL_ASSEMBLER_NAME_SET_P (olddecl))
1108 	mangle_decl (olddecl);
1109     }
1110 
1111   if (!DECL_FUNCTION_VERSIONED (newdecl))
1112     {
1113       DECL_FUNCTION_VERSIONED (newdecl) = 1;
1114       if (DECL_ASSEMBLER_NAME_SET_P (newdecl))
1115 	mangle_decl (newdecl);
1116     }
1117 
1118   if (record)
1119     cgraph_node::record_function_versions (olddecl, newdecl);
1120 
1121   return true;
1122 }
1123 
1124 /* If NEWDECL is `static' and an `extern' was seen previously,
1125    warn about it.  OLDDECL is the previous declaration.
1126 
1127    Note that this does not apply to the C++ case of declaring
1128    a variable `extern const' and then later `const'.
1129 
1130    Don't complain about built-in functions, since they are beyond
1131    the user's control.  */
1132 
1133 void
warn_extern_redeclared_static(tree newdecl,tree olddecl)1134 warn_extern_redeclared_static (tree newdecl, tree olddecl)
1135 {
1136   if (TREE_CODE (newdecl) == TYPE_DECL
1137       || TREE_CODE (newdecl) == TEMPLATE_DECL
1138       || TREE_CODE (newdecl) == CONST_DECL
1139       || TREE_CODE (newdecl) == NAMESPACE_DECL)
1140     return;
1141 
1142   /* Don't get confused by static member functions; that's a different
1143      use of `static'.  */
1144   if (TREE_CODE (newdecl) == FUNCTION_DECL
1145       && DECL_STATIC_FUNCTION_P (newdecl))
1146     return;
1147 
1148   /* If the old declaration was `static', or the new one isn't, then
1149      everything is OK.  */
1150   if (DECL_THIS_STATIC (olddecl) || !DECL_THIS_STATIC (newdecl))
1151     return;
1152 
1153   /* It's OK to declare a builtin function as `static'.  */
1154   if (TREE_CODE (olddecl) == FUNCTION_DECL
1155       && DECL_ARTIFICIAL (olddecl))
1156     return;
1157 
1158   auto_diagnostic_group d;
1159   if (permerror (DECL_SOURCE_LOCATION (newdecl),
1160 		 "%qD was declared %<extern%> and later %<static%>", newdecl))
1161     inform (DECL_SOURCE_LOCATION (olddecl),
1162 	    "previous declaration of %qD", olddecl);
1163 }
1164 
1165 /* NEW_DECL is a redeclaration of OLD_DECL; both are functions or
1166    function templates.  If their exception specifications do not
1167    match, issue a diagnostic.  */
1168 
1169 static void
check_redeclaration_exception_specification(tree new_decl,tree old_decl)1170 check_redeclaration_exception_specification (tree new_decl,
1171 					     tree old_decl)
1172 {
1173   tree new_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (new_decl));
1174   tree old_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (old_decl));
1175 
1176   /* Two default specs are equivalent, don't force evaluation.  */
1177   if (UNEVALUATED_NOEXCEPT_SPEC_P (new_exceptions)
1178       && UNEVALUATED_NOEXCEPT_SPEC_P (old_exceptions))
1179     return;
1180 
1181   if (!type_dependent_expression_p (old_decl))
1182     {
1183       maybe_instantiate_noexcept (new_decl);
1184       maybe_instantiate_noexcept (old_decl);
1185     }
1186   new_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (new_decl));
1187   old_exceptions = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (old_decl));
1188 
1189   /* [except.spec]
1190 
1191      If any declaration of a function has an exception-specification,
1192      all declarations, including the definition and an explicit
1193      specialization, of that function shall have an
1194      exception-specification with the same set of type-ids.  */
1195   if (! DECL_IS_BUILTIN (old_decl)
1196       && !comp_except_specs (new_exceptions, old_exceptions, ce_normal))
1197     {
1198       const char *const msg
1199 	= G_("declaration of %qF has a different exception specifier");
1200       bool complained = true;
1201       location_t new_loc = DECL_SOURCE_LOCATION (new_decl);
1202       auto_diagnostic_group d;
1203       if (DECL_IN_SYSTEM_HEADER (old_decl))
1204 	complained = pedwarn (new_loc, OPT_Wsystem_headers, msg, new_decl);
1205       else if (!flag_exceptions)
1206 	/* We used to silently permit mismatched eh specs with
1207 	   -fno-exceptions, so make them a pedwarn now.  */
1208 	complained = pedwarn (new_loc, OPT_Wpedantic, msg, new_decl);
1209       else
1210 	error_at (new_loc, msg, new_decl);
1211       if (complained)
1212 	inform (DECL_SOURCE_LOCATION (old_decl),
1213 		"from previous declaration %qF", old_decl);
1214     }
1215 }
1216 
1217 /* Return true if OLD_DECL and NEW_DECL agree on constexprness.
1218    Otherwise issue diagnostics.  */
1219 
1220 static bool
validate_constexpr_redeclaration(tree old_decl,tree new_decl)1221 validate_constexpr_redeclaration (tree old_decl, tree new_decl)
1222 {
1223   old_decl = STRIP_TEMPLATE (old_decl);
1224   new_decl = STRIP_TEMPLATE (new_decl);
1225   if (!VAR_OR_FUNCTION_DECL_P (old_decl)
1226       || !VAR_OR_FUNCTION_DECL_P (new_decl))
1227     return true;
1228   if (DECL_DECLARED_CONSTEXPR_P (old_decl)
1229       == DECL_DECLARED_CONSTEXPR_P (new_decl))
1230     {
1231       if (TREE_CODE (old_decl) != FUNCTION_DECL)
1232 	return true;
1233       if (DECL_IMMEDIATE_FUNCTION_P (old_decl)
1234 	  == DECL_IMMEDIATE_FUNCTION_P (new_decl))
1235 	return true;
1236     }
1237   if (TREE_CODE (old_decl) == FUNCTION_DECL)
1238     {
1239       if (fndecl_built_in_p (old_decl))
1240 	{
1241 	  /* Hide a built-in declaration.  */
1242 	  DECL_DECLARED_CONSTEXPR_P (old_decl)
1243 	    = DECL_DECLARED_CONSTEXPR_P (new_decl);
1244 	  if (DECL_IMMEDIATE_FUNCTION_P (new_decl))
1245 	    SET_DECL_IMMEDIATE_FUNCTION_P (old_decl);
1246 	  return true;
1247 	}
1248       /* 7.1.5 [dcl.constexpr]
1249 	 Note: An explicit specialization can differ from the template
1250 	 declaration with respect to the constexpr specifier.  */
1251       if (! DECL_TEMPLATE_SPECIALIZATION (old_decl)
1252 	  && DECL_TEMPLATE_SPECIALIZATION (new_decl))
1253 	return true;
1254 
1255       const char *kind = "constexpr";
1256       if (DECL_IMMEDIATE_FUNCTION_P (old_decl)
1257 	  || DECL_IMMEDIATE_FUNCTION_P (new_decl))
1258 	kind = "consteval";
1259       error_at (DECL_SOURCE_LOCATION (new_decl),
1260 		"redeclaration %qD differs in %qs "
1261 		"from previous declaration", new_decl,
1262 		kind);
1263       inform (DECL_SOURCE_LOCATION (old_decl),
1264 	      "previous declaration %qD", old_decl);
1265       return false;
1266     }
1267   return true;
1268 }
1269 
1270 // If OLDDECL and NEWDECL are concept declarations with the same type
1271 // (i.e., and template parameters), but different requirements,
1272 // emit diagnostics and return true. Otherwise, return false.
1273 static inline bool
check_concept_refinement(tree olddecl,tree newdecl)1274 check_concept_refinement (tree olddecl, tree newdecl)
1275 {
1276   if (!DECL_DECLARED_CONCEPT_P (olddecl) || !DECL_DECLARED_CONCEPT_P (newdecl))
1277     return false;
1278 
1279   tree d1 = DECL_TEMPLATE_RESULT (olddecl);
1280   tree d2 = DECL_TEMPLATE_RESULT (newdecl);
1281   if (TREE_CODE (d1) != TREE_CODE (d2))
1282     return false;
1283 
1284   tree t1 = TREE_TYPE (d1);
1285   tree t2 = TREE_TYPE (d2);
1286   if (TREE_CODE (d1) == FUNCTION_DECL)
1287     {
1288       if (compparms (TYPE_ARG_TYPES (t1), TYPE_ARG_TYPES (t2))
1289           && comp_template_parms (DECL_TEMPLATE_PARMS (olddecl),
1290                                   DECL_TEMPLATE_PARMS (newdecl))
1291           && !equivalently_constrained (olddecl, newdecl))
1292         {
1293           error ("cannot specialize concept %q#D", olddecl);
1294           return true;
1295         }
1296     }
1297   return false;
1298 }
1299 
1300 /* DECL is a redeclaration of a function or function template.  If
1301    it does have default arguments issue a diagnostic.  Note: this
1302    function is used to enforce the requirements in C++11 8.3.6 about
1303    no default arguments in redeclarations.  */
1304 
1305 static void
check_redeclaration_no_default_args(tree decl)1306 check_redeclaration_no_default_args (tree decl)
1307 {
1308   gcc_assert (DECL_DECLARES_FUNCTION_P (decl));
1309 
1310   for (tree t = FUNCTION_FIRST_USER_PARMTYPE (decl);
1311        t && t != void_list_node; t = TREE_CHAIN (t))
1312     if (TREE_PURPOSE (t))
1313       {
1314 	permerror (DECL_SOURCE_LOCATION (decl),
1315 		   "redeclaration of %q#D may not have default "
1316 		   "arguments", decl);
1317 	return;
1318       }
1319 }
1320 
1321 /* NEWDECL is a redeclaration of a function or function template OLDDECL,
1322    in any case represented as FUNCTION_DECLs (the DECL_TEMPLATE_RESULTs of
1323    the TEMPLATE_DECLs in case of function templates).  This function is used
1324    to enforce the final part of C++17 11.3.6/4, about a single declaration:
1325    "If a friend declaration specifies a default argument expression, that
1326    declaration shall be a definition and shall be the only declaration of
1327    the function or function template in the translation unit."  */
1328 
1329 static void
check_no_redeclaration_friend_default_args(tree olddecl,tree newdecl,bool olddecl_hidden_friend_p)1330 check_no_redeclaration_friend_default_args (tree olddecl, tree newdecl,
1331 					    bool olddecl_hidden_friend_p)
1332 {
1333   if (!olddecl_hidden_friend_p && !DECL_FRIEND_P (newdecl))
1334     return;
1335 
1336   tree t1 = FUNCTION_FIRST_USER_PARMTYPE (olddecl);
1337   tree t2 = FUNCTION_FIRST_USER_PARMTYPE (newdecl);
1338 
1339   for (; t1 && t1 != void_list_node;
1340        t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2))
1341     if ((olddecl_hidden_friend_p && TREE_PURPOSE (t1))
1342 	|| (DECL_FRIEND_P (newdecl) && TREE_PURPOSE (t2)))
1343       {
1344 	auto_diagnostic_group d;
1345 	if (permerror (DECL_SOURCE_LOCATION (newdecl),
1346 		       "friend declaration of %q#D specifies default "
1347 		       "arguments and isn%'t the only declaration", newdecl))
1348 	  inform (DECL_SOURCE_LOCATION (olddecl),
1349 		  "previous declaration of %q#D", olddecl);
1350 	return;
1351       }
1352 }
1353 
1354 /* Merge tree bits that correspond to attributes noreturn, nothrow,
1355    const,  malloc, and pure from NEWDECL with those of OLDDECL.  */
1356 
1357 static void
merge_attribute_bits(tree newdecl,tree olddecl)1358 merge_attribute_bits (tree newdecl, tree olddecl)
1359 {
1360   TREE_THIS_VOLATILE (newdecl) |= TREE_THIS_VOLATILE (olddecl);
1361   TREE_THIS_VOLATILE (olddecl) |= TREE_THIS_VOLATILE (newdecl);
1362   TREE_NOTHROW (newdecl) |= TREE_NOTHROW (olddecl);
1363   TREE_NOTHROW (olddecl) |= TREE_NOTHROW (newdecl);
1364   TREE_READONLY (newdecl) |= TREE_READONLY (olddecl);
1365   TREE_READONLY (olddecl) |= TREE_READONLY (newdecl);
1366   DECL_IS_MALLOC (newdecl) |= DECL_IS_MALLOC (olddecl);
1367   DECL_IS_MALLOC (olddecl) |= DECL_IS_MALLOC (newdecl);
1368   DECL_PURE_P (newdecl) |= DECL_PURE_P (olddecl);
1369   DECL_PURE_P (olddecl) |= DECL_PURE_P (newdecl);
1370   DECL_UNINLINABLE (newdecl) |= DECL_UNINLINABLE (olddecl);
1371   DECL_UNINLINABLE (olddecl) |= DECL_UNINLINABLE (newdecl);
1372 }
1373 
1374 #define GNU_INLINE_P(fn) (DECL_DECLARED_INLINE_P (fn)			\
1375 			  && lookup_attribute ("gnu_inline",		\
1376 					       DECL_ATTRIBUTES (fn)))
1377 
1378 /* A subroutine of duplicate_decls. Emits a diagnostic when newdecl
1379    ambiguates olddecl.  Returns true if an error occurs.  */
1380 
1381 static bool
duplicate_function_template_decls(tree newdecl,tree olddecl)1382 duplicate_function_template_decls (tree newdecl, tree olddecl)
1383 {
1384 
1385   tree newres = DECL_TEMPLATE_RESULT (newdecl);
1386   tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1387   /* Function template declarations can be differentiated by parameter
1388      and return type.  */
1389   if (compparms (TYPE_ARG_TYPES (TREE_TYPE (oldres)),
1390 		 TYPE_ARG_TYPES (TREE_TYPE (newres)))
1391        && same_type_p (TREE_TYPE (TREE_TYPE (newdecl)),
1392 		       TREE_TYPE (TREE_TYPE (olddecl))))
1393     {
1394       /* ... and also by their template-heads and requires-clauses.  */
1395       if (template_heads_equivalent_p (newdecl, olddecl)
1396 	  && function_requirements_equivalent_p (newres, oldres))
1397 	{
1398 	  error ("ambiguating new declaration %q+#D", newdecl);
1399 	  inform (DECL_SOURCE_LOCATION (olddecl),
1400 		  "old declaration %q#D", olddecl);
1401 	  return true;
1402 	}
1403 
1404       /* FIXME: The types are the same but the are differences
1405 	 in either the template heads or function requirements.
1406 	 We should be able to diagnose a set of common errors
1407 	 stemming from these declarations. For example:
1408 
1409 	   template<typename T> requires C void f(...);
1410 	   template<typename T> void f(...) requires C;
1411 
1412 	 These are functionally equivalent but not equivalent.  */
1413     }
1414 
1415   return false;
1416 }
1417 
1418 /* If NEWDECL is a redeclaration of OLDDECL, merge the declarations.
1419    If the redeclaration is invalid, a diagnostic is issued, and the
1420    error_mark_node is returned.  Otherwise, OLDDECL is returned.
1421 
1422    If NEWDECL is not a redeclaration of OLDDECL, NULL_TREE is
1423    returned.
1424 
1425    NEWDECL_IS_FRIEND is true if NEWDECL was declared as a friend.  */
1426 
1427 tree
duplicate_decls(tree newdecl,tree olddecl,bool newdecl_is_friend)1428 duplicate_decls (tree newdecl, tree olddecl, bool newdecl_is_friend)
1429 {
1430   unsigned olddecl_uid = DECL_UID (olddecl);
1431   int olddecl_friend = 0, types_match = 0, hidden_friend = 0;
1432   int olddecl_hidden_friend = 0;
1433   int new_defines_function = 0;
1434   tree new_template_info;
1435   location_t olddecl_loc = DECL_SOURCE_LOCATION (olddecl);
1436   location_t newdecl_loc = DECL_SOURCE_LOCATION (newdecl);
1437 
1438   if (newdecl == olddecl)
1439     return olddecl;
1440 
1441   types_match = decls_match (newdecl, olddecl);
1442 
1443   /* If either the type of the new decl or the type of the old decl is an
1444      error_mark_node, then that implies that we have already issued an
1445      error (earlier) for some bogus type specification, and in that case,
1446      it is rather pointless to harass the user with yet more error message
1447      about the same declaration, so just pretend the types match here.  */
1448   if (TREE_TYPE (newdecl) == error_mark_node
1449       || TREE_TYPE (olddecl) == error_mark_node)
1450     return error_mark_node;
1451 
1452   /* Check for redeclaration and other discrepancies.  */
1453   if (TREE_CODE (olddecl) == FUNCTION_DECL
1454       && DECL_ARTIFICIAL (olddecl)
1455       /* A C++20 implicit friend operator== uses the normal path (94462).  */
1456       && !DECL_HIDDEN_FRIEND_P (olddecl))
1457     {
1458       if (TREE_CODE (newdecl) != FUNCTION_DECL)
1459 	{
1460 	  /* Avoid warnings redeclaring built-ins which have not been
1461 	     explicitly declared.  */
1462 	  if (DECL_ANTICIPATED (olddecl))
1463 	    {
1464 	      if (TREE_PUBLIC (newdecl)
1465 		  && CP_DECL_CONTEXT (newdecl) == global_namespace)
1466 		warning_at (newdecl_loc,
1467 			    OPT_Wbuiltin_declaration_mismatch,
1468 			    "built-in function %qD declared as non-function",
1469 			    newdecl);
1470 	      return NULL_TREE;
1471 	    }
1472 
1473 	  /* If you declare a built-in or predefined function name as static,
1474 	     the old definition is overridden, but optionally warn this was a
1475 	     bad choice of name.  */
1476 	  if (! TREE_PUBLIC (newdecl))
1477 	    {
1478 	      warning_at (newdecl_loc,
1479 			  OPT_Wshadow,
1480 			  fndecl_built_in_p (olddecl)
1481 			  ? G_("shadowing built-in function %q#D")
1482 			  : G_("shadowing library function %q#D"), olddecl);
1483 	      /* Discard the old built-in function.  */
1484 	      return NULL_TREE;
1485 	    }
1486 	  /* If the built-in is not ansi, then programs can override
1487 	     it even globally without an error.  */
1488 	  else if (! fndecl_built_in_p (olddecl))
1489 	    warning_at (newdecl_loc, 0,
1490 			"library function %q#D redeclared as non-function %q#D",
1491 			olddecl, newdecl);
1492 	  else
1493 	    error_at (newdecl_loc,
1494 		      "declaration of %q#D conflicts with built-in "
1495 		      "declaration %q#D", newdecl, olddecl);
1496 	  return NULL_TREE;
1497 	}
1498       else if (DECL_OMP_DECLARE_REDUCTION_P (olddecl))
1499 	{
1500 	  gcc_assert (DECL_OMP_DECLARE_REDUCTION_P (newdecl));
1501 	  error_at (newdecl_loc,
1502 		    "redeclaration of %<pragma omp declare reduction%>");
1503 	  inform (olddecl_loc,
1504 		  "previous %<pragma omp declare reduction%> declaration");
1505 	  return error_mark_node;
1506 	}
1507       else if (!types_match)
1508 	{
1509 	  /* Avoid warnings redeclaring built-ins which have not been
1510 	     explicitly declared.  */
1511 	  if (DECL_ANTICIPATED (olddecl))
1512 	    {
1513 	      tree t1, t2;
1514 
1515 	      /* A new declaration doesn't match a built-in one unless it
1516 		 is also extern "C".  */
1517 	      gcc_assert (DECL_IS_BUILTIN (olddecl));
1518 	      gcc_assert (DECL_EXTERN_C_P (olddecl));
1519 	      if (!DECL_EXTERN_C_P (newdecl))
1520 		return NULL_TREE;
1521 
1522 	      for (t1 = TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1523 		   t2 = TYPE_ARG_TYPES (TREE_TYPE (olddecl));
1524 		   t1 || t2;
1525 		   t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2))
1526 		{
1527 		  if (!t1 || !t2)
1528 		    break;
1529 		  /* FILE, tm types are not known at the time
1530 		     we create the builtins.  */
1531 		  for (unsigned i = 0;
1532 		       i < sizeof (builtin_structptr_types)
1533 			   / sizeof (builtin_structptr_type);
1534 		       ++i)
1535 		    if (TREE_VALUE (t2) == builtin_structptr_types[i].node)
1536 		      {
1537 			tree t = TREE_VALUE (t1);
1538 
1539 			if (TYPE_PTR_P (t)
1540 			    && TYPE_IDENTIFIER (TREE_TYPE (t))
1541 			    == get_identifier (builtin_structptr_types[i].str)
1542 			    && compparms (TREE_CHAIN (t1), TREE_CHAIN (t2)))
1543 			  {
1544 			    tree oldargs = TYPE_ARG_TYPES (TREE_TYPE (olddecl));
1545 
1546 			    TYPE_ARG_TYPES (TREE_TYPE (olddecl))
1547 			      = TYPE_ARG_TYPES (TREE_TYPE (newdecl));
1548 			    types_match = decls_match (newdecl, olddecl);
1549 			    if (types_match)
1550 			      return duplicate_decls (newdecl, olddecl,
1551 						      newdecl_is_friend);
1552 			    TYPE_ARG_TYPES (TREE_TYPE (olddecl)) = oldargs;
1553 			  }
1554 			goto next_arg;
1555 		      }
1556 
1557 		  if (! same_type_p (TREE_VALUE (t1), TREE_VALUE (t2)))
1558 		    break;
1559 		next_arg:;
1560 		}
1561 
1562 	      warning_at (newdecl_loc,
1563 			  OPT_Wbuiltin_declaration_mismatch,
1564 			  "declaration of %q#D conflicts with built-in "
1565 			  "declaration %q#D", newdecl, olddecl);
1566 	    }
1567 	  else if ((DECL_EXTERN_C_P (newdecl)
1568 		    && DECL_EXTERN_C_P (olddecl))
1569 		   || compparms (TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1570 				 TYPE_ARG_TYPES (TREE_TYPE (olddecl))))
1571 	    {
1572 	      /* Don't really override olddecl for __* prefixed builtins
1573 		 except for __[^b]*_chk, the compiler might be using those
1574 		 explicitly.  */
1575 	      if (fndecl_built_in_p (olddecl))
1576 		{
1577 		  tree id = DECL_NAME (olddecl);
1578 		  const char *name = IDENTIFIER_POINTER (id);
1579 		  size_t len;
1580 
1581 		  if (name[0] == '_'
1582 		      && name[1] == '_'
1583 		      && (strncmp (name + 2, "builtin_",
1584 				   strlen ("builtin_")) == 0
1585 			  || (len = strlen (name)) <= strlen ("___chk")
1586 			  || memcmp (name + len - strlen ("_chk"),
1587 				     "_chk", strlen ("_chk") + 1) != 0))
1588 		    {
1589 		      if (DECL_INITIAL (newdecl))
1590 			{
1591 			  error_at (newdecl_loc,
1592 				    "definition of %q#D ambiguates built-in "
1593 				    "declaration %q#D", newdecl, olddecl);
1594 			  return error_mark_node;
1595 			}
1596 		      auto_diagnostic_group d;
1597 		      if (permerror (newdecl_loc,
1598 				     "new declaration %q#D ambiguates built-in"
1599 				     " declaration %q#D", newdecl, olddecl)
1600 			  && flag_permissive)
1601 			inform (newdecl_loc,
1602 				"ignoring the %q#D declaration", newdecl);
1603 		      return flag_permissive ? olddecl : error_mark_node;
1604 		    }
1605 		}
1606 
1607 	      /* A near match; override the builtin.  */
1608 
1609 	      if (TREE_PUBLIC (newdecl))
1610 		warning_at (newdecl_loc,
1611 			    OPT_Wbuiltin_declaration_mismatch,
1612 			    "new declaration %q#D ambiguates built-in "
1613 			    "declaration %q#D", newdecl, olddecl);
1614 	      else
1615 		warning (OPT_Wshadow,
1616 			 fndecl_built_in_p (olddecl)
1617 			 ? G_("shadowing built-in function %q#D")
1618 			 : G_("shadowing library function %q#D"), olddecl);
1619 	    }
1620 	  else
1621 	    /* Discard the old built-in function.  */
1622 	    return NULL_TREE;
1623 
1624 	  /* Replace the old RTL to avoid problems with inlining.  */
1625 	  COPY_DECL_RTL (newdecl, olddecl);
1626 	}
1627       /* Even if the types match, prefer the new declarations type for
1628 	 built-ins which have not been explicitly declared, for
1629 	 exception lists, etc...  */
1630       else if (DECL_IS_BUILTIN (olddecl))
1631 	{
1632 	  tree type = TREE_TYPE (newdecl);
1633 	  tree attribs = (*targetm.merge_type_attributes)
1634 	    (TREE_TYPE (olddecl), type);
1635 
1636 	  type = cp_build_type_attribute_variant (type, attribs);
1637 	  TREE_TYPE (newdecl) = TREE_TYPE (olddecl) = type;
1638 	}
1639 
1640       /* If a function is explicitly declared "throw ()", propagate that to
1641 	 the corresponding builtin.  */
1642       if (DECL_BUILT_IN_CLASS (olddecl) == BUILT_IN_NORMAL
1643 	  && DECL_ANTICIPATED (olddecl)
1644 	  && TREE_NOTHROW (newdecl)
1645 	  && !TREE_NOTHROW (olddecl))
1646 	{
1647 	  enum built_in_function fncode = DECL_FUNCTION_CODE (olddecl);
1648 	  tree tmpdecl = builtin_decl_explicit (fncode);
1649 	  if (tmpdecl && tmpdecl != olddecl && types_match)
1650 	    TREE_NOTHROW (tmpdecl)  = 1;
1651 	}
1652 
1653       /* Whether or not the builtin can throw exceptions has no
1654 	 bearing on this declarator.  */
1655       TREE_NOTHROW (olddecl) = 0;
1656 
1657       if (DECL_THIS_STATIC (newdecl) && !DECL_THIS_STATIC (olddecl))
1658 	{
1659 	  /* If a builtin function is redeclared as `static', merge
1660 	     the declarations, but make the original one static.  */
1661 	  DECL_THIS_STATIC (olddecl) = 1;
1662 	  TREE_PUBLIC (olddecl) = 0;
1663 
1664 	  /* Make the old declaration consistent with the new one so
1665 	     that all remnants of the builtin-ness of this function
1666 	     will be banished.  */
1667 	  SET_DECL_LANGUAGE (olddecl, DECL_LANGUAGE (newdecl));
1668 	  COPY_DECL_RTL (newdecl, olddecl);
1669 	}
1670     }
1671   else if (TREE_CODE (olddecl) != TREE_CODE (newdecl))
1672     {
1673       /* C++ Standard, 3.3, clause 4:
1674 	 "[Note: a namespace name or a class template name must be unique
1675 	 in its declarative region (7.3.2, clause 14). ]"  */
1676       if (TREE_CODE (olddecl) == NAMESPACE_DECL
1677 	  || TREE_CODE (newdecl) == NAMESPACE_DECL)
1678 	/* Namespace conflicts with not namespace.  */;
1679       else if (DECL_TYPE_TEMPLATE_P (olddecl)
1680 	       || DECL_TYPE_TEMPLATE_P (newdecl))
1681 	/* Class template conflicts.  */;
1682       else if ((TREE_CODE (newdecl) == FUNCTION_DECL
1683 		&& DECL_FUNCTION_TEMPLATE_P (olddecl))
1684 	       || (TREE_CODE (olddecl) == FUNCTION_DECL
1685 		   && DECL_FUNCTION_TEMPLATE_P (newdecl)))
1686 	{
1687 	  /* One is a function and the other is a template
1688 	     function.  */
1689 	  if (!UDLIT_OPER_P (DECL_NAME (newdecl)))
1690 	    return NULL_TREE;
1691 
1692 	  /* There can only be one!  */
1693 	  if (TREE_CODE (newdecl) == TEMPLATE_DECL
1694 	      && check_raw_literal_operator (olddecl))
1695 	    error_at (newdecl_loc,
1696 		      "literal operator %q#D conflicts with"
1697 		      " raw literal operator", newdecl);
1698 	  else if (check_raw_literal_operator (newdecl))
1699 	    error_at (newdecl_loc,
1700 		      "raw literal operator %q#D conflicts with"
1701 		      " literal operator template", newdecl);
1702 	  else
1703 	    return NULL_TREE;
1704 
1705 	  inform (olddecl_loc, "previous declaration %q#D", olddecl);
1706 	  return error_mark_node;
1707 	}
1708       else if (DECL_IMPLICIT_TYPEDEF_P (olddecl)
1709 	       || DECL_IMPLICIT_TYPEDEF_P (newdecl))
1710 	/* One is an implicit typedef, that's ok.  */
1711 	return NULL_TREE;
1712 
1713       error ("%q#D redeclared as different kind of entity", newdecl);
1714       inform (olddecl_loc, "previous declaration %q#D", olddecl);
1715 
1716       return error_mark_node;
1717     }
1718   else if (!types_match)
1719     {
1720       if (CP_DECL_CONTEXT (newdecl) != CP_DECL_CONTEXT (olddecl))
1721 	/* These are certainly not duplicate declarations; they're
1722 	   from different scopes.  */
1723 	return NULL_TREE;
1724 
1725       if (TREE_CODE (newdecl) == TEMPLATE_DECL)
1726 	{
1727 	  tree oldres = DECL_TEMPLATE_RESULT (olddecl);
1728 	  tree newres = DECL_TEMPLATE_RESULT (newdecl);
1729 
1730 	  /* The name of a class template may not be declared to refer to
1731 	     any other template, class, function, object, namespace, value,
1732 	     or type in the same scope.  */
1733 	  if (TREE_CODE (oldres) == TYPE_DECL
1734 	      || TREE_CODE (newres) == TYPE_DECL)
1735 	    {
1736 	      error_at (newdecl_loc,
1737 			"conflicting declaration of template %q#D", newdecl);
1738 	      inform (olddecl_loc,
1739 		      "previous declaration %q#D", olddecl);
1740 	      return error_mark_node;
1741 	    }
1742 
1743 	  else if (TREE_CODE (oldres) == FUNCTION_DECL
1744 		   && TREE_CODE (newres) == FUNCTION_DECL)
1745 	    {
1746 	      if (duplicate_function_template_decls (newdecl, olddecl))
1747 		return error_mark_node;
1748 	      return NULL_TREE;
1749 	    }
1750           else if (check_concept_refinement (olddecl, newdecl))
1751 	    return error_mark_node;
1752 	  return NULL_TREE;
1753 	}
1754       if (TREE_CODE (newdecl) == FUNCTION_DECL)
1755 	{
1756 	  if (DECL_EXTERN_C_P (newdecl) && DECL_EXTERN_C_P (olddecl))
1757 	    {
1758 	      error_at (newdecl_loc,
1759 			"conflicting declaration of C function %q#D",
1760 			newdecl);
1761 	      inform (olddecl_loc,
1762 		      "previous declaration %q#D", olddecl);
1763 	      return NULL_TREE;
1764 	    }
1765 	  /* For function versions, params and types match, but they
1766 	     are not ambiguous.  */
1767 	  else if ((!DECL_FUNCTION_VERSIONED (newdecl)
1768 		    && !DECL_FUNCTION_VERSIONED (olddecl))
1769                    // The functions have the same parameter types.
1770 		   && compparms (TYPE_ARG_TYPES (TREE_TYPE (newdecl)),
1771 				 TYPE_ARG_TYPES (TREE_TYPE (olddecl)))
1772                    // And the same constraints.
1773                    && equivalently_constrained (newdecl, olddecl))
1774 	    {
1775 	      error_at (newdecl_loc,
1776 			"ambiguating new declaration of %q#D", newdecl);
1777 	      inform (olddecl_loc,
1778 		      "old declaration %q#D", olddecl);
1779               return error_mark_node;
1780 	    }
1781 	  else
1782 	    return NULL_TREE;
1783 	}
1784       else
1785 	{
1786 	  error_at (newdecl_loc, "conflicting declaration %q#D", newdecl);
1787 	  inform (olddecl_loc,
1788 		  "previous declaration as %q#D", olddecl);
1789 	  return error_mark_node;
1790 	}
1791     }
1792   else if (TREE_CODE (newdecl) == FUNCTION_DECL
1793 	    && ((DECL_TEMPLATE_SPECIALIZATION (olddecl)
1794 		 && (!DECL_TEMPLATE_INFO (newdecl)
1795 		     || (DECL_TI_TEMPLATE (newdecl)
1796 			 != DECL_TI_TEMPLATE (olddecl))))
1797 		|| (DECL_TEMPLATE_SPECIALIZATION (newdecl)
1798 		    && (!DECL_TEMPLATE_INFO (olddecl)
1799 			|| (DECL_TI_TEMPLATE (olddecl)
1800 			    != DECL_TI_TEMPLATE (newdecl))))))
1801     /* It's OK to have a template specialization and a non-template
1802        with the same type, or to have specializations of two
1803        different templates with the same type.  Note that if one is a
1804        specialization, and the other is an instantiation of the same
1805        template, that we do not exit at this point.  That situation
1806        can occur if we instantiate a template class, and then
1807        specialize one of its methods.  This situation is valid, but
1808        the declarations must be merged in the usual way.  */
1809     return NULL_TREE;
1810   else if (TREE_CODE (newdecl) == FUNCTION_DECL
1811 	   && ((DECL_TEMPLATE_INSTANTIATION (olddecl)
1812 		&& !DECL_USE_TEMPLATE (newdecl))
1813 	       || (DECL_TEMPLATE_INSTANTIATION (newdecl)
1814 		   && !DECL_USE_TEMPLATE (olddecl))))
1815     /* One of the declarations is a template instantiation, and the
1816        other is not a template at all.  That's OK.  */
1817     return NULL_TREE;
1818   else if (TREE_CODE (newdecl) == NAMESPACE_DECL)
1819     {
1820       /* In [namespace.alias] we have:
1821 
1822 	   In a declarative region, a namespace-alias-definition can be
1823 	   used to redefine a namespace-alias declared in that declarative
1824 	   region to refer only to the namespace to which it already
1825 	   refers.
1826 
1827 	 Therefore, if we encounter a second alias directive for the same
1828 	 alias, we can just ignore the second directive.  */
1829       if (DECL_NAMESPACE_ALIAS (newdecl)
1830 	  && (DECL_NAMESPACE_ALIAS (newdecl)
1831 	      == DECL_NAMESPACE_ALIAS (olddecl)))
1832 	return olddecl;
1833 
1834       /* Leave it to update_binding to merge or report error.  */
1835       return NULL_TREE;
1836     }
1837   else
1838     {
1839       const char *errmsg = redeclaration_error_message (newdecl, olddecl);
1840       if (errmsg)
1841 	{
1842 	  auto_diagnostic_group d;
1843 	  error_at (newdecl_loc, errmsg, newdecl);
1844 	  if (DECL_NAME (olddecl) != NULL_TREE)
1845 	    inform (olddecl_loc,
1846 		    (DECL_INITIAL (olddecl) && namespace_bindings_p ())
1847 		    ? G_("%q#D previously defined here")
1848 		    : G_("%q#D previously declared here"), olddecl);
1849 	  return error_mark_node;
1850 	}
1851       else if (TREE_CODE (olddecl) == FUNCTION_DECL
1852 	       && DECL_INITIAL (olddecl) != NULL_TREE
1853 	       && !prototype_p (TREE_TYPE (olddecl))
1854 	       && prototype_p (TREE_TYPE (newdecl)))
1855 	{
1856 	  /* Prototype decl follows defn w/o prototype.  */
1857 	  auto_diagnostic_group d;
1858 	  if (warning_at (newdecl_loc, 0,
1859 			  "prototype specified for %q#D", newdecl))
1860 	    inform (olddecl_loc,
1861 		    "previous non-prototype definition here");
1862 	}
1863       else if (VAR_OR_FUNCTION_DECL_P (olddecl)
1864 	       && DECL_LANGUAGE (newdecl) != DECL_LANGUAGE (olddecl))
1865 	{
1866 	  /* [dcl.link]
1867 	     If two declarations of the same function or object
1868 	     specify different linkage-specifications ..., the program
1869 	     is ill-formed.... Except for functions with C++ linkage,
1870 	     a function declaration without a linkage specification
1871 	     shall not precede the first linkage specification for
1872 	     that function.  A function can be declared without a
1873 	     linkage specification after an explicit linkage
1874 	     specification has been seen; the linkage explicitly
1875 	     specified in the earlier declaration is not affected by
1876 	     such a function declaration.
1877 
1878 	     DR 563 raises the question why the restrictions on
1879 	     functions should not also apply to objects.  Older
1880 	     versions of G++ silently ignore the linkage-specification
1881 	     for this example:
1882 
1883 	       namespace N {
1884                  extern int i;
1885    	         extern "C" int i;
1886                }
1887 
1888              which is clearly wrong.  Therefore, we now treat objects
1889 	     like functions.  */
1890 	  if (current_lang_depth () == 0)
1891 	    {
1892 	      /* There is no explicit linkage-specification, so we use
1893 		 the linkage from the previous declaration.  */
1894 	      retrofit_lang_decl (newdecl);
1895 	      SET_DECL_LANGUAGE (newdecl, DECL_LANGUAGE (olddecl));
1896 	    }
1897 	  else
1898 	    {
1899 	      auto_diagnostic_group d;
1900 	      error_at (newdecl_loc,
1901 			"conflicting declaration of %q#D with %qL linkage",
1902 			newdecl, DECL_LANGUAGE (newdecl));
1903 	      inform (olddecl_loc,
1904 		      "previous declaration with %qL linkage",
1905 		      DECL_LANGUAGE (olddecl));
1906 	    }
1907 	}
1908 
1909       if (DECL_LANG_SPECIFIC (olddecl) && DECL_USE_TEMPLATE (olddecl))
1910 	;
1911       else if (TREE_CODE (olddecl) == FUNCTION_DECL)
1912 	{
1913 	  /* Note: free functions, as TEMPLATE_DECLs, are handled below.  */
1914 	  if (DECL_FUNCTION_MEMBER_P (olddecl)
1915 	      && (/* grokfndecl passes member function templates too
1916 		     as FUNCTION_DECLs.  */
1917 		  DECL_TEMPLATE_INFO (olddecl)
1918 		  /* C++11 8.3.6/6.
1919 		     Default arguments for a member function of a class
1920 		     template shall be specified on the initial declaration
1921 		     of the member function within the class template.  */
1922 		  || CLASSTYPE_TEMPLATE_INFO (CP_DECL_CONTEXT (olddecl))))
1923 	    check_redeclaration_no_default_args (newdecl);
1924 	  else
1925 	    {
1926 	      tree t1 = FUNCTION_FIRST_USER_PARMTYPE (olddecl);
1927 	      tree t2 = FUNCTION_FIRST_USER_PARMTYPE (newdecl);
1928 	      int i = 1;
1929 
1930 	      for (; t1 && t1 != void_list_node;
1931 		   t1 = TREE_CHAIN (t1), t2 = TREE_CHAIN (t2), i++)
1932 		if (TREE_PURPOSE (t1) && TREE_PURPOSE (t2))
1933 		  {
1934 		    if (simple_cst_equal (TREE_PURPOSE (t1),
1935 					  TREE_PURPOSE (t2)) == 1)
1936 		      {
1937 			auto_diagnostic_group d;
1938 			if (permerror (newdecl_loc,
1939 				       "default argument given for parameter "
1940 				       "%d of %q#D", i, newdecl))
1941 			  inform (olddecl_loc,
1942 				  "previous specification in %q#D here",
1943 				  olddecl);
1944 		      }
1945 		    else
1946 		      {
1947 			auto_diagnostic_group d;
1948 			error_at (newdecl_loc,
1949 				  "default argument given for parameter %d "
1950 				  "of %q#D", i, newdecl);
1951 			inform (olddecl_loc,
1952 				"previous specification in %q#D here",
1953 				olddecl);
1954 		      }
1955 		  }
1956 
1957 	      /* C++17 11.3.6/4: "If a friend declaration specifies a default
1958 		 argument expression, that declaration... shall be the only
1959 		 declaration of the function or function template in the
1960 		 translation unit."  */
1961 	      check_no_redeclaration_friend_default_args
1962 		(olddecl, newdecl, DECL_HIDDEN_FRIEND_P (olddecl));
1963 	    }
1964 	}
1965     }
1966 
1967   /* Do not merge an implicit typedef with an explicit one.  In:
1968 
1969        class A;
1970        ...
1971        typedef class A A __attribute__ ((foo));
1972 
1973      the attribute should apply only to the typedef.  */
1974   if (TREE_CODE (olddecl) == TYPE_DECL
1975       && (DECL_IMPLICIT_TYPEDEF_P (olddecl)
1976 	  || DECL_IMPLICIT_TYPEDEF_P (newdecl)))
1977     return NULL_TREE;
1978 
1979   if (!validate_constexpr_redeclaration (olddecl, newdecl))
1980     return error_mark_node;
1981 
1982   /* We have committed to returning OLDDECL at this point.  */
1983 
1984   /* If new decl is `static' and an `extern' was seen previously,
1985      warn about it.  */
1986   warn_extern_redeclared_static (newdecl, olddecl);
1987 
1988   /* True to merge attributes between the declarations, false to
1989      set OLDDECL's attributes to those of NEWDECL (for template
1990      explicit specializations that specify their own attributes
1991      independent of those specified for the primary template).  */
1992   const bool merge_attr = (TREE_CODE (newdecl) != FUNCTION_DECL
1993 			   || !DECL_TEMPLATE_SPECIALIZATION (newdecl)
1994 			   || DECL_TEMPLATE_SPECIALIZATION (olddecl));
1995 
1996   if (TREE_CODE (newdecl) == FUNCTION_DECL)
1997     {
1998       if (merge_attr)
1999 	{
2000 	  if (diagnose_mismatched_attributes (olddecl, newdecl))
2001 	    inform (olddecl_loc, DECL_INITIAL (olddecl)
2002 		    ? G_("previous definition of %qD here")
2003 		    : G_("previous declaration of %qD here"), olddecl);
2004 
2005 	  /* [dcl.attr.noreturn]: The first declaration of a function shall
2006 	     specify the noreturn attribute if any declaration of that function
2007 	     specifies the noreturn attribute.  */
2008 	  tree a;
2009 	  if (TREE_THIS_VOLATILE (newdecl)
2010 	      && !TREE_THIS_VOLATILE (olddecl)
2011 	      /* This applies to [[noreturn]] only, not its GNU variants.  */
2012 	      && (a = lookup_attribute ("noreturn", DECL_ATTRIBUTES (newdecl)))
2013 	      && cxx11_attribute_p (a)
2014 	      && get_attribute_namespace (a) == NULL_TREE)
2015 	    {
2016 	      error_at (newdecl_loc, "function %qD declared %<[[noreturn]]%> "
2017 			"but its first declaration was not", newdecl);
2018 	      inform (olddecl_loc, "previous declaration of %qD", olddecl);
2019 	    }
2020 	}
2021 
2022       /* Now that functions must hold information normally held
2023 	 by field decls, there is extra work to do so that
2024 	 declaration information does not get destroyed during
2025 	 definition.  */
2026       if (DECL_VINDEX (olddecl))
2027 	DECL_VINDEX (newdecl) = DECL_VINDEX (olddecl);
2028       if (DECL_CONTEXT (olddecl))
2029 	DECL_CONTEXT (newdecl) = DECL_CONTEXT (olddecl);
2030       DECL_STATIC_CONSTRUCTOR (newdecl) |= DECL_STATIC_CONSTRUCTOR (olddecl);
2031       DECL_STATIC_DESTRUCTOR (newdecl) |= DECL_STATIC_DESTRUCTOR (olddecl);
2032       DECL_PURE_VIRTUAL_P (newdecl) |= DECL_PURE_VIRTUAL_P (olddecl);
2033       DECL_VIRTUAL_P (newdecl) |= DECL_VIRTUAL_P (olddecl);
2034       DECL_INVALID_OVERRIDER_P (newdecl) |= DECL_INVALID_OVERRIDER_P (olddecl);
2035       DECL_FINAL_P (newdecl) |= DECL_FINAL_P (olddecl);
2036       DECL_OVERRIDE_P (newdecl) |= DECL_OVERRIDE_P (olddecl);
2037       DECL_THIS_STATIC (newdecl) |= DECL_THIS_STATIC (olddecl);
2038       DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (newdecl)
2039 	|= DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (olddecl);
2040       if (DECL_OVERLOADED_OPERATOR_P (olddecl))
2041 	DECL_OVERLOADED_OPERATOR_CODE_RAW (newdecl)
2042 	  = DECL_OVERLOADED_OPERATOR_CODE_RAW (olddecl);
2043       new_defines_function = DECL_INITIAL (newdecl) != NULL_TREE;
2044 
2045       /* Optionally warn about more than one declaration for the same
2046 	 name, but don't warn about a function declaration followed by a
2047 	 definition.  */
2048       if (warn_redundant_decls && ! DECL_ARTIFICIAL (olddecl)
2049 	  && !(new_defines_function && DECL_INITIAL (olddecl) == NULL_TREE)
2050 	  /* Don't warn about extern decl followed by definition.  */
2051 	  && !(DECL_EXTERNAL (olddecl) && ! DECL_EXTERNAL (newdecl))
2052 	  /* Don't warn about friends, let add_friend take care of it.  */
2053 	  && ! (newdecl_is_friend || DECL_FRIEND_P (olddecl))
2054 	  /* Don't warn about declaration followed by specialization.  */
2055 	  && (! DECL_TEMPLATE_SPECIALIZATION (newdecl)
2056 	      || DECL_TEMPLATE_SPECIALIZATION (olddecl)))
2057 	{
2058 	  auto_diagnostic_group d;
2059 	  if (warning_at (newdecl_loc,
2060 			  OPT_Wredundant_decls,
2061 			  "redundant redeclaration of %qD in same scope",
2062 			  newdecl))
2063 	    inform (olddecl_loc,
2064 		    "previous declaration of %qD", olddecl);
2065 	}
2066 
2067       if (!(DECL_TEMPLATE_INSTANTIATION (olddecl)
2068 	    && DECL_TEMPLATE_SPECIALIZATION (newdecl)))
2069 	{
2070 	  if (DECL_DELETED_FN (newdecl))
2071 	    {
2072 	      auto_diagnostic_group d;
2073 	      error_at (newdecl_loc, "deleted definition of %qD", newdecl);
2074 	      inform (olddecl_loc,
2075 		      "previous declaration of %qD", olddecl);
2076 	    }
2077 	  DECL_DELETED_FN (newdecl) |= DECL_DELETED_FN (olddecl);
2078 	}
2079     }
2080 
2081   /* Deal with C++: must preserve virtual function table size.  */
2082   if (TREE_CODE (olddecl) == TYPE_DECL)
2083     {
2084       tree newtype = TREE_TYPE (newdecl);
2085       tree oldtype = TREE_TYPE (olddecl);
2086 
2087       if (newtype != error_mark_node && oldtype != error_mark_node
2088 	  && TYPE_LANG_SPECIFIC (newtype) && TYPE_LANG_SPECIFIC (oldtype))
2089 	CLASSTYPE_FRIEND_CLASSES (newtype)
2090 	  = CLASSTYPE_FRIEND_CLASSES (oldtype);
2091 
2092       DECL_ORIGINAL_TYPE (newdecl) = DECL_ORIGINAL_TYPE (olddecl);
2093     }
2094 
2095   /* Copy all the DECL_... slots specified in the new decl except for
2096      any that we copy here from the old type.  */
2097   if (merge_attr)
2098     DECL_ATTRIBUTES (newdecl)
2099       = (*targetm.merge_decl_attributes) (olddecl, newdecl);
2100   else
2101     DECL_ATTRIBUTES (olddecl) = DECL_ATTRIBUTES (newdecl);
2102 
2103   if (DECL_DECLARES_FUNCTION_P (olddecl))
2104     {
2105       olddecl_friend = DECL_FRIEND_P (olddecl);
2106       olddecl_hidden_friend = DECL_HIDDEN_FRIEND_P (olddecl);
2107       hidden_friend = (DECL_ANTICIPATED (olddecl)
2108 		       && DECL_HIDDEN_FRIEND_P (olddecl)
2109 		       && newdecl_is_friend);
2110       if (!hidden_friend)
2111 	{
2112 	  DECL_ANTICIPATED (olddecl) = 0;
2113 	  DECL_HIDDEN_FRIEND_P (olddecl) = 0;
2114 	}
2115     }
2116 
2117   if (TREE_CODE (newdecl) == TEMPLATE_DECL)
2118     {
2119       tree old_result = DECL_TEMPLATE_RESULT (olddecl);
2120       tree new_result = DECL_TEMPLATE_RESULT (newdecl);
2121       TREE_TYPE (olddecl) = TREE_TYPE (old_result);
2122 
2123       /* The new decl should not already have gathered any
2124 	 specializations.  */
2125       gcc_assert (!DECL_TEMPLATE_SPECIALIZATIONS (newdecl));
2126 
2127       DECL_ATTRIBUTES (old_result)
2128 	= (*targetm.merge_decl_attributes) (old_result, new_result);
2129 
2130       if (DECL_FUNCTION_TEMPLATE_P (newdecl))
2131 	{
2132 	  if (DECL_SOURCE_LOCATION (newdecl)
2133 	      != DECL_SOURCE_LOCATION (olddecl))
2134 	    {
2135 	      /* Per C++11 8.3.6/4, default arguments cannot be added in
2136 		 later declarations of a function template.  */
2137 	      check_redeclaration_no_default_args (newdecl);
2138 	      /* C++17 11.3.6/4: "If a friend declaration specifies a default
2139 		 argument expression, that declaration... shall be the only
2140 		 declaration of the function or function template in the
2141 		 translation unit."  */
2142 	      check_no_redeclaration_friend_default_args
2143 		(old_result, new_result, olddecl_hidden_friend);
2144 	    }
2145 
2146 	  check_default_args (newdecl);
2147 
2148 	  if (GNU_INLINE_P (old_result) != GNU_INLINE_P (new_result)
2149 	      && DECL_INITIAL (new_result))
2150 	    {
2151 	      if (DECL_INITIAL (old_result))
2152 		DECL_UNINLINABLE (old_result) = 1;
2153 	      else
2154 		DECL_UNINLINABLE (old_result) = DECL_UNINLINABLE (new_result);
2155 	      DECL_EXTERNAL (old_result) = DECL_EXTERNAL (new_result);
2156 	      DECL_NOT_REALLY_EXTERN (old_result)
2157 		= DECL_NOT_REALLY_EXTERN (new_result);
2158 	      DECL_INTERFACE_KNOWN (old_result)
2159 		= DECL_INTERFACE_KNOWN (new_result);
2160 	      DECL_DECLARED_INLINE_P (old_result)
2161 		= DECL_DECLARED_INLINE_P (new_result);
2162 	      DECL_DISREGARD_INLINE_LIMITS (old_result)
2163 	        |= DECL_DISREGARD_INLINE_LIMITS (new_result);
2164 
2165 	    }
2166 	  else
2167 	    {
2168 	      DECL_DECLARED_INLINE_P (old_result)
2169 		|= DECL_DECLARED_INLINE_P (new_result);
2170 	      DECL_DISREGARD_INLINE_LIMITS (old_result)
2171 	        |= DECL_DISREGARD_INLINE_LIMITS (new_result);
2172 	      check_redeclaration_exception_specification (newdecl, olddecl);
2173 
2174 	      merge_attribute_bits (new_result, old_result);
2175 	    }
2176 	}
2177 
2178       /* If the new declaration is a definition, update the file and
2179 	 line information on the declaration, and also make
2180 	 the old declaration the same definition.  */
2181       if (DECL_INITIAL (new_result) != NULL_TREE)
2182 	{
2183 	  DECL_SOURCE_LOCATION (olddecl)
2184 	    = DECL_SOURCE_LOCATION (old_result)
2185 	    = DECL_SOURCE_LOCATION (newdecl);
2186 	  DECL_INITIAL (old_result) = DECL_INITIAL (new_result);
2187 	  if (DECL_FUNCTION_TEMPLATE_P (newdecl))
2188 	    {
2189 	      tree parm;
2190 	      DECL_ARGUMENTS (old_result)
2191 		= DECL_ARGUMENTS (new_result);
2192 	      for (parm = DECL_ARGUMENTS (old_result); parm;
2193 		   parm = DECL_CHAIN (parm))
2194 		DECL_CONTEXT (parm) = old_result;
2195 	    }
2196 	}
2197 
2198       return olddecl;
2199     }
2200 
2201   if (types_match)
2202     {
2203       if (TREE_CODE (newdecl) == FUNCTION_DECL)
2204 	check_redeclaration_exception_specification (newdecl, olddecl);
2205 
2206       /* Automatically handles default parameters.  */
2207       tree oldtype = TREE_TYPE (olddecl);
2208       tree newtype;
2209 
2210       /* For typedefs use the old type, as the new type's DECL_NAME points
2211 	 at newdecl, which will be ggc_freed.  */
2212       if (TREE_CODE (newdecl) == TYPE_DECL)
2213 	{
2214 	  /* But NEWTYPE might have an attribute, honor that.  */
2215 	  tree tem = TREE_TYPE (newdecl);
2216 	  newtype = oldtype;
2217 
2218 	  if (TYPE_USER_ALIGN (tem))
2219 	    {
2220 	      if (TYPE_ALIGN (tem) > TYPE_ALIGN (newtype))
2221 		SET_TYPE_ALIGN (newtype, TYPE_ALIGN (tem));
2222 	      TYPE_USER_ALIGN (newtype) = true;
2223 	    }
2224 
2225 	  /* And remove the new type from the variants list.  */
2226 	  if (TYPE_NAME (TREE_TYPE (newdecl)) == newdecl)
2227 	    {
2228 	      tree remove = TREE_TYPE (newdecl);
2229 	      if (TYPE_MAIN_VARIANT (remove) == remove)
2230 		{
2231 		  gcc_assert (TYPE_NEXT_VARIANT (remove) == NULL_TREE);
2232 		  /* If remove is the main variant, no need to remove that
2233 		     from the list.  One of the DECL_ORIGINAL_TYPE
2234 		     variants, e.g. created for aligned attribute, might still
2235 		     refer to the newdecl TYPE_DECL though, so remove that one
2236 		     in that case.  */
2237 		  if (tree orig = DECL_ORIGINAL_TYPE (newdecl))
2238 		    if (orig != remove)
2239 		      for (tree t = TYPE_MAIN_VARIANT (orig); t;
2240 			   t = TYPE_MAIN_VARIANT (t))
2241 			if (TYPE_NAME (TYPE_NEXT_VARIANT (t)) == newdecl)
2242 			  {
2243 			    TYPE_NEXT_VARIANT (t)
2244 			      = TYPE_NEXT_VARIANT (TYPE_NEXT_VARIANT (t));
2245 			    break;
2246 			  }
2247 		}
2248 	      else
2249 		for (tree t = TYPE_MAIN_VARIANT (remove); ;
2250 		     t = TYPE_NEXT_VARIANT (t))
2251 		  if (TYPE_NEXT_VARIANT (t) == remove)
2252 		    {
2253 		      TYPE_NEXT_VARIANT (t) = TYPE_NEXT_VARIANT (remove);
2254 		      break;
2255 		    }
2256 	    }
2257 	}
2258       else if (merge_attr)
2259 	newtype = merge_types (TREE_TYPE (newdecl), TREE_TYPE (olddecl));
2260       else
2261 	newtype = TREE_TYPE (newdecl);
2262 
2263       if (VAR_P (newdecl))
2264 	{
2265 	  DECL_THIS_EXTERN (newdecl) |= DECL_THIS_EXTERN (olddecl);
2266 	  /* For already initialized vars, TREE_READONLY could have been
2267 	     cleared in cp_finish_decl, because the var needs runtime
2268 	     initialization or destruction.  Make sure not to set
2269 	     TREE_READONLY on it again.  */
2270 	  if (DECL_INITIALIZED_P (olddecl)
2271 	      && !DECL_EXTERNAL (olddecl)
2272 	      && !TREE_READONLY (olddecl))
2273 	    TREE_READONLY (newdecl) = 0;
2274 	  DECL_INITIALIZED_P (newdecl) |= DECL_INITIALIZED_P (olddecl);
2275 	  DECL_NONTRIVIALLY_INITIALIZED_P (newdecl)
2276 	    |= DECL_NONTRIVIALLY_INITIALIZED_P (olddecl);
2277 	  if (DECL_DEPENDENT_INIT_P (olddecl))
2278 	    SET_DECL_DEPENDENT_INIT_P (newdecl, true);
2279 	  DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (newdecl)
2280 	    |= DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (olddecl);
2281 	  DECL_DECLARED_CONSTEXPR_P (newdecl)
2282 	    |= DECL_DECLARED_CONSTEXPR_P (olddecl);
2283 
2284 	  /* Merge the threadprivate attribute from OLDDECL into NEWDECL.  */
2285 	  if (DECL_LANG_SPECIFIC (olddecl)
2286 	      && CP_DECL_THREADPRIVATE_P (olddecl))
2287 	    {
2288 	      /* Allocate a LANG_SPECIFIC structure for NEWDECL, if needed.  */
2289 	      retrofit_lang_decl (newdecl);
2290 	      CP_DECL_THREADPRIVATE_P (newdecl) = 1;
2291 	    }
2292 	}
2293 
2294       /* An explicit specialization of a function template or of a member
2295 	 function of a class template can be declared transaction_safe
2296 	 independently of whether the corresponding template entity is declared
2297 	 transaction_safe. */
2298       if (flag_tm && TREE_CODE (newdecl) == FUNCTION_DECL
2299 	  && DECL_TEMPLATE_INSTANTIATION (olddecl)
2300 	  && DECL_TEMPLATE_SPECIALIZATION (newdecl)
2301 	  && tx_safe_fn_type_p (newtype)
2302 	  && !tx_safe_fn_type_p (TREE_TYPE (newdecl)))
2303 	newtype = tx_unsafe_fn_variant (newtype);
2304 
2305       TREE_TYPE (newdecl) = TREE_TYPE (olddecl) = newtype;
2306 
2307       if (TREE_CODE (newdecl) == FUNCTION_DECL)
2308 	check_default_args (newdecl);
2309 
2310       /* Lay the type out, unless already done.  */
2311       if (! same_type_p (newtype, oldtype)
2312 	  && TREE_TYPE (newdecl) != error_mark_node
2313 	  && !(processing_template_decl && uses_template_parms (newdecl)))
2314 	layout_type (TREE_TYPE (newdecl));
2315 
2316       if ((VAR_P (newdecl)
2317 	   || TREE_CODE (newdecl) == PARM_DECL
2318 	   || TREE_CODE (newdecl) == RESULT_DECL
2319 	   || TREE_CODE (newdecl) == FIELD_DECL
2320 	   || TREE_CODE (newdecl) == TYPE_DECL)
2321 	  && !(processing_template_decl && uses_template_parms (newdecl)))
2322 	layout_decl (newdecl, 0);
2323 
2324       /* Merge deprecatedness.  */
2325       if (TREE_DEPRECATED (newdecl))
2326 	TREE_DEPRECATED (olddecl) = 1;
2327 
2328       /* Preserve function specific target and optimization options */
2329       if (TREE_CODE (newdecl) == FUNCTION_DECL)
2330 	{
2331 	  if (DECL_FUNCTION_SPECIFIC_TARGET (olddecl)
2332 	      && !DECL_FUNCTION_SPECIFIC_TARGET (newdecl))
2333 	    DECL_FUNCTION_SPECIFIC_TARGET (newdecl)
2334 	      = DECL_FUNCTION_SPECIFIC_TARGET (olddecl);
2335 
2336 	  if (DECL_FUNCTION_SPECIFIC_OPTIMIZATION (olddecl)
2337 	      && !DECL_FUNCTION_SPECIFIC_OPTIMIZATION (newdecl))
2338 	    DECL_FUNCTION_SPECIFIC_OPTIMIZATION (newdecl)
2339 	      = DECL_FUNCTION_SPECIFIC_OPTIMIZATION (olddecl);
2340 	}
2341       else
2342 	{
2343 	  /* Merge the const type qualifier.  */
2344 	  if (TREE_READONLY (newdecl))
2345 	    TREE_READONLY (olddecl) = 1;
2346 	  /* Merge the volatile type qualifier.  */
2347 	  if (TREE_THIS_VOLATILE (newdecl))
2348 	    TREE_THIS_VOLATILE (olddecl) = 1;
2349 	}
2350 
2351       /* Merge the initialization information.  */
2352       if (DECL_INITIAL (newdecl) == NULL_TREE
2353 	  && DECL_INITIAL (olddecl) != NULL_TREE)
2354 	{
2355 	  DECL_INITIAL (newdecl) = DECL_INITIAL (olddecl);
2356 	  DECL_SOURCE_LOCATION (newdecl) = DECL_SOURCE_LOCATION (olddecl);
2357 	  if (TREE_CODE (newdecl) == FUNCTION_DECL)
2358 	    {
2359 	      DECL_SAVED_TREE (newdecl) = DECL_SAVED_TREE (olddecl);
2360 	      DECL_STRUCT_FUNCTION (newdecl) = DECL_STRUCT_FUNCTION (olddecl);
2361 	    }
2362 	}
2363 
2364       if (TREE_CODE (newdecl) == FUNCTION_DECL)
2365 	{
2366 	  DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (newdecl)
2367 	    |= DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT (olddecl);
2368 	  DECL_NO_LIMIT_STACK (newdecl) |= DECL_NO_LIMIT_STACK (olddecl);
2369 	  if (DECL_IS_OPERATOR_NEW_P (olddecl))
2370 	    DECL_SET_IS_OPERATOR_NEW (newdecl, true);
2371 	  DECL_LOOPING_CONST_OR_PURE_P (newdecl)
2372 	    |= DECL_LOOPING_CONST_OR_PURE_P (olddecl);
2373 	  DECL_IS_REPLACEABLE_OPERATOR (newdecl)
2374 	    |= DECL_IS_REPLACEABLE_OPERATOR (olddecl);
2375 
2376 	  if (merge_attr)
2377 	    merge_attribute_bits (newdecl, olddecl);
2378 	  else
2379 	    {
2380 	      /* Merge the noreturn bit.  */
2381 	      TREE_THIS_VOLATILE (olddecl) = TREE_THIS_VOLATILE (newdecl);
2382 	      TREE_READONLY (olddecl) = TREE_READONLY (newdecl);
2383 	      TREE_NOTHROW (olddecl) = TREE_NOTHROW (newdecl);
2384 	      DECL_IS_MALLOC (olddecl) = DECL_IS_MALLOC (newdecl);
2385 	      DECL_PURE_P (olddecl) = DECL_PURE_P (newdecl);
2386 	    }
2387 	  /* Keep the old RTL.  */
2388 	  COPY_DECL_RTL (olddecl, newdecl);
2389 	}
2390       else if (VAR_P (newdecl)
2391 	       && (DECL_SIZE (olddecl) || !DECL_SIZE (newdecl)))
2392 	{
2393 	  /* Keep the old RTL.  We cannot keep the old RTL if the old
2394 	     declaration was for an incomplete object and the new
2395 	     declaration is not since many attributes of the RTL will
2396 	     change.  */
2397 	  COPY_DECL_RTL (olddecl, newdecl);
2398 	}
2399     }
2400   /* If cannot merge, then use the new type and qualifiers,
2401      and don't preserve the old rtl.  */
2402   else
2403     {
2404       /* Clean out any memory we had of the old declaration.  */
2405       tree oldstatic = value_member (olddecl, static_aggregates);
2406       if (oldstatic)
2407 	TREE_VALUE (oldstatic) = error_mark_node;
2408 
2409       TREE_TYPE (olddecl) = TREE_TYPE (newdecl);
2410       TREE_READONLY (olddecl) = TREE_READONLY (newdecl);
2411       TREE_THIS_VOLATILE (olddecl) = TREE_THIS_VOLATILE (newdecl);
2412       TREE_NOTHROW (olddecl) = TREE_NOTHROW (newdecl);
2413       TREE_SIDE_EFFECTS (olddecl) = TREE_SIDE_EFFECTS (newdecl);
2414     }
2415 
2416   /* Merge the storage class information.  */
2417   merge_weak (newdecl, olddecl);
2418 
2419   DECL_DEFER_OUTPUT (newdecl) |= DECL_DEFER_OUTPUT (olddecl);
2420   TREE_PUBLIC (newdecl) = TREE_PUBLIC (olddecl);
2421   TREE_STATIC (olddecl) = TREE_STATIC (newdecl) |= TREE_STATIC (olddecl);
2422   if (! DECL_EXTERNAL (olddecl))
2423     DECL_EXTERNAL (newdecl) = 0;
2424   if (! DECL_COMDAT (olddecl))
2425     DECL_COMDAT (newdecl) = 0;
2426 
2427   new_template_info = NULL_TREE;
2428   if (DECL_LANG_SPECIFIC (newdecl) && DECL_LANG_SPECIFIC (olddecl))
2429     {
2430       bool new_redefines_gnu_inline = false;
2431 
2432       if (new_defines_function
2433 	  && ((DECL_INTERFACE_KNOWN (olddecl)
2434 	       && TREE_CODE (olddecl) == FUNCTION_DECL)
2435 	      || (TREE_CODE (olddecl) == TEMPLATE_DECL
2436 		  && (TREE_CODE (DECL_TEMPLATE_RESULT (olddecl))
2437 		      == FUNCTION_DECL))))
2438 	{
2439 	  tree fn = olddecl;
2440 
2441 	  if (TREE_CODE (fn) == TEMPLATE_DECL)
2442 	    fn = DECL_TEMPLATE_RESULT (olddecl);
2443 
2444 	  new_redefines_gnu_inline = GNU_INLINE_P (fn) && DECL_INITIAL (fn);
2445 	}
2446 
2447       if (!new_redefines_gnu_inline)
2448 	{
2449 	  DECL_INTERFACE_KNOWN (newdecl) |= DECL_INTERFACE_KNOWN (olddecl);
2450 	  DECL_NOT_REALLY_EXTERN (newdecl) |= DECL_NOT_REALLY_EXTERN (olddecl);
2451 	  DECL_COMDAT (newdecl) |= DECL_COMDAT (olddecl);
2452 	}
2453       DECL_TEMPLATE_INSTANTIATED (newdecl)
2454 	|= DECL_TEMPLATE_INSTANTIATED (olddecl);
2455       DECL_ODR_USED (newdecl) |= DECL_ODR_USED (olddecl);
2456 
2457       /* If the OLDDECL is an instantiation and/or specialization,
2458 	 then the NEWDECL must be too.  But, it may not yet be marked
2459 	 as such if the caller has created NEWDECL, but has not yet
2460 	 figured out that it is a redeclaration.  */
2461       if (!DECL_USE_TEMPLATE (newdecl))
2462 	DECL_USE_TEMPLATE (newdecl) = DECL_USE_TEMPLATE (olddecl);
2463 
2464       /* Don't really know how much of the language-specific
2465 	 values we should copy from old to new.  */
2466       DECL_IN_AGGR_P (newdecl) = DECL_IN_AGGR_P (olddecl);
2467       DECL_INITIALIZED_IN_CLASS_P (newdecl)
2468 	|= DECL_INITIALIZED_IN_CLASS_P (olddecl);
2469 
2470       if (LANG_DECL_HAS_MIN (newdecl))
2471 	{
2472 	  DECL_ACCESS (newdecl) = DECL_ACCESS (olddecl);
2473 	  if (DECL_TEMPLATE_INFO (newdecl))
2474 	    {
2475 	      new_template_info = DECL_TEMPLATE_INFO (newdecl);
2476 	      if (DECL_TEMPLATE_INSTANTIATION (olddecl)
2477 		  && DECL_TEMPLATE_SPECIALIZATION (newdecl))
2478 		/* Remember the presence of explicit specialization args.  */
2479 		TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (olddecl))
2480 		  = TINFO_USED_TEMPLATE_ID (new_template_info);
2481 	    }
2482 	  DECL_TEMPLATE_INFO (newdecl) = DECL_TEMPLATE_INFO (olddecl);
2483 	}
2484 
2485       if (DECL_DECLARES_FUNCTION_P (newdecl))
2486 	{
2487 	  /* Only functions have these fields.  */
2488 	  DECL_NONCONVERTING_P (newdecl) = DECL_NONCONVERTING_P (olddecl);
2489 	  DECL_BEFRIENDING_CLASSES (newdecl)
2490 	    = chainon (DECL_BEFRIENDING_CLASSES (newdecl),
2491 		       DECL_BEFRIENDING_CLASSES (olddecl));
2492 	  /* DECL_THUNKS is only valid for virtual functions,
2493 	     otherwise it is a DECL_FRIEND_CONTEXT.  */
2494 	  if (DECL_VIRTUAL_P (newdecl))
2495 	    SET_DECL_THUNKS (newdecl, DECL_THUNKS (olddecl));
2496 	}
2497       else if (VAR_P (newdecl))
2498 	{
2499 	  /* Only variables have this field.  */
2500 	  if (VAR_HAD_UNKNOWN_BOUND (olddecl))
2501 	    SET_VAR_HAD_UNKNOWN_BOUND (newdecl);
2502 	}
2503     }
2504 
2505   if (TREE_CODE (newdecl) == FUNCTION_DECL)
2506     {
2507       tree parm;
2508 
2509       /* Merge parameter attributes. */
2510       tree oldarg, newarg;
2511       for (oldarg = DECL_ARGUMENTS(olddecl),  newarg = DECL_ARGUMENTS(newdecl);
2512            oldarg && newarg;
2513            oldarg = DECL_CHAIN(oldarg), newarg = DECL_CHAIN(newarg))
2514 	{
2515           DECL_ATTRIBUTES (newarg)
2516 	    = (*targetm.merge_decl_attributes) (oldarg, newarg);
2517           DECL_ATTRIBUTES (oldarg) = DECL_ATTRIBUTES (newarg);
2518 	}
2519 
2520       if (DECL_TEMPLATE_INSTANTIATION (olddecl)
2521 	  && !DECL_TEMPLATE_INSTANTIATION (newdecl))
2522 	{
2523 	  /* If newdecl is not a specialization, then it is not a
2524 	     template-related function at all.  And that means that we
2525 	     should have exited above, returning 0.  */
2526 	  gcc_assert (DECL_TEMPLATE_SPECIALIZATION (newdecl));
2527 
2528 	  if (DECL_ODR_USED (olddecl))
2529 	    /* From [temp.expl.spec]:
2530 
2531 	       If a template, a member template or the member of a class
2532 	       template is explicitly specialized then that
2533 	       specialization shall be declared before the first use of
2534 	       that specialization that would cause an implicit
2535 	       instantiation to take place, in every translation unit in
2536 	       which such a use occurs.  */
2537 	    error ("explicit specialization of %qD after first use",
2538 		      olddecl);
2539 
2540 	  SET_DECL_TEMPLATE_SPECIALIZATION (olddecl);
2541 	  DECL_COMDAT (newdecl) = (TREE_PUBLIC (newdecl)
2542 				   && DECL_DECLARED_INLINE_P (newdecl));
2543 
2544 	  /* Don't propagate visibility from the template to the
2545 	     specialization here.  We'll do that in determine_visibility if
2546 	     appropriate.  */
2547 	  DECL_VISIBILITY_SPECIFIED (olddecl) = 0;
2548 
2549 	  /* [temp.expl.spec/14] We don't inline explicit specialization
2550 	     just because the primary template says so.  */
2551 	  gcc_assert (!merge_attr);
2552 
2553 	  DECL_DECLARED_INLINE_P (olddecl)
2554 	    = DECL_DECLARED_INLINE_P (newdecl);
2555 
2556 	  DECL_DISREGARD_INLINE_LIMITS (olddecl)
2557 	    = DECL_DISREGARD_INLINE_LIMITS (newdecl);
2558 
2559 	  DECL_UNINLINABLE (olddecl) = DECL_UNINLINABLE (newdecl);
2560 	}
2561       else if (new_defines_function && DECL_INITIAL (olddecl))
2562 	{
2563 	  /* Never inline re-defined extern inline functions.
2564 	     FIXME: this could be better handled by keeping both
2565 	     function as separate declarations.  */
2566 	  DECL_UNINLINABLE (newdecl) = 1;
2567 	}
2568       else
2569 	{
2570 	  if (DECL_PENDING_INLINE_P (olddecl))
2571 	    {
2572 	      DECL_PENDING_INLINE_P (newdecl) = 1;
2573 	      DECL_PENDING_INLINE_INFO (newdecl)
2574 		= DECL_PENDING_INLINE_INFO (olddecl);
2575 	    }
2576 	  else if (DECL_PENDING_INLINE_P (newdecl))
2577 	    ;
2578 	  else if (DECL_SAVED_AUTO_RETURN_TYPE (newdecl) == NULL)
2579 	    DECL_SAVED_AUTO_RETURN_TYPE (newdecl)
2580 	      = DECL_SAVED_AUTO_RETURN_TYPE (olddecl);
2581 
2582 	  DECL_DECLARED_INLINE_P (newdecl) |= DECL_DECLARED_INLINE_P (olddecl);
2583 
2584 	  DECL_UNINLINABLE (newdecl) = DECL_UNINLINABLE (olddecl)
2585 	    = (DECL_UNINLINABLE (newdecl) || DECL_UNINLINABLE (olddecl));
2586 
2587 	  DECL_DISREGARD_INLINE_LIMITS (newdecl)
2588 	    = DECL_DISREGARD_INLINE_LIMITS (olddecl)
2589 	    = (DECL_DISREGARD_INLINE_LIMITS (newdecl)
2590 	       || DECL_DISREGARD_INLINE_LIMITS (olddecl));
2591 	}
2592 
2593       /* Preserve abstractness on cloned [cd]tors.  */
2594       DECL_ABSTRACT_P (newdecl) = DECL_ABSTRACT_P (olddecl);
2595 
2596       /* Update newdecl's parms to point at olddecl.  */
2597       for (parm = DECL_ARGUMENTS (newdecl); parm;
2598 	   parm = DECL_CHAIN (parm))
2599 	DECL_CONTEXT (parm) = olddecl;
2600 
2601       if (! types_match)
2602 	{
2603 	  SET_DECL_LANGUAGE (olddecl, DECL_LANGUAGE (newdecl));
2604 	  COPY_DECL_ASSEMBLER_NAME (newdecl, olddecl);
2605 	  COPY_DECL_RTL (newdecl, olddecl);
2606 	}
2607       if (! types_match || new_defines_function)
2608 	{
2609 	  /* These need to be copied so that the names are available.
2610 	     Note that if the types do match, we'll preserve inline
2611 	     info and other bits, but if not, we won't.  */
2612 	  DECL_ARGUMENTS (olddecl) = DECL_ARGUMENTS (newdecl);
2613 	  DECL_RESULT (olddecl) = DECL_RESULT (newdecl);
2614 	}
2615       /* If redeclaring a builtin function, it stays built in
2616 	 if newdecl is a gnu_inline definition, or if newdecl is just
2617 	 a declaration.  */
2618       if (fndecl_built_in_p (olddecl)
2619 	  && (new_defines_function ? GNU_INLINE_P (newdecl) : types_match))
2620 	{
2621 	  copy_decl_built_in_function (newdecl, olddecl);
2622 	  /* If we're keeping the built-in definition, keep the rtl,
2623 	     regardless of declaration matches.  */
2624 	  COPY_DECL_RTL (olddecl, newdecl);
2625 	  if (DECL_BUILT_IN_CLASS (newdecl) == BUILT_IN_NORMAL)
2626 	    {
2627 	      enum built_in_function fncode = DECL_FUNCTION_CODE (newdecl);
2628 	      switch (fncode)
2629 		{
2630 		  /* If a compatible prototype of these builtin functions
2631 		     is seen, assume the runtime implements it with the
2632 		     expected semantics.  */
2633 		case BUILT_IN_STPCPY:
2634 		  if (builtin_decl_explicit_p (fncode))
2635 		    set_builtin_decl_implicit_p (fncode, true);
2636 		  break;
2637 		default:
2638 		  if (builtin_decl_explicit_p (fncode))
2639 		    set_builtin_decl_declared_p (fncode, true);
2640 		  break;
2641 		}
2642 
2643 	      copy_attributes_to_builtin (newdecl);
2644 	    }
2645 	}
2646       if (new_defines_function)
2647 	/* If defining a function declared with other language
2648 	   linkage, use the previously declared language linkage.  */
2649 	SET_DECL_LANGUAGE (newdecl, DECL_LANGUAGE (olddecl));
2650       else if (types_match)
2651 	{
2652 	  DECL_RESULT (newdecl) = DECL_RESULT (olddecl);
2653 	  /* Don't clear out the arguments if we're just redeclaring a
2654 	     function.  */
2655 	  if (DECL_ARGUMENTS (olddecl))
2656 	    DECL_ARGUMENTS (newdecl) = DECL_ARGUMENTS (olddecl);
2657 	}
2658     }
2659   else if (TREE_CODE (newdecl) == NAMESPACE_DECL)
2660     NAMESPACE_LEVEL (newdecl) = NAMESPACE_LEVEL (olddecl);
2661 
2662   /* Now preserve various other info from the definition.  */
2663   TREE_ADDRESSABLE (newdecl) = TREE_ADDRESSABLE (olddecl);
2664   TREE_ASM_WRITTEN (newdecl) = TREE_ASM_WRITTEN (olddecl);
2665   DECL_COMMON (newdecl) = DECL_COMMON (olddecl);
2666   COPY_DECL_ASSEMBLER_NAME (olddecl, newdecl);
2667 
2668   /* Warn about conflicting visibility specifications.  */
2669   if (DECL_VISIBILITY_SPECIFIED (olddecl)
2670       && DECL_VISIBILITY_SPECIFIED (newdecl)
2671       && DECL_VISIBILITY (newdecl) != DECL_VISIBILITY (olddecl))
2672     {
2673       auto_diagnostic_group d;
2674       if (warning_at (newdecl_loc, OPT_Wattributes,
2675 		      "%qD: visibility attribute ignored because it "
2676 		      "conflicts with previous declaration", newdecl))
2677 	inform (olddecl_loc,
2678 		"previous declaration of %qD", olddecl);
2679     }
2680   /* Choose the declaration which specified visibility.  */
2681   if (DECL_VISIBILITY_SPECIFIED (olddecl))
2682     {
2683       DECL_VISIBILITY (newdecl) = DECL_VISIBILITY (olddecl);
2684       DECL_VISIBILITY_SPECIFIED (newdecl) = 1;
2685     }
2686   /* Init priority used to be merged from newdecl to olddecl by the memcpy,
2687      so keep this behavior.  */
2688   if (VAR_P (newdecl) && DECL_HAS_INIT_PRIORITY_P (newdecl))
2689     {
2690       SET_DECL_INIT_PRIORITY (olddecl, DECL_INIT_PRIORITY (newdecl));
2691       DECL_HAS_INIT_PRIORITY_P (olddecl) = 1;
2692     }
2693   /* Likewise for DECL_ALIGN, DECL_USER_ALIGN and DECL_PACKED.  */
2694   if (DECL_ALIGN (olddecl) > DECL_ALIGN (newdecl))
2695     {
2696       SET_DECL_ALIGN (newdecl, DECL_ALIGN (olddecl));
2697       DECL_USER_ALIGN (newdecl) |= DECL_USER_ALIGN (olddecl);
2698     }
2699   DECL_USER_ALIGN (olddecl) = DECL_USER_ALIGN (newdecl);
2700   if (DECL_WARN_IF_NOT_ALIGN (olddecl)
2701       > DECL_WARN_IF_NOT_ALIGN (newdecl))
2702     SET_DECL_WARN_IF_NOT_ALIGN (newdecl,
2703 				DECL_WARN_IF_NOT_ALIGN (olddecl));
2704   if (TREE_CODE (newdecl) == FIELD_DECL)
2705     DECL_PACKED (olddecl) = DECL_PACKED (newdecl);
2706 
2707   /* The DECL_LANG_SPECIFIC information in OLDDECL will be replaced
2708      with that from NEWDECL below.  */
2709   if (DECL_LANG_SPECIFIC (olddecl))
2710     {
2711       gcc_assert (DECL_LANG_SPECIFIC (olddecl)
2712 		  != DECL_LANG_SPECIFIC (newdecl));
2713       ggc_free (DECL_LANG_SPECIFIC (olddecl));
2714     }
2715 
2716   /* Merge the USED information.  */
2717   if (TREE_USED (olddecl))
2718     TREE_USED (newdecl) = 1;
2719   else if (TREE_USED (newdecl))
2720     TREE_USED (olddecl) = 1;
2721   if (VAR_P (newdecl))
2722     {
2723       if (DECL_READ_P (olddecl))
2724 	DECL_READ_P (newdecl) = 1;
2725       else if (DECL_READ_P (newdecl))
2726 	DECL_READ_P (olddecl) = 1;
2727     }
2728   if (DECL_PRESERVE_P (olddecl))
2729     DECL_PRESERVE_P (newdecl) = 1;
2730   else if (DECL_PRESERVE_P (newdecl))
2731     DECL_PRESERVE_P (olddecl) = 1;
2732 
2733   /* Merge the DECL_FUNCTION_VERSIONED information.  newdecl will be copied
2734      to olddecl and deleted.  */
2735   if (TREE_CODE (newdecl) == FUNCTION_DECL
2736       && DECL_FUNCTION_VERSIONED (olddecl))
2737     {
2738       /* Set the flag for newdecl so that it gets copied to olddecl.  */
2739       DECL_FUNCTION_VERSIONED (newdecl) = 1;
2740       /* newdecl will be purged after copying to olddecl and is no longer
2741          a version.  */
2742       cgraph_node::delete_function_version_by_decl (newdecl);
2743     }
2744 
2745   if (TREE_CODE (newdecl) == FUNCTION_DECL)
2746     {
2747       int function_size;
2748       struct symtab_node *snode = symtab_node::get (olddecl);
2749 
2750       function_size = sizeof (struct tree_decl_common);
2751 
2752       memcpy ((char *) olddecl + sizeof (struct tree_common),
2753 	      (char *) newdecl + sizeof (struct tree_common),
2754 	      function_size - sizeof (struct tree_common));
2755 
2756       memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
2757 	      (char *) newdecl + sizeof (struct tree_decl_common),
2758 	      sizeof (struct tree_function_decl) - sizeof (struct tree_decl_common));
2759 
2760       /* Preserve symtab node mapping.  */
2761       olddecl->decl_with_vis.symtab_node = snode;
2762 
2763       if (new_template_info)
2764 	/* If newdecl is a template instantiation, it is possible that
2765 	   the following sequence of events has occurred:
2766 
2767 	   o A friend function was declared in a class template.  The
2768 	   class template was instantiated.
2769 
2770 	   o The instantiation of the friend declaration was
2771 	   recorded on the instantiation list, and is newdecl.
2772 
2773 	   o Later, however, instantiate_class_template called pushdecl
2774 	   on the newdecl to perform name injection.  But, pushdecl in
2775 	   turn called duplicate_decls when it discovered that another
2776 	   declaration of a global function with the same name already
2777 	   existed.
2778 
2779 	   o Here, in duplicate_decls, we decided to clobber newdecl.
2780 
2781 	   If we're going to do that, we'd better make sure that
2782 	   olddecl, and not newdecl, is on the list of
2783 	   instantiations so that if we try to do the instantiation
2784 	   again we won't get the clobbered declaration.  */
2785 	reregister_specialization (newdecl,
2786 				   new_template_info,
2787 				   olddecl);
2788     }
2789   else
2790     {
2791       size_t size = tree_code_size (TREE_CODE (newdecl));
2792 
2793       memcpy ((char *) olddecl + sizeof (struct tree_common),
2794 	      (char *) newdecl + sizeof (struct tree_common),
2795 	      sizeof (struct tree_decl_common) - sizeof (struct tree_common));
2796       switch (TREE_CODE (newdecl))
2797 	{
2798 	case LABEL_DECL:
2799 	case VAR_DECL:
2800 	case RESULT_DECL:
2801 	case PARM_DECL:
2802 	case FIELD_DECL:
2803 	case TYPE_DECL:
2804 	case CONST_DECL:
2805 	  {
2806             struct symtab_node *snode = NULL;
2807 
2808 	    if (VAR_P (newdecl)
2809 		&& (TREE_STATIC (olddecl) || TREE_PUBLIC (olddecl)
2810 		    || DECL_EXTERNAL (olddecl)))
2811 	      snode = symtab_node::get (olddecl);
2812 	    memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
2813 		    (char *) newdecl + sizeof (struct tree_decl_common),
2814 		    size - sizeof (struct tree_decl_common)
2815 		    + TREE_CODE_LENGTH (TREE_CODE (newdecl)) * sizeof (char *));
2816 	    if (VAR_P (newdecl))
2817 	      olddecl->decl_with_vis.symtab_node = snode;
2818 	  }
2819 	  break;
2820 	default:
2821 	  memcpy ((char *) olddecl + sizeof (struct tree_decl_common),
2822 		  (char *) newdecl + sizeof (struct tree_decl_common),
2823 		  sizeof (struct tree_decl_non_common) - sizeof (struct tree_decl_common)
2824 		  + TREE_CODE_LENGTH (TREE_CODE (newdecl)) * sizeof (char *));
2825 	  break;
2826 	}
2827     }
2828 
2829   if (VAR_OR_FUNCTION_DECL_P (newdecl))
2830     {
2831       if (DECL_EXTERNAL (olddecl)
2832 	  || TREE_PUBLIC (olddecl)
2833 	  || TREE_STATIC (olddecl))
2834 	{
2835 	  /* Merge the section attribute.
2836 	     We want to issue an error if the sections conflict but that must be
2837 	     done later in decl_attributes since we are called before attributes
2838 	     are assigned.  */
2839 	  if (DECL_SECTION_NAME (newdecl) != NULL)
2840 	    set_decl_section_name (olddecl, DECL_SECTION_NAME (newdecl));
2841 
2842 	  if (DECL_ONE_ONLY (newdecl))
2843 	    {
2844 	      struct symtab_node *oldsym, *newsym;
2845 	      if (TREE_CODE (olddecl) == FUNCTION_DECL)
2846 		oldsym = cgraph_node::get_create (olddecl);
2847 	      else
2848 		oldsym = varpool_node::get_create (olddecl);
2849 	      newsym = symtab_node::get (newdecl);
2850 	      oldsym->set_comdat_group (newsym->get_comdat_group ());
2851 	    }
2852 	}
2853 
2854       if (VAR_P (newdecl)
2855 	  && CP_DECL_THREAD_LOCAL_P (newdecl))
2856 	{
2857 	  CP_DECL_THREAD_LOCAL_P (olddecl) = true;
2858 	  if (!processing_template_decl)
2859 	    set_decl_tls_model (olddecl, DECL_TLS_MODEL (newdecl));
2860 	}
2861     }
2862 
2863   DECL_UID (olddecl) = olddecl_uid;
2864   if (olddecl_friend)
2865     DECL_FRIEND_P (olddecl) = 1;
2866   if (hidden_friend)
2867     {
2868       DECL_ANTICIPATED (olddecl) = 1;
2869       DECL_HIDDEN_FRIEND_P (olddecl) = 1;
2870     }
2871 
2872   /* NEWDECL contains the merged attribute lists.
2873      Update OLDDECL to be the same.  */
2874   DECL_ATTRIBUTES (olddecl) = DECL_ATTRIBUTES (newdecl);
2875 
2876   /* If OLDDECL had its DECL_RTL instantiated, re-invoke make_decl_rtl
2877     so that encode_section_info has a chance to look at the new decl
2878     flags and attributes.  */
2879   if (DECL_RTL_SET_P (olddecl)
2880       && (TREE_CODE (olddecl) == FUNCTION_DECL
2881 	  || (VAR_P (olddecl)
2882 	      && TREE_STATIC (olddecl))))
2883     make_decl_rtl (olddecl);
2884 
2885   /* The NEWDECL will no longer be needed.  Because every out-of-class
2886      declaration of a member results in a call to duplicate_decls,
2887      freeing these nodes represents in a significant savings.
2888 
2889      Before releasing the node, be sore to remove function from symbol
2890      table that might have been inserted there to record comdat group.
2891      Be sure to however do not free DECL_STRUCT_FUNCTION because this
2892      structure is shared in between newdecl and oldecl.  */
2893   if (TREE_CODE (newdecl) == FUNCTION_DECL)
2894     DECL_STRUCT_FUNCTION (newdecl) = NULL;
2895   if (VAR_OR_FUNCTION_DECL_P (newdecl))
2896     {
2897       struct symtab_node *snode = symtab_node::get (newdecl);
2898       if (snode)
2899 	snode->remove ();
2900     }
2901 
2902   if (TREE_CODE (olddecl) == FUNCTION_DECL)
2903     {
2904       tree clone;
2905       FOR_EACH_CLONE (clone, olddecl)
2906 	{
2907 	  DECL_ATTRIBUTES (clone) = DECL_ATTRIBUTES (olddecl);
2908 	  DECL_PRESERVE_P (clone) |= DECL_PRESERVE_P (olddecl);
2909 	}
2910     }
2911 
2912   /* Remove the associated constraints for newdecl, if any, before
2913      reclaiming memory. */
2914   if (flag_concepts)
2915     remove_constraints (newdecl);
2916 
2917   ggc_free (newdecl);
2918 
2919   return olddecl;
2920 }
2921 
2922 /* Return zero if the declaration NEWDECL is valid
2923    when the declaration OLDDECL (assumed to be for the same name)
2924    has already been seen.
2925    Otherwise return an error message format string with a %s
2926    where the identifier should go.  */
2927 
2928 static const char *
redeclaration_error_message(tree newdecl,tree olddecl)2929 redeclaration_error_message (tree newdecl, tree olddecl)
2930 {
2931   if (TREE_CODE (newdecl) == TYPE_DECL)
2932     {
2933       /* Because C++ can put things into name space for free,
2934 	 constructs like "typedef struct foo { ... } foo"
2935 	 would look like an erroneous redeclaration.  */
2936       if (same_type_p (TREE_TYPE (newdecl), TREE_TYPE (olddecl)))
2937 	return NULL;
2938       else
2939 	return G_("redefinition of %q#D");
2940     }
2941   else if (TREE_CODE (newdecl) == FUNCTION_DECL)
2942     {
2943       /* If this is a pure function, its olddecl will actually be
2944 	 the original initialization to `0' (which we force to call
2945 	 abort()).  Don't complain about redefinition in this case.  */
2946       if (DECL_LANG_SPECIFIC (olddecl) && DECL_PURE_VIRTUAL_P (olddecl)
2947 	  && DECL_INITIAL (olddecl) == NULL_TREE)
2948 	return NULL;
2949 
2950       /* If both functions come from different namespaces, this is not
2951 	 a redeclaration - this is a conflict with a used function.  */
2952       if (DECL_NAMESPACE_SCOPE_P (olddecl)
2953 	  && DECL_CONTEXT (olddecl) != DECL_CONTEXT (newdecl)
2954 	  && ! decls_match (olddecl, newdecl))
2955 	return G_("%qD conflicts with used function");
2956 
2957       /* We'll complain about linkage mismatches in
2958 	 warn_extern_redeclared_static.  */
2959 
2960       /* Defining the same name twice is no good.  */
2961       if (decl_defined_p (olddecl)
2962 	  && decl_defined_p (newdecl))
2963 	{
2964 	  if (DECL_NAME (olddecl) == NULL_TREE)
2965 	    return G_("%q#D not declared in class");
2966 	  else if (!GNU_INLINE_P (olddecl)
2967 		   || GNU_INLINE_P (newdecl))
2968 	    return G_("redefinition of %q#D");
2969 	}
2970 
2971       if (DECL_DECLARED_INLINE_P (olddecl) && DECL_DECLARED_INLINE_P (newdecl))
2972 	{
2973 	  bool olda = GNU_INLINE_P (olddecl);
2974 	  bool newa = GNU_INLINE_P (newdecl);
2975 
2976 	  if (olda != newa)
2977 	    {
2978 	      if (newa)
2979 		return G_("%q+D redeclared inline with "
2980 			  "%<gnu_inline%> attribute");
2981 	      else
2982 		return G_("%q+D redeclared inline without "
2983 			  "%<gnu_inline%> attribute");
2984 	    }
2985 	}
2986 
2987       /* [class.compare.default]: A definition of a comparison operator as
2988 	 defaulted that appears in a class shall be the first declaration of
2989 	 that function.  */
2990       special_function_kind sfk = special_function_p (olddecl);
2991       if (sfk == sfk_comparison && DECL_DEFAULTED_FN (newdecl))
2992 	return G_("comparison operator %q+D defaulted after "
2993 		  "its first declaration");
2994 
2995       check_abi_tag_redeclaration
2996 	(olddecl, lookup_attribute ("abi_tag", DECL_ATTRIBUTES (olddecl)),
2997 	 lookup_attribute ("abi_tag", DECL_ATTRIBUTES (newdecl)));
2998 
2999       return NULL;
3000     }
3001   else if (TREE_CODE (newdecl) == TEMPLATE_DECL)
3002     {
3003       tree nt, ot;
3004 
3005       if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) == CONCEPT_DECL)
3006         return G_("redefinition of %q#D");
3007 
3008       if (TREE_CODE (DECL_TEMPLATE_RESULT (newdecl)) != FUNCTION_DECL)
3009 	return redeclaration_error_message (DECL_TEMPLATE_RESULT (newdecl),
3010 					    DECL_TEMPLATE_RESULT (olddecl));
3011 
3012       if (DECL_TEMPLATE_RESULT (newdecl) == DECL_TEMPLATE_RESULT (olddecl))
3013 	return NULL;
3014 
3015       nt = DECL_TEMPLATE_RESULT (newdecl);
3016       if (DECL_TEMPLATE_INFO (nt))
3017 	nt = DECL_TEMPLATE_RESULT (template_for_substitution (nt));
3018       ot = DECL_TEMPLATE_RESULT (olddecl);
3019       if (DECL_TEMPLATE_INFO (ot))
3020 	ot = DECL_TEMPLATE_RESULT (template_for_substitution (ot));
3021       if (DECL_INITIAL (nt) && DECL_INITIAL (ot)
3022 	  && (!GNU_INLINE_P (ot) || GNU_INLINE_P (nt)))
3023 	return G_("redefinition of %q#D");
3024 
3025       if (DECL_DECLARED_INLINE_P (ot) && DECL_DECLARED_INLINE_P (nt))
3026 	{
3027 	  bool olda = GNU_INLINE_P (ot);
3028 	  bool newa = GNU_INLINE_P (nt);
3029 
3030 	  if (olda != newa)
3031 	    {
3032 	      if (newa)
3033 		return G_("%q+D redeclared inline with "
3034 			  "%<gnu_inline%> attribute");
3035 	      else
3036 		return G_("%q+D redeclared inline without "
3037 		     	  "%<gnu_inline%> attribute");
3038 	    }
3039 	}
3040 
3041       /* Core issue #226 (C++0x):
3042 
3043            If a friend function template declaration specifies a
3044            default template-argument, that declaration shall be a
3045            definition and shall be the only declaration of the
3046            function template in the translation unit.  */
3047       if ((cxx_dialect != cxx98)
3048           && TREE_CODE (ot) == FUNCTION_DECL && DECL_FRIEND_P (ot)
3049           && !check_default_tmpl_args (nt, DECL_TEMPLATE_PARMS (newdecl),
3050                                        /*is_primary=*/true,
3051 				       /*is_partial=*/false,
3052                                        /*is_friend_decl=*/2))
3053         return G_("redeclaration of friend %q#D "
3054 	 	  "may not have default template arguments");
3055 
3056       return NULL;
3057     }
3058   else if (VAR_P (newdecl)
3059 	   && CP_DECL_THREAD_LOCAL_P (newdecl) != CP_DECL_THREAD_LOCAL_P (olddecl)
3060 	   && (! DECL_LANG_SPECIFIC (olddecl)
3061 	       || ! CP_DECL_THREADPRIVATE_P (olddecl)
3062 	       || CP_DECL_THREAD_LOCAL_P (newdecl)))
3063     {
3064       /* Only variables can be thread-local, and all declarations must
3065 	 agree on this property.  */
3066       if (CP_DECL_THREAD_LOCAL_P (newdecl))
3067 	return G_("thread-local declaration of %q#D follows "
3068 	          "non-thread-local declaration");
3069       else
3070 	return G_("non-thread-local declaration of %q#D follows "
3071 	          "thread-local declaration");
3072     }
3073   else if (toplevel_bindings_p () || DECL_NAMESPACE_SCOPE_P (newdecl))
3074     {
3075       /* The objects have been declared at namespace scope.  If either
3076 	 is a member of an anonymous union, then this is an invalid
3077 	 redeclaration.  For example:
3078 
3079 	   int i;
3080 	   union { int i; };
3081 
3082 	   is invalid.  */
3083       if ((VAR_P (newdecl) && DECL_ANON_UNION_VAR_P (newdecl))
3084 	  || (VAR_P (olddecl) && DECL_ANON_UNION_VAR_P (olddecl)))
3085 	return G_("redeclaration of %q#D");
3086       /* If at least one declaration is a reference, there is no
3087 	 conflict.  For example:
3088 
3089 	   int i = 3;
3090 	   extern int i;
3091 
3092 	 is valid.  */
3093       if (DECL_EXTERNAL (newdecl) || DECL_EXTERNAL (olddecl))
3094 	return NULL;
3095 
3096       /* Static data member declared outside a class definition
3097 	 if the variable is defined within the class with constexpr
3098 	 specifier is declaration rather than definition (and
3099 	 deprecated).  */
3100       if (cxx_dialect >= cxx17
3101 	  && VAR_P (olddecl)
3102 	  && DECL_CLASS_SCOPE_P (olddecl)
3103 	  && DECL_DECLARED_CONSTEXPR_P (olddecl)
3104 	  && !DECL_INITIAL (newdecl))
3105 	{
3106 	  DECL_EXTERNAL (newdecl) = 1;
3107 	  /* For now, only warn with explicit -Wdeprecated.  */
3108 	  if (global_options_set.x_warn_deprecated)
3109 	    {
3110 	      auto_diagnostic_group d;
3111 	      if (warning_at (DECL_SOURCE_LOCATION (newdecl), OPT_Wdeprecated,
3112 				"redundant redeclaration of %<constexpr%> "
3113 				"static data member %qD", newdecl))
3114 		inform (DECL_SOURCE_LOCATION (olddecl),
3115 			  "previous declaration of %qD", olddecl);
3116 	    }
3117 	  return NULL;
3118 	}
3119 
3120       /* Reject two definitions.  */
3121       return G_("redefinition of %q#D");
3122     }
3123   else
3124     {
3125       /* Objects declared with block scope:  */
3126       /* Reject two definitions, and reject a definition
3127 	 together with an external reference.  */
3128       if (!(DECL_EXTERNAL (newdecl) && DECL_EXTERNAL (olddecl)))
3129 	return G_("redeclaration of %q#D");
3130       return NULL;
3131     }
3132 }
3133 
3134 
3135 /* Hash and equality functions for the named_label table.  */
3136 
3137 hashval_t
hash(const value_type entry)3138 named_label_hash::hash (const value_type entry)
3139 {
3140   return IDENTIFIER_HASH_VALUE (entry->name);
3141 }
3142 
3143 bool
equal(const value_type entry,compare_type name)3144 named_label_hash::equal (const value_type entry, compare_type name)
3145 {
3146   return name == entry->name;
3147 }
3148 
3149 /* Look for a label named ID in the current function.  If one cannot
3150    be found, create one.  Return the named_label_entry, or NULL on
3151    failure.  */
3152 
3153 static named_label_entry *
lookup_label_1(tree id,bool making_local_p)3154 lookup_label_1 (tree id, bool making_local_p)
3155 {
3156   /* You can't use labels at global scope.  */
3157   if (current_function_decl == NULL_TREE)
3158     {
3159       error ("label %qE referenced outside of any function", id);
3160       return NULL;
3161     }
3162 
3163   if (!named_labels)
3164     named_labels = hash_table<named_label_hash>::create_ggc (13);
3165 
3166   hashval_t hash = IDENTIFIER_HASH_VALUE (id);
3167   named_label_entry **slot
3168     = named_labels->find_slot_with_hash (id, hash, INSERT);
3169   named_label_entry *old = *slot;
3170 
3171   if (old && old->label_decl)
3172     {
3173       if (!making_local_p)
3174 	return old;
3175 
3176       if (old->binding_level == current_binding_level)
3177 	{
3178 	  error ("local label %qE conflicts with existing label", id);
3179 	  inform (DECL_SOURCE_LOCATION (old->label_decl), "previous label");
3180 	  return NULL;
3181 	}
3182     }
3183 
3184   /* We are making a new decl, create or reuse the named_label_entry  */
3185   named_label_entry *ent = NULL;
3186   if (old && !old->label_decl)
3187     ent = old;
3188   else
3189     {
3190       ent = ggc_cleared_alloc<named_label_entry> ();
3191       ent->name = id;
3192       ent->outer = old;
3193       *slot = ent;
3194     }
3195 
3196   /* Now create the LABEL_DECL.  */
3197   tree decl = build_decl (input_location, LABEL_DECL, id, void_type_node);
3198 
3199   DECL_CONTEXT (decl) = current_function_decl;
3200   SET_DECL_MODE (decl, VOIDmode);
3201   if (making_local_p)
3202     {
3203       C_DECLARED_LABEL_FLAG (decl) = true;
3204       DECL_CHAIN (decl) = current_binding_level->names;
3205       current_binding_level->names = decl;
3206     }
3207 
3208   ent->label_decl = decl;
3209 
3210   return ent;
3211 }
3212 
3213 /* Wrapper for lookup_label_1.  */
3214 
3215 tree
lookup_label(tree id)3216 lookup_label (tree id)
3217 {
3218   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
3219   named_label_entry *ent = lookup_label_1 (id, false);
3220   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
3221   return ent ? ent->label_decl : NULL_TREE;
3222 }
3223 
3224 tree
declare_local_label(tree id)3225 declare_local_label (tree id)
3226 {
3227   bool subtime = timevar_cond_start (TV_NAME_LOOKUP);
3228   named_label_entry *ent = lookup_label_1 (id, true);
3229   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
3230   return ent ? ent->label_decl : NULL_TREE;
3231 }
3232 
3233 /* Returns nonzero if it is ill-formed to jump past the declaration of
3234    DECL.  Returns 2 if it's also a real problem.  */
3235 
3236 static int
decl_jump_unsafe(tree decl)3237 decl_jump_unsafe (tree decl)
3238 {
3239   /* [stmt.dcl]/3: A program that jumps from a point where a local variable
3240      with automatic storage duration is not in scope to a point where it is
3241      in scope is ill-formed unless the variable has scalar type, class type
3242      with a trivial default constructor and a trivial destructor, a
3243      cv-qualified version of one of these types, or an array of one of the
3244      preceding types and is declared without an initializer (8.5).  */
3245   tree type = TREE_TYPE (decl);
3246 
3247   if (!VAR_P (decl) || TREE_STATIC (decl)
3248       || type == error_mark_node)
3249     return 0;
3250 
3251   if (DECL_NONTRIVIALLY_INITIALIZED_P (decl)
3252       || variably_modified_type_p (type, NULL_TREE))
3253     return 2;
3254 
3255   if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
3256     return 1;
3257 
3258   return 0;
3259 }
3260 
3261 /* A subroutine of check_previous_goto_1 and check_goto to identify a branch
3262    to the user.  */
3263 
3264 static bool
identify_goto(tree decl,location_t loc,const location_t * locus,diagnostic_t diag_kind)3265 identify_goto (tree decl, location_t loc, const location_t *locus,
3266 	       diagnostic_t diag_kind)
3267 {
3268   bool complained
3269     = emit_diagnostic (diag_kind, loc, 0,
3270 		       decl ? N_("jump to label %qD")
3271 		       : N_("jump to case label"), decl);
3272   if (complained && locus)
3273     inform (*locus, "  from here");
3274   return complained;
3275 }
3276 
3277 /* Check that a single previously seen jump to a newly defined label
3278    is OK.  DECL is the LABEL_DECL or 0; LEVEL is the binding_level for
3279    the jump context; NAMES are the names in scope in LEVEL at the jump
3280    context; LOCUS is the source position of the jump or 0.  Returns
3281    true if all is well.  */
3282 
3283 static bool
check_previous_goto_1(tree decl,cp_binding_level * level,tree names,bool exited_omp,const location_t * locus)3284 check_previous_goto_1 (tree decl, cp_binding_level* level, tree names,
3285 		       bool exited_omp, const location_t *locus)
3286 {
3287   cp_binding_level *b;
3288   bool complained = false;
3289   int identified = 0;
3290   bool saw_eh = false, saw_omp = false, saw_tm = false, saw_cxif = false;
3291 
3292   if (exited_omp)
3293     {
3294       complained = identify_goto (decl, input_location, locus, DK_ERROR);
3295       if (complained)
3296 	inform (input_location, "  exits OpenMP structured block");
3297       saw_omp = true;
3298       identified = 2;
3299     }
3300 
3301   for (b = current_binding_level; b ; b = b->level_chain)
3302     {
3303       tree new_decls, old_decls = (b == level ? names : NULL_TREE);
3304 
3305       for (new_decls = b->names; new_decls != old_decls;
3306 	   new_decls = (DECL_P (new_decls) ? DECL_CHAIN (new_decls)
3307 			: TREE_CHAIN (new_decls)))
3308 	{
3309 	  int problem = decl_jump_unsafe (new_decls);
3310 	  if (! problem)
3311 	    continue;
3312 
3313 	  if (!identified)
3314 	    {
3315 	      complained = identify_goto (decl, input_location, locus,
3316 					  problem > 1
3317 					  ? DK_ERROR : DK_PERMERROR);
3318 	      identified = 1;
3319 	    }
3320 	  if (complained)
3321 	    {
3322 	      if (problem > 1)
3323 		inform (DECL_SOURCE_LOCATION (new_decls),
3324 			"  crosses initialization of %q#D", new_decls);
3325 	      else
3326 		inform (DECL_SOURCE_LOCATION (new_decls),
3327 			"  enters scope of %q#D, which has "
3328 			"non-trivial destructor", new_decls);
3329 	    }
3330 	}
3331 
3332       if (b == level)
3333 	break;
3334 
3335       const char *inf = NULL;
3336       location_t loc = input_location;
3337       switch (b->kind)
3338 	{
3339 	case sk_try:
3340 	  if (!saw_eh)
3341 	    inf = G_("  enters %<try%> block");
3342 	  saw_eh = true;
3343 	  break;
3344 
3345 	case sk_catch:
3346 	  if (!saw_eh)
3347 	    inf = G_("  enters %<catch%> block");
3348 	  saw_eh = true;
3349 	  break;
3350 
3351 	case sk_omp:
3352 	  if (!saw_omp)
3353 	    inf = G_("  enters OpenMP structured block");
3354 	  saw_omp = true;
3355 	  break;
3356 
3357 	case sk_transaction:
3358 	  if (!saw_tm)
3359 	    inf = G_("  enters synchronized or atomic statement");
3360 	  saw_tm = true;
3361 	  break;
3362 
3363 	case sk_block:
3364 	  if (!saw_cxif && level_for_constexpr_if (b->level_chain))
3365 	    {
3366 	      inf = G_("  enters %<constexpr if%> statement");
3367 	      loc = EXPR_LOCATION (b->level_chain->this_entity);
3368 	      saw_cxif = true;
3369 	    }
3370 	  break;
3371 
3372 	default:
3373 	  break;
3374 	}
3375 
3376       if (inf)
3377 	{
3378 	  if (identified < 2)
3379 	    complained = identify_goto (decl, input_location, locus, DK_ERROR);
3380 	  identified = 2;
3381 	  if (complained)
3382 	    inform (loc, inf);
3383 	}
3384     }
3385 
3386   return !identified;
3387 }
3388 
3389 static void
check_previous_goto(tree decl,struct named_label_use_entry * use)3390 check_previous_goto (tree decl, struct named_label_use_entry *use)
3391 {
3392   check_previous_goto_1 (decl, use->binding_level,
3393 			 use->names_in_scope, use->in_omp_scope,
3394 			 &use->o_goto_locus);
3395 }
3396 
3397 static bool
check_switch_goto(cp_binding_level * level)3398 check_switch_goto (cp_binding_level* level)
3399 {
3400   return check_previous_goto_1 (NULL_TREE, level, level->names, false, NULL);
3401 }
3402 
3403 /* Check that a new jump to a label DECL is OK.  Called by
3404    finish_goto_stmt.  */
3405 
3406 void
check_goto(tree decl)3407 check_goto (tree decl)
3408 {
3409   /* We can't know where a computed goto is jumping.
3410      So we assume that it's OK.  */
3411   if (TREE_CODE (decl) != LABEL_DECL)
3412     return;
3413 
3414   /* We didn't record any information about this label when we created it,
3415      and there's not much point since it's trivial to analyze as a return.  */
3416   if (decl == cdtor_label)
3417     return;
3418 
3419   hashval_t hash = IDENTIFIER_HASH_VALUE (DECL_NAME (decl));
3420   named_label_entry **slot
3421     = named_labels->find_slot_with_hash (DECL_NAME (decl), hash, NO_INSERT);
3422   named_label_entry *ent = *slot;
3423 
3424   /* If the label hasn't been defined yet, defer checking.  */
3425   if (! DECL_INITIAL (decl))
3426     {
3427       /* Don't bother creating another use if the last goto had the
3428 	 same data, and will therefore create the same set of errors.  */
3429       if (ent->uses
3430 	  && ent->uses->names_in_scope == current_binding_level->names)
3431 	return;
3432 
3433       named_label_use_entry *new_use
3434 	= ggc_alloc<named_label_use_entry> ();
3435       new_use->binding_level = current_binding_level;
3436       new_use->names_in_scope = current_binding_level->names;
3437       new_use->o_goto_locus = input_location;
3438       new_use->in_omp_scope = false;
3439 
3440       new_use->next = ent->uses;
3441       ent->uses = new_use;
3442       return;
3443     }
3444 
3445   bool saw_catch = false, complained = false;
3446   int identified = 0;
3447   tree bad;
3448   unsigned ix;
3449 
3450   if (ent->in_try_scope || ent->in_catch_scope || ent->in_transaction_scope
3451       || ent->in_constexpr_if
3452       || ent->in_omp_scope || !vec_safe_is_empty (ent->bad_decls))
3453     {
3454       diagnostic_t diag_kind = DK_PERMERROR;
3455       if (ent->in_try_scope || ent->in_catch_scope || ent->in_constexpr_if
3456 	  || ent->in_transaction_scope || ent->in_omp_scope)
3457 	diag_kind = DK_ERROR;
3458       complained = identify_goto (decl, DECL_SOURCE_LOCATION (decl),
3459 				  &input_location, diag_kind);
3460       identified = 1 + (diag_kind == DK_ERROR);
3461     }
3462 
3463   FOR_EACH_VEC_SAFE_ELT (ent->bad_decls, ix, bad)
3464     {
3465       int u = decl_jump_unsafe (bad);
3466 
3467       if (u > 1 && DECL_ARTIFICIAL (bad))
3468 	{
3469 	  /* Can't skip init of __exception_info.  */
3470 	  if (identified == 1)
3471 	    {
3472 	      complained = identify_goto (decl, DECL_SOURCE_LOCATION (decl),
3473 					  &input_location, DK_ERROR);
3474 	      identified = 2;
3475 	    }
3476 	  if (complained)
3477 	    inform (DECL_SOURCE_LOCATION (bad), "  enters %<catch%> block");
3478 	  saw_catch = true;
3479 	}
3480       else if (complained)
3481 	{
3482 	  if (u > 1)
3483 	    inform (DECL_SOURCE_LOCATION (bad),
3484 		    "  skips initialization of %q#D", bad);
3485 	  else
3486 	    inform (DECL_SOURCE_LOCATION (bad),
3487 		    "  enters scope of %q#D which has "
3488 		    "non-trivial destructor", bad);
3489 	}
3490     }
3491 
3492   if (complained)
3493     {
3494       if (ent->in_try_scope)
3495 	inform (input_location, "  enters %<try%> block");
3496       else if (ent->in_catch_scope && !saw_catch)
3497 	inform (input_location, "  enters %<catch%> block");
3498       else if (ent->in_transaction_scope)
3499 	inform (input_location, "  enters synchronized or atomic statement");
3500       else if (ent->in_constexpr_if)
3501 	inform (input_location, "  enters %<constexpr if%> statement");
3502     }
3503 
3504   if (ent->in_omp_scope)
3505     {
3506       if (complained)
3507 	inform (input_location, "  enters OpenMP structured block");
3508     }
3509   else if (flag_openmp)
3510     for (cp_binding_level *b = current_binding_level; b ; b = b->level_chain)
3511       {
3512 	if (b == ent->binding_level)
3513 	  break;
3514 	if (b->kind == sk_omp)
3515 	  {
3516 	    if (identified < 2)
3517 	      {
3518 		complained = identify_goto (decl,
3519 					    DECL_SOURCE_LOCATION (decl),
3520 					    &input_location, DK_ERROR);
3521 		identified = 2;
3522 	      }
3523 	    if (complained)
3524 	      inform (input_location, "  exits OpenMP structured block");
3525 	    break;
3526 	  }
3527       }
3528 }
3529 
3530 /* Check that a return is ok wrt OpenMP structured blocks.
3531    Called by finish_return_stmt.  Returns true if all is well.  */
3532 
3533 bool
check_omp_return(void)3534 check_omp_return (void)
3535 {
3536   for (cp_binding_level *b = current_binding_level; b ; b = b->level_chain)
3537     if (b->kind == sk_omp)
3538       {
3539 	error ("invalid exit from OpenMP structured block");
3540 	return false;
3541       }
3542     else if (b->kind == sk_function_parms)
3543       break;
3544   return true;
3545 }
3546 
3547 /* Define a label, specifying the location in the source file.
3548    Return the LABEL_DECL node for the label.  */
3549 
3550 static tree
define_label_1(location_t location,tree name)3551 define_label_1 (location_t location, tree name)
3552 {
3553   /* After labels, make any new cleanups in the function go into their
3554      own new (temporary) binding contour.  */
3555   for (cp_binding_level *p = current_binding_level;
3556        p->kind != sk_function_parms;
3557        p = p->level_chain)
3558     p->more_cleanups_ok = 0;
3559 
3560   named_label_entry *ent = lookup_label_1 (name, false);
3561   tree decl = ent->label_decl;
3562 
3563   if (DECL_INITIAL (decl) != NULL_TREE)
3564     {
3565       error ("duplicate label %qD", decl);
3566       return error_mark_node;
3567     }
3568   else
3569     {
3570       /* Mark label as having been defined.  */
3571       DECL_INITIAL (decl) = error_mark_node;
3572       /* Say where in the source.  */
3573       DECL_SOURCE_LOCATION (decl) = location;
3574 
3575       ent->binding_level = current_binding_level;
3576       ent->names_in_scope = current_binding_level->names;
3577 
3578       for (named_label_use_entry *use = ent->uses; use; use = use->next)
3579 	check_previous_goto (decl, use);
3580       ent->uses = NULL;
3581     }
3582 
3583   return decl;
3584 }
3585 
3586 /* Wrapper for define_label_1.  */
3587 
3588 tree
define_label(location_t location,tree name)3589 define_label (location_t location, tree name)
3590 {
3591   bool running = timevar_cond_start (TV_NAME_LOOKUP);
3592   tree ret = define_label_1 (location, name);
3593   timevar_cond_stop (TV_NAME_LOOKUP, running);
3594   return ret;
3595 }
3596 
3597 
3598 struct cp_switch
3599 {
3600   cp_binding_level *level;
3601   struct cp_switch *next;
3602   /* The SWITCH_STMT being built.  */
3603   tree switch_stmt;
3604   /* A splay-tree mapping the low element of a case range to the high
3605      element, or NULL_TREE if there is no high element.  Used to
3606      determine whether or not a new case label duplicates an old case
3607      label.  We need a tree, rather than simply a hash table, because
3608      of the GNU case range extension.  */
3609   splay_tree cases;
3610   /* Remember whether a default: case label has been seen.  */
3611   bool has_default_p;
3612   /* Remember whether a BREAK_STMT has been seen in this SWITCH_STMT.  */
3613   bool break_stmt_seen_p;
3614   /* Set if inside of {FOR,DO,WHILE}_BODY nested inside of a switch,
3615      where BREAK_STMT doesn't belong to the SWITCH_STMT.  */
3616   bool in_loop_body_p;
3617 };
3618 
3619 /* A stack of the currently active switch statements.  The innermost
3620    switch statement is on the top of the stack.  There is no need to
3621    mark the stack for garbage collection because it is only active
3622    during the processing of the body of a function, and we never
3623    collect at that point.  */
3624 
3625 static struct cp_switch *switch_stack;
3626 
3627 /* Called right after a switch-statement condition is parsed.
3628    SWITCH_STMT is the switch statement being parsed.  */
3629 
3630 void
push_switch(tree switch_stmt)3631 push_switch (tree switch_stmt)
3632 {
3633   struct cp_switch *p = XNEW (struct cp_switch);
3634   p->level = current_binding_level;
3635   p->next = switch_stack;
3636   p->switch_stmt = switch_stmt;
3637   p->cases = splay_tree_new (case_compare, NULL, NULL);
3638   p->has_default_p = false;
3639   p->break_stmt_seen_p = false;
3640   p->in_loop_body_p = false;
3641   switch_stack = p;
3642 }
3643 
3644 void
pop_switch(void)3645 pop_switch (void)
3646 {
3647   struct cp_switch *cs = switch_stack;
3648 
3649   /* Emit warnings as needed.  */
3650   location_t switch_location = cp_expr_loc_or_input_loc (cs->switch_stmt);
3651   tree cond = SWITCH_STMT_COND (cs->switch_stmt);
3652   const bool bool_cond_p
3653     = (SWITCH_STMT_TYPE (cs->switch_stmt)
3654        && TREE_CODE (SWITCH_STMT_TYPE (cs->switch_stmt)) == BOOLEAN_TYPE);
3655   if (!processing_template_decl)
3656     c_do_switch_warnings (cs->cases, switch_location,
3657 			  SWITCH_STMT_TYPE (cs->switch_stmt), cond,
3658 			  bool_cond_p);
3659 
3660   /* For the benefit of block_may_fallthru remember if the switch body
3661      case labels cover all possible values and if there are break; stmts.  */
3662   if (cs->has_default_p
3663       || (!processing_template_decl
3664 	  && c_switch_covers_all_cases_p (cs->cases,
3665 					  SWITCH_STMT_TYPE (cs->switch_stmt))))
3666     SWITCH_STMT_ALL_CASES_P (cs->switch_stmt) = 1;
3667   if (!cs->break_stmt_seen_p)
3668     SWITCH_STMT_NO_BREAK_P (cs->switch_stmt) = 1;
3669   /* Now that we're done with the switch warnings, set the switch type
3670      to the type of the condition if the index type was of scoped enum type.
3671      (Such types don't participate in the integer promotions.)  We do this
3672      because of bit-fields whose declared type is a scoped enum type:
3673      gimplification will use the lowered index type, but convert the
3674      case values to SWITCH_STMT_TYPE, which would have been the declared type
3675      and verify_gimple_switch doesn't accept that.  */
3676   if (is_bitfield_expr_with_lowered_type (cond))
3677     SWITCH_STMT_TYPE (cs->switch_stmt) = TREE_TYPE (cond);
3678   gcc_assert (!cs->in_loop_body_p);
3679   splay_tree_delete (cs->cases);
3680   switch_stack = switch_stack->next;
3681   free (cs);
3682 }
3683 
3684 /* Note that a BREAK_STMT is about to be added.  If it is inside of
3685    a SWITCH_STMT and not inside of a loop body inside of it, note
3686    in switch_stack we've seen a BREAK_STMT.  */
3687 
3688 void
note_break_stmt(void)3689 note_break_stmt (void)
3690 {
3691   if (switch_stack && !switch_stack->in_loop_body_p)
3692     switch_stack->break_stmt_seen_p = true;
3693 }
3694 
3695 /* Note the start of processing of an iteration statement's body.
3696    The note_break_stmt function will do nothing while processing it.
3697    Return a flag that should be passed to note_iteration_stmt_body_end.  */
3698 
3699 bool
note_iteration_stmt_body_start(void)3700 note_iteration_stmt_body_start (void)
3701 {
3702   if (!switch_stack)
3703     return false;
3704   bool ret = switch_stack->in_loop_body_p;
3705   switch_stack->in_loop_body_p = true;
3706   return ret;
3707 }
3708 
3709 /* Note the end of processing of an iteration statement's body.  */
3710 
3711 void
note_iteration_stmt_body_end(bool prev)3712 note_iteration_stmt_body_end (bool prev)
3713 {
3714   if (switch_stack)
3715     switch_stack->in_loop_body_p = prev;
3716 }
3717 
3718 /* Convert a case constant VALUE in a switch to the type TYPE of the switch
3719    condition.  Note that if TYPE and VALUE are already integral we don't
3720    really do the conversion because the language-independent
3721    warning/optimization code will work better that way.  */
3722 
3723 static tree
case_conversion(tree type,tree value)3724 case_conversion (tree type, tree value)
3725 {
3726   if (value == NULL_TREE)
3727     return value;
3728 
3729   value = mark_rvalue_use (value);
3730 
3731   if (INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
3732     type = type_promotes_to (type);
3733 
3734   tree ovalue = value;
3735   /* The constant-expression VALUE shall be a converted constant expression
3736      of the adjusted type of the switch condition, which doesn't allow
3737      narrowing conversions.  */
3738   value = build_converted_constant_expr (type, value, tf_warning_or_error);
3739 
3740   if (cxx_dialect >= cxx11
3741       && (SCOPED_ENUM_P (type)
3742 	  || !INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (TREE_TYPE (ovalue))))
3743     /* Use the converted value.  */;
3744   else
3745     /* The already integral case.  */
3746     value = ovalue;
3747 
3748   return cxx_constant_value (value);
3749 }
3750 
3751 /* Note that we've seen a definition of a case label, and complain if this
3752    is a bad place for one.  */
3753 
3754 tree
finish_case_label(location_t loc,tree low_value,tree high_value)3755 finish_case_label (location_t loc, tree low_value, tree high_value)
3756 {
3757   tree cond, r;
3758   cp_binding_level *p;
3759   tree type;
3760 
3761   if (low_value == NULL_TREE && high_value == NULL_TREE)
3762     switch_stack->has_default_p = true;
3763 
3764   if (processing_template_decl)
3765     {
3766       tree label;
3767 
3768       /* For templates, just add the case label; we'll do semantic
3769 	 analysis at instantiation-time.  */
3770       label = build_decl (loc, LABEL_DECL, NULL_TREE, void_type_node);
3771       return add_stmt (build_case_label (low_value, high_value, label));
3772     }
3773 
3774   /* Find the condition on which this switch statement depends.  */
3775   cond = SWITCH_STMT_COND (switch_stack->switch_stmt);
3776   if (cond && TREE_CODE (cond) == TREE_LIST)
3777     cond = TREE_VALUE (cond);
3778 
3779   if (!check_switch_goto (switch_stack->level))
3780     return error_mark_node;
3781 
3782   type = SWITCH_STMT_TYPE (switch_stack->switch_stmt);
3783   if (type == error_mark_node)
3784     return error_mark_node;
3785 
3786   low_value = case_conversion (type, low_value);
3787   high_value = case_conversion (type, high_value);
3788 
3789   r = c_add_case_label (loc, switch_stack->cases, cond, low_value, high_value);
3790 
3791   /* After labels, make any new cleanups in the function go into their
3792      own new (temporary) binding contour.  */
3793   for (p = current_binding_level;
3794        p->kind != sk_function_parms;
3795        p = p->level_chain)
3796     p->more_cleanups_ok = 0;
3797 
3798   return r;
3799 }
3800 
3801 struct typename_info {
3802   tree scope;
3803   tree name;
3804   tree template_id;
3805   bool enum_p;
3806   bool class_p;
3807 };
3808 
3809 struct typename_hasher : ggc_ptr_hash<tree_node>
3810 {
3811   typedef typename_info *compare_type;
3812 
3813   /* Hash a TYPENAME_TYPE.  */
3814 
3815   static hashval_t
hashtypename_hasher3816   hash (tree t)
3817   {
3818     hashval_t hash;
3819 
3820     hash = (htab_hash_pointer (TYPE_CONTEXT (t))
3821 	    ^ htab_hash_pointer (TYPE_IDENTIFIER (t)));
3822 
3823     return hash;
3824   }
3825 
3826   /* Compare two TYPENAME_TYPEs.  */
3827 
3828   static bool
equaltypename_hasher3829   equal (tree t1, const typename_info *t2)
3830   {
3831     return (TYPE_IDENTIFIER (t1) == t2->name
3832 	    && TYPE_CONTEXT (t1) == t2->scope
3833 	    && TYPENAME_TYPE_FULLNAME (t1) == t2->template_id
3834 	    && TYPENAME_IS_ENUM_P (t1) == t2->enum_p
3835 	    && TYPENAME_IS_CLASS_P (t1) == t2->class_p);
3836   }
3837 };
3838 
3839 /* Build a TYPENAME_TYPE.  If the type is `typename T::t', CONTEXT is
3840    the type of `T', NAME is the IDENTIFIER_NODE for `t'.
3841 
3842    Returns the new TYPENAME_TYPE.  */
3843 
3844 static GTY (()) hash_table<typename_hasher> *typename_htab;
3845 
3846 tree
build_typename_type(tree context,tree name,tree fullname,enum tag_types tag_type)3847 build_typename_type (tree context, tree name, tree fullname,
3848 		     enum tag_types tag_type)
3849 {
3850   tree t;
3851   tree d;
3852   typename_info ti;
3853   tree *e;
3854   hashval_t hash;
3855 
3856   if (typename_htab == NULL)
3857     typename_htab = hash_table<typename_hasher>::create_ggc (61);
3858 
3859   ti.scope = FROB_CONTEXT (context);
3860   ti.name = name;
3861   ti.template_id = fullname;
3862   ti.enum_p = tag_type == enum_type;
3863   ti.class_p = (tag_type == class_type
3864 		|| tag_type == record_type
3865 		|| tag_type == union_type);
3866   hash =  (htab_hash_pointer (ti.scope)
3867 	   ^ htab_hash_pointer (ti.name));
3868 
3869   /* See if we already have this type.  */
3870   e = typename_htab->find_slot_with_hash (&ti, hash, INSERT);
3871   if (*e)
3872     t = *e;
3873   else
3874     {
3875       /* Build the TYPENAME_TYPE.  */
3876       t = cxx_make_type (TYPENAME_TYPE);
3877       TYPE_CONTEXT (t) = ti.scope;
3878       TYPENAME_TYPE_FULLNAME (t) = ti.template_id;
3879       TYPENAME_IS_ENUM_P (t) = ti.enum_p;
3880       TYPENAME_IS_CLASS_P (t) = ti.class_p;
3881 
3882       /* Build the corresponding TYPE_DECL.  */
3883       d = build_decl (input_location, TYPE_DECL, name, t);
3884       TYPE_NAME (TREE_TYPE (d)) = d;
3885       TYPE_STUB_DECL (TREE_TYPE (d)) = d;
3886       DECL_CONTEXT (d) = FROB_CONTEXT (context);
3887       DECL_ARTIFICIAL (d) = 1;
3888 
3889       /* Store it in the hash table.  */
3890       *e = t;
3891 
3892       /* TYPENAME_TYPEs must always be compared structurally, because
3893 	 they may or may not resolve down to another type depending on
3894 	 the currently open classes. */
3895       SET_TYPE_STRUCTURAL_EQUALITY (t);
3896     }
3897 
3898   return t;
3899 }
3900 
3901 /* Resolve `typename CONTEXT::NAME'.  TAG_TYPE indicates the tag
3902    provided to name the type.  Returns an appropriate type, unless an
3903    error occurs, in which case error_mark_node is returned.  If we
3904    locate a non-artificial TYPE_DECL and TF_KEEP_TYPE_DECL is set, we
3905    return that, rather than the _TYPE it corresponds to, in other
3906    cases we look through the type decl.  If TF_ERROR is set, complain
3907    about errors, otherwise be quiet.  */
3908 
3909 tree
make_typename_type(tree context,tree name,enum tag_types tag_type,tsubst_flags_t complain)3910 make_typename_type (tree context, tree name, enum tag_types tag_type,
3911 		    tsubst_flags_t complain)
3912 {
3913   tree fullname;
3914   tree t;
3915   bool want_template;
3916 
3917   if (name == error_mark_node
3918       || context == NULL_TREE
3919       || context == error_mark_node)
3920     return error_mark_node;
3921 
3922   if (TYPE_P (name))
3923     {
3924       if (!(TYPE_LANG_SPECIFIC (name)
3925 	    && (CLASSTYPE_IS_TEMPLATE (name)
3926 		|| CLASSTYPE_USE_TEMPLATE (name))))
3927 	name = TYPE_IDENTIFIER (name);
3928       else
3929 	/* Create a TEMPLATE_ID_EXPR for the type.  */
3930 	name = build_nt (TEMPLATE_ID_EXPR,
3931 			 CLASSTYPE_TI_TEMPLATE (name),
3932 			 CLASSTYPE_TI_ARGS (name));
3933     }
3934   else if (TREE_CODE (name) == TYPE_DECL)
3935     name = DECL_NAME (name);
3936 
3937   fullname = name;
3938 
3939   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
3940     {
3941       name = TREE_OPERAND (name, 0);
3942       if (DECL_TYPE_TEMPLATE_P (name))
3943 	name = TREE_OPERAND (fullname, 0) = DECL_NAME (name);
3944       if (TREE_CODE (name) != IDENTIFIER_NODE)
3945 	{
3946 	  if (complain & tf_error)
3947 	    error ("%qD is not a type", name);
3948 	  return error_mark_node;
3949 	}
3950     }
3951   if (TREE_CODE (name) == TEMPLATE_DECL)
3952     {
3953       if (complain & tf_error)
3954 	error ("%qD used without template arguments", name);
3955       return error_mark_node;
3956     }
3957   gcc_assert (identifier_p (name));
3958   gcc_assert (TYPE_P (context));
3959 
3960   if (TREE_CODE (context) == TYPE_PACK_EXPANSION)
3961     /* This can happen for C++17 variadic using (c++/88986).  */;
3962   else if (!MAYBE_CLASS_TYPE_P (context))
3963     {
3964       if (complain & tf_error)
3965 	error ("%q#T is not a class", context);
3966       return error_mark_node;
3967     }
3968 
3969   /* When the CONTEXT is a dependent type,  NAME could refer to a
3970      dependent base class of CONTEXT.  But look inside it anyway
3971      if CONTEXT is a currently open scope, in case it refers to a
3972      member of the current instantiation or a non-dependent base;
3973      lookup will stop when we hit a dependent base.  */
3974   if (!dependent_scope_p (context))
3975     /* We should only set WANT_TYPE when we're a nested typename type.
3976        Then we can give better diagnostics if we find a non-type.  */
3977     t = lookup_field (context, name, 2, /*want_type=*/true);
3978   else
3979     t = NULL_TREE;
3980 
3981   if ((!t || TREE_CODE (t) == TREE_LIST) && dependent_type_p (context))
3982     return build_typename_type (context, name, fullname, tag_type);
3983 
3984   want_template = TREE_CODE (fullname) == TEMPLATE_ID_EXPR;
3985 
3986   if (!t)
3987     {
3988       if (complain & tf_error)
3989 	{
3990 	  if (!COMPLETE_TYPE_P (context))
3991 	    cxx_incomplete_type_error (NULL_TREE, context);
3992 	  else
3993 	    error (want_template ? G_("no class template named %q#T in %q#T")
3994 		   : G_("no type named %q#T in %q#T"), name, context);
3995 	}
3996       return error_mark_node;
3997     }
3998 
3999   /* Pull out the template from an injected-class-name (or multiple).  */
4000   if (want_template)
4001     t = maybe_get_template_decl_from_type_decl (t);
4002 
4003   if (TREE_CODE (t) == TREE_LIST)
4004     {
4005       if (complain & tf_error)
4006 	{
4007 	  error ("lookup of %qT in %qT is ambiguous", name, context);
4008 	  print_candidates (t);
4009 	}
4010       return error_mark_node;
4011     }
4012 
4013   if (want_template && !DECL_TYPE_TEMPLATE_P (t))
4014     {
4015       if (complain & tf_error)
4016 	error ("%<typename %T::%D%> names %q#T, which is not a class template",
4017 	       context, name, t);
4018       return error_mark_node;
4019     }
4020   if (!want_template && TREE_CODE (t) != TYPE_DECL)
4021     {
4022       if (complain & tf_error)
4023 	error ("%<typename %T::%D%> names %q#T, which is not a type",
4024 	       context, name, t);
4025       return error_mark_node;
4026     }
4027 
4028   if (!perform_or_defer_access_check (TYPE_BINFO (context), t, t, complain))
4029     return error_mark_node;
4030 
4031   /* If we are currently parsing a template and if T is a typedef accessed
4032      through CONTEXT then we need to remember and check access of T at
4033      template instantiation time.  */
4034   add_typedef_to_current_template_for_access_check (t, context, input_location);
4035 
4036   if (want_template)
4037     return lookup_template_class (t, TREE_OPERAND (fullname, 1),
4038 				  NULL_TREE, context,
4039 				  /*entering_scope=*/0,
4040 				  complain | tf_user);
4041 
4042   if (DECL_ARTIFICIAL (t) || !(complain & tf_keep_type_decl))
4043     t = TREE_TYPE (t);
4044 
4045   maybe_record_typedef_use (t);
4046 
4047   return t;
4048 }
4049 
4050 /* Resolve `CONTEXT::template NAME'.  Returns a TEMPLATE_DECL if the name
4051    can be resolved or an UNBOUND_CLASS_TEMPLATE, unless an error occurs,
4052    in which case error_mark_node is returned.
4053 
4054    If PARM_LIST is non-NULL, also make sure that the template parameter
4055    list of TEMPLATE_DECL matches.
4056 
4057    If COMPLAIN zero, don't complain about any errors that occur.  */
4058 
4059 tree
make_unbound_class_template(tree context,tree name,tree parm_list,tsubst_flags_t complain)4060 make_unbound_class_template (tree context, tree name, tree parm_list,
4061 			     tsubst_flags_t complain)
4062 {
4063   tree t;
4064   tree d;
4065 
4066   if (TYPE_P (name))
4067     name = TYPE_IDENTIFIER (name);
4068   else if (DECL_P (name))
4069     name = DECL_NAME (name);
4070   gcc_assert (identifier_p (name));
4071 
4072   if (!dependent_type_p (context)
4073       || currently_open_class (context))
4074     {
4075       tree tmpl = NULL_TREE;
4076 
4077       if (MAYBE_CLASS_TYPE_P (context))
4078 	tmpl = lookup_field (context, name, 0, false);
4079 
4080       if (tmpl && TREE_CODE (tmpl) == TYPE_DECL)
4081 	tmpl = maybe_get_template_decl_from_type_decl (tmpl);
4082 
4083       if (!tmpl || !DECL_TYPE_TEMPLATE_P (tmpl))
4084 	{
4085 	  if (complain & tf_error)
4086 	    error ("no class template named %q#T in %q#T", name, context);
4087 	  return error_mark_node;
4088 	}
4089 
4090       if (parm_list
4091 	  && !comp_template_parms (DECL_TEMPLATE_PARMS (tmpl), parm_list))
4092 	{
4093 	  if (complain & tf_error)
4094 	    {
4095 	      error ("template parameters do not match template %qD", tmpl);
4096 	      inform (DECL_SOURCE_LOCATION (tmpl),
4097 		      "%qD declared here", tmpl);
4098 	    }
4099 	  return error_mark_node;
4100 	}
4101 
4102       if (!perform_or_defer_access_check (TYPE_BINFO (context), tmpl, tmpl,
4103 					  complain))
4104 	return error_mark_node;
4105 
4106       return tmpl;
4107     }
4108 
4109   /* Build the UNBOUND_CLASS_TEMPLATE.  */
4110   t = cxx_make_type (UNBOUND_CLASS_TEMPLATE);
4111   TYPE_CONTEXT (t) = FROB_CONTEXT (context);
4112   TREE_TYPE (t) = NULL_TREE;
4113   SET_TYPE_STRUCTURAL_EQUALITY (t);
4114 
4115   /* Build the corresponding TEMPLATE_DECL.  */
4116   d = build_decl (input_location, TEMPLATE_DECL, name, t);
4117   TYPE_NAME (TREE_TYPE (d)) = d;
4118   TYPE_STUB_DECL (TREE_TYPE (d)) = d;
4119   DECL_CONTEXT (d) = FROB_CONTEXT (context);
4120   DECL_ARTIFICIAL (d) = 1;
4121   DECL_TEMPLATE_PARMS (d) = parm_list;
4122 
4123   return t;
4124 }
4125 
4126 
4127 
4128 /* Push the declarations of builtin types into the global namespace.
4129    RID_INDEX is the index of the builtin type in the array
4130    RID_POINTERS.  NAME is the name used when looking up the builtin
4131    type.  TYPE is the _TYPE node for the builtin type.
4132 
4133    The calls to set_global_binding below should be
4134    eliminated.  Built-in types should not be looked up name; their
4135    names are keywords that the parser can recognize.  However, there
4136    is code in c-common.c that uses identifier_global_value to look up
4137    built-in types by name.  */
4138 
4139 void
record_builtin_type(enum rid rid_index,const char * name,tree type)4140 record_builtin_type (enum rid rid_index,
4141 		     const char* name,
4142 		     tree type)
4143 {
4144   tree decl = NULL_TREE;
4145 
4146   if (name)
4147     {
4148       tree tname = get_identifier (name);
4149       tree tdecl = build_decl (BUILTINS_LOCATION, TYPE_DECL, tname, type);
4150       DECL_ARTIFICIAL (tdecl) = 1;
4151       set_global_binding (tdecl);
4152       decl = tdecl;
4153     }
4154 
4155   if ((int) rid_index < (int) RID_MAX)
4156     if (tree rname = ridpointers[(int) rid_index])
4157       if (!decl || DECL_NAME (decl) != rname)
4158 	{
4159 	  tree rdecl = build_decl (BUILTINS_LOCATION, TYPE_DECL, rname, type);
4160 	  DECL_ARTIFICIAL (rdecl) = 1;
4161 	  set_global_binding (rdecl);
4162 	  if (!decl)
4163 	    decl = rdecl;
4164 	}
4165 
4166   if (decl)
4167     {
4168       if (!TYPE_NAME (type))
4169 	TYPE_NAME (type) = decl;
4170       debug_hooks->type_decl (decl, 0);
4171     }
4172 }
4173 
4174 /* Push a type into the namespace so that the back ends ignore it.  */
4175 
4176 static void
record_unknown_type(tree type,const char * name)4177 record_unknown_type (tree type, const char* name)
4178 {
4179   tree decl = pushdecl (build_decl (UNKNOWN_LOCATION,
4180 				    TYPE_DECL, get_identifier (name), type));
4181   /* Make sure the "unknown type" typedecl gets ignored for debug info.  */
4182   DECL_IGNORED_P (decl) = 1;
4183   TYPE_DECL_SUPPRESS_DEBUG (decl) = 1;
4184   TYPE_SIZE (type) = TYPE_SIZE (void_type_node);
4185   SET_TYPE_ALIGN (type, 1);
4186   TYPE_USER_ALIGN (type) = 0;
4187   SET_TYPE_MODE (type, TYPE_MODE (void_type_node));
4188 }
4189 
4190 /* Create all the predefined identifiers.  */
4191 
4192 static void
initialize_predefined_identifiers(void)4193 initialize_predefined_identifiers (void)
4194 {
4195   struct predefined_identifier
4196   {
4197     const char *name; /* Name.  */
4198     tree *node;  /* Node to store it in.  */
4199     cp_identifier_kind kind;  /* Kind of identifier.  */
4200   };
4201 
4202   /* A table of identifiers to create at startup.  */
4203   static const predefined_identifier predefined_identifiers[] = {
4204     {"C++", &lang_name_cplusplus, cik_normal},
4205     {"C", &lang_name_c, cik_normal},
4206     /* Some of these names have a trailing space so that it is
4207        impossible for them to conflict with names written by users.  */
4208     {"__ct ", &ctor_identifier, cik_ctor},
4209     {"__ct_base ", &base_ctor_identifier, cik_ctor},
4210     {"__ct_comp ", &complete_ctor_identifier, cik_ctor},
4211     {"__dt ", &dtor_identifier, cik_dtor},
4212     {"__dt_base ", &base_dtor_identifier, cik_dtor},
4213     {"__dt_comp ", &complete_dtor_identifier, cik_dtor},
4214     {"__dt_del ", &deleting_dtor_identifier, cik_dtor},
4215     {"__conv_op ", &conv_op_identifier, cik_conv_op},
4216     {"__in_chrg", &in_charge_identifier, cik_normal},
4217     {"this", &this_identifier, cik_normal},
4218     {"__delta", &delta_identifier, cik_normal},
4219     {"__pfn", &pfn_identifier, cik_normal},
4220     {"_vptr", &vptr_identifier, cik_normal},
4221     {"__vtt_parm", &vtt_parm_identifier, cik_normal},
4222     {"::", &global_identifier, cik_normal},
4223       /* The demangler expects anonymous namespaces to be called
4224 	 something starting with '_GLOBAL__N_'.  It no longer needs
4225 	 to be unique to the TU.  */
4226     {"_GLOBAL__N_1", &anon_identifier, cik_normal},
4227     {"auto", &auto_identifier, cik_normal},
4228     {"decltype(auto)", &decltype_auto_identifier, cik_normal},
4229     {"initializer_list", &init_list_identifier, cik_normal},
4230     {"__for_range ", &for_range__identifier, cik_normal},
4231     {"__for_begin ", &for_begin__identifier, cik_normal},
4232     {"__for_end ", &for_end__identifier, cik_normal},
4233     {"__for_range", &for_range_identifier, cik_normal},
4234     {"__for_begin", &for_begin_identifier, cik_normal},
4235     {"__for_end", &for_end_identifier, cik_normal},
4236     {"abi_tag", &abi_tag_identifier, cik_normal},
4237     {"aligned", &aligned_identifier, cik_normal},
4238     {"begin", &begin_identifier, cik_normal},
4239     {"end", &end_identifier, cik_normal},
4240     {"get", &get__identifier, cik_normal},
4241     {"gnu", &gnu_identifier, cik_normal},
4242     {"tuple_element", &tuple_element_identifier, cik_normal},
4243     {"tuple_size", &tuple_size_identifier, cik_normal},
4244     {"type", &type_identifier, cik_normal},
4245     {"value", &value_identifier, cik_normal},
4246     {"_FUN", &fun_identifier, cik_normal},
4247     {"__closure", &closure_identifier, cik_normal},
4248     {"heap uninit", &heap_uninit_identifier, cik_normal},
4249     {"heap ", &heap_identifier, cik_normal},
4250     {"heap deleted", &heap_deleted_identifier, cik_normal},
4251     {NULL, NULL, cik_normal}
4252   };
4253 
4254   for (const predefined_identifier *pid = predefined_identifiers;
4255        pid->name; ++pid)
4256     {
4257       *pid->node = get_identifier (pid->name);
4258       /* Some of these identifiers already have a special kind.  */
4259       if (pid->kind != cik_normal)
4260 	set_identifier_kind (*pid->node, pid->kind);
4261     }
4262 }
4263 
4264 /* Create the predefined scalar types of C,
4265    and some nodes representing standard constants (0, 1, (void *)0).
4266    Initialize the global binding level.
4267    Make definitions for built-in primitive functions.  */
4268 
4269 void
cxx_init_decl_processing(void)4270 cxx_init_decl_processing (void)
4271 {
4272   tree void_ftype;
4273   tree void_ftype_ptr;
4274 
4275   /* Create all the identifiers we need.  */
4276   initialize_predefined_identifiers ();
4277 
4278   /* Create the global variables.  */
4279   push_to_top_level ();
4280 
4281   current_function_decl = NULL_TREE;
4282   current_binding_level = NULL;
4283   /* Enter the global namespace.  */
4284   gcc_assert (global_namespace == NULL_TREE);
4285   global_namespace = build_lang_decl (NAMESPACE_DECL, global_identifier,
4286 				      void_type_node);
4287   TREE_PUBLIC (global_namespace) = 1;
4288   DECL_CONTEXT (global_namespace)
4289     = build_translation_unit_decl (get_identifier (main_input_filename));
4290   /* Remember whether we want the empty class passing ABI change warning
4291      in this TU.  */
4292   TRANSLATION_UNIT_WARN_EMPTY_P (DECL_CONTEXT (global_namespace))
4293     = warn_abi && abi_version_crosses (12);
4294   debug_hooks->register_main_translation_unit
4295     (DECL_CONTEXT (global_namespace));
4296   begin_scope (sk_namespace, global_namespace);
4297   current_namespace = global_namespace;
4298 
4299   if (flag_visibility_ms_compat)
4300     default_visibility = VISIBILITY_HIDDEN;
4301 
4302   /* Initially, C.  */
4303   current_lang_name = lang_name_c;
4304 
4305   /* Create the `std' namespace.  */
4306   push_namespace (get_identifier ("std"));
4307   std_node = current_namespace;
4308   pop_namespace ();
4309 
4310   flag_noexcept_type = (cxx_dialect >= cxx17);
4311 
4312   c_common_nodes_and_builtins ();
4313 
4314   tree bool_ftype = build_function_type_list (boolean_type_node, NULL_TREE);
4315   tree decl
4316     = add_builtin_function ("__builtin_is_constant_evaluated",
4317 			    bool_ftype, CP_BUILT_IN_IS_CONSTANT_EVALUATED,
4318 			    BUILT_IN_FRONTEND, NULL, NULL_TREE);
4319   set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4320 
4321   tree cptr_ftype = build_function_type_list (const_ptr_type_node, NULL_TREE);
4322   decl = add_builtin_function ("__builtin_source_location",
4323 			       cptr_ftype, CP_BUILT_IN_SOURCE_LOCATION,
4324 			       BUILT_IN_FRONTEND, NULL, NULL_TREE);
4325   set_call_expr_flags (decl, ECF_CONST | ECF_NOTHROW | ECF_LEAF);
4326 
4327   integer_two_node = build_int_cst (NULL_TREE, 2);
4328 
4329   /* Guess at the initial static decls size.  */
4330   vec_alloc (static_decls, 500);
4331 
4332   /* ... and keyed classes.  */
4333   vec_alloc (keyed_classes, 100);
4334 
4335   record_builtin_type (RID_BOOL, "bool", boolean_type_node);
4336   truthvalue_type_node = boolean_type_node;
4337   truthvalue_false_node = boolean_false_node;
4338   truthvalue_true_node = boolean_true_node;
4339 
4340   empty_except_spec = build_tree_list (NULL_TREE, NULL_TREE);
4341   noexcept_true_spec = build_tree_list (boolean_true_node, NULL_TREE);
4342   noexcept_false_spec = build_tree_list (boolean_false_node, NULL_TREE);
4343   noexcept_deferred_spec = build_tree_list (make_node (DEFERRED_NOEXCEPT),
4344 					    NULL_TREE);
4345 
4346 #if 0
4347   record_builtin_type (RID_MAX, NULL, string_type_node);
4348 #endif
4349 
4350   delta_type_node = ptrdiff_type_node;
4351   vtable_index_type = ptrdiff_type_node;
4352 
4353   vtt_parm_type = build_pointer_type (const_ptr_type_node);
4354   void_ftype = build_function_type_list (void_type_node, NULL_TREE);
4355   void_ftype_ptr = build_function_type_list (void_type_node,
4356 					     ptr_type_node, NULL_TREE);
4357   void_ftype_ptr
4358     = build_exception_variant (void_ftype_ptr, empty_except_spec);
4359 
4360   /* Create the conversion operator marker.  This operator's DECL_NAME
4361      is in the identifier table, so we can use identifier equality to
4362      find it.  */
4363   conv_op_marker = build_lang_decl (FUNCTION_DECL, conv_op_identifier,
4364 				    void_ftype);
4365 
4366   /* C++ extensions */
4367 
4368   unknown_type_node = make_node (LANG_TYPE);
4369   record_unknown_type (unknown_type_node, "unknown type");
4370 
4371   /* Indirecting an UNKNOWN_TYPE node yields an UNKNOWN_TYPE node.  */
4372   TREE_TYPE (unknown_type_node) = unknown_type_node;
4373 
4374   /* Looking up TYPE_POINTER_TO and TYPE_REFERENCE_TO yield the same
4375      result.  */
4376   TYPE_POINTER_TO (unknown_type_node) = unknown_type_node;
4377   TYPE_REFERENCE_TO (unknown_type_node) = unknown_type_node;
4378 
4379   init_list_type_node = make_node (LANG_TYPE);
4380   record_unknown_type (init_list_type_node, "init list");
4381 
4382   {
4383     /* Make sure we get a unique function type, so we can give
4384        its pointer type a name.  (This wins for gdb.) */
4385     tree vfunc_type = make_node (FUNCTION_TYPE);
4386     TREE_TYPE (vfunc_type) = integer_type_node;
4387     TYPE_ARG_TYPES (vfunc_type) = NULL_TREE;
4388     layout_type (vfunc_type);
4389 
4390     vtable_entry_type = build_pointer_type (vfunc_type);
4391   }
4392   record_builtin_type (RID_MAX, "__vtbl_ptr_type", vtable_entry_type);
4393 
4394   vtbl_type_node
4395     = build_cplus_array_type (vtable_entry_type, NULL_TREE);
4396   layout_type (vtbl_type_node);
4397   vtbl_type_node = cp_build_qualified_type (vtbl_type_node, TYPE_QUAL_CONST);
4398   record_builtin_type (RID_MAX, NULL, vtbl_type_node);
4399   vtbl_ptr_type_node = build_pointer_type (vtable_entry_type);
4400   layout_type (vtbl_ptr_type_node);
4401   record_builtin_type (RID_MAX, NULL, vtbl_ptr_type_node);
4402 
4403   push_namespace (get_identifier ("__cxxabiv1"));
4404   abi_node = current_namespace;
4405   pop_namespace ();
4406 
4407   global_type_node = make_node (LANG_TYPE);
4408   record_unknown_type (global_type_node, "global type");
4409 
4410   any_targ_node = make_node (LANG_TYPE);
4411   record_unknown_type (any_targ_node, "any type");
4412 
4413   /* Now, C++.  */
4414   current_lang_name = lang_name_cplusplus;
4415 
4416   if (aligned_new_threshold > 1
4417       && !pow2p_hwi (aligned_new_threshold))
4418     {
4419       error ("%<-faligned-new=%d%> is not a power of two",
4420 	     aligned_new_threshold);
4421       aligned_new_threshold = 1;
4422     }
4423   if (aligned_new_threshold == -1)
4424     aligned_new_threshold = (cxx_dialect >= cxx17) ? 1 : 0;
4425   if (aligned_new_threshold == 1)
4426     aligned_new_threshold = malloc_alignment () / BITS_PER_UNIT;
4427 
4428   {
4429     tree newattrs, extvisattr;
4430     tree newtype, deltype;
4431     tree ptr_ftype_sizetype;
4432     tree new_eh_spec;
4433 
4434     ptr_ftype_sizetype
4435       = build_function_type_list (ptr_type_node, size_type_node, NULL_TREE);
4436     if (cxx_dialect == cxx98)
4437       {
4438 	tree bad_alloc_id;
4439 	tree bad_alloc_type_node;
4440 	tree bad_alloc_decl;
4441 
4442 	push_nested_namespace (std_node);
4443 	bad_alloc_id = get_identifier ("bad_alloc");
4444 	bad_alloc_type_node = make_class_type (RECORD_TYPE);
4445 	TYPE_CONTEXT (bad_alloc_type_node) = current_namespace;
4446 	bad_alloc_decl
4447 	  = create_implicit_typedef (bad_alloc_id, bad_alloc_type_node);
4448 	DECL_CONTEXT (bad_alloc_decl) = current_namespace;
4449 	pop_nested_namespace (std_node);
4450 
4451 	new_eh_spec
4452 	  = add_exception_specifier (NULL_TREE, bad_alloc_type_node, -1);
4453       }
4454     else
4455       new_eh_spec = noexcept_false_spec;
4456 
4457     /* Ensure attribs.c is initialized.  */
4458     init_attributes ();
4459 
4460     extvisattr = build_tree_list (get_identifier ("externally_visible"),
4461 				  NULL_TREE);
4462     newattrs = tree_cons (get_identifier ("alloc_size"),
4463 			  build_tree_list (NULL_TREE, integer_one_node),
4464 			  extvisattr);
4465     newtype = cp_build_type_attribute_variant (ptr_ftype_sizetype, newattrs);
4466     newtype = build_exception_variant (newtype, new_eh_spec);
4467     deltype = cp_build_type_attribute_variant (void_ftype_ptr, extvisattr);
4468     deltype = build_exception_variant (deltype, empty_except_spec);
4469     tree opnew = push_cp_library_fn (NEW_EXPR, newtype, 0);
4470     DECL_IS_MALLOC (opnew) = 1;
4471     DECL_SET_IS_OPERATOR_NEW (opnew, true);
4472     DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4473     opnew = push_cp_library_fn (VEC_NEW_EXPR, newtype, 0);
4474     DECL_IS_MALLOC (opnew) = 1;
4475     DECL_SET_IS_OPERATOR_NEW (opnew, true);
4476     DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4477     tree opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4478     DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4479     DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4480     opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4481     DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4482     DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4483     if (flag_sized_deallocation)
4484       {
4485 	/* Also push the sized deallocation variants:
4486 	     void operator delete(void*, std::size_t) throw();
4487 	     void operator delete[](void*, std::size_t) throw();  */
4488 	tree void_ftype_ptr_size
4489 	  = build_function_type_list (void_type_node, ptr_type_node,
4490 				      size_type_node, NULL_TREE);
4491 	deltype = cp_build_type_attribute_variant (void_ftype_ptr_size,
4492 						   extvisattr);
4493 	deltype = build_exception_variant (deltype, empty_except_spec);
4494 	opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4495 	DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4496 	DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4497 	opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4498 	DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4499 	DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4500       }
4501 
4502     if (aligned_new_threshold)
4503       {
4504 	push_nested_namespace (std_node);
4505 	tree align_id = get_identifier ("align_val_t");
4506 	align_type_node = start_enum (align_id, NULL_TREE, size_type_node,
4507 				      NULL_TREE, /*scoped*/true, NULL);
4508 	pop_nested_namespace (std_node);
4509 
4510 	/* operator new (size_t, align_val_t); */
4511 	newtype = build_function_type_list (ptr_type_node, size_type_node,
4512 					    align_type_node, NULL_TREE);
4513 	newtype = cp_build_type_attribute_variant (newtype, newattrs);
4514 	newtype = build_exception_variant (newtype, new_eh_spec);
4515 	opnew = push_cp_library_fn (NEW_EXPR, newtype, 0);
4516 	DECL_IS_MALLOC (opnew) = 1;
4517 	DECL_SET_IS_OPERATOR_NEW (opnew, true);
4518 	DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4519 	opnew = push_cp_library_fn (VEC_NEW_EXPR, newtype, 0);
4520 	DECL_IS_MALLOC (opnew) = 1;
4521 	DECL_SET_IS_OPERATOR_NEW (opnew, true);
4522 	DECL_IS_REPLACEABLE_OPERATOR (opnew) = 1;
4523 
4524 	/* operator delete (void *, align_val_t); */
4525 	deltype = build_function_type_list (void_type_node, ptr_type_node,
4526 					    align_type_node, NULL_TREE);
4527 	deltype = cp_build_type_attribute_variant (deltype, extvisattr);
4528 	deltype = build_exception_variant (deltype, empty_except_spec);
4529 	opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4530 	DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4531 	DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4532 	opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4533 	DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4534 	DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4535 
4536 	if (flag_sized_deallocation)
4537 	  {
4538 	    /* operator delete (void *, size_t, align_val_t); */
4539 	    deltype = build_function_type_list (void_type_node, ptr_type_node,
4540 						size_type_node, align_type_node,
4541 						NULL_TREE);
4542 	    deltype = cp_build_type_attribute_variant (deltype, extvisattr);
4543 	    deltype = build_exception_variant (deltype, empty_except_spec);
4544 	    opdel = push_cp_library_fn (DELETE_EXPR, deltype, ECF_NOTHROW);
4545 	    DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4546 	    DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4547 	    opdel = push_cp_library_fn (VEC_DELETE_EXPR, deltype, ECF_NOTHROW);
4548 	    DECL_SET_IS_OPERATOR_DELETE (opdel, true);
4549 	    DECL_IS_REPLACEABLE_OPERATOR (opdel) = 1;
4550 	  }
4551       }
4552 
4553     nullptr_type_node = make_node (NULLPTR_TYPE);
4554     TYPE_SIZE (nullptr_type_node) = bitsize_int (GET_MODE_BITSIZE (ptr_mode));
4555     TYPE_SIZE_UNIT (nullptr_type_node) = size_int (GET_MODE_SIZE (ptr_mode));
4556     TYPE_UNSIGNED (nullptr_type_node) = 1;
4557     TYPE_PRECISION (nullptr_type_node) = GET_MODE_BITSIZE (ptr_mode);
4558     if (abi_version_at_least (9))
4559       SET_TYPE_ALIGN (nullptr_type_node, GET_MODE_ALIGNMENT (ptr_mode));
4560     SET_TYPE_MODE (nullptr_type_node, ptr_mode);
4561     record_builtin_type (RID_MAX, "decltype(nullptr)", nullptr_type_node);
4562     nullptr_node = build_int_cst (nullptr_type_node, 0);
4563   }
4564 
4565   abort_fndecl
4566     = build_library_fn_ptr ("__cxa_pure_virtual", void_ftype,
4567 			    ECF_NORETURN | ECF_NOTHROW | ECF_COLD);
4568 
4569   /* Perform other language dependent initializations.  */
4570   init_class_processing ();
4571   init_rtti_processing ();
4572   init_template_processing ();
4573 
4574   if (flag_exceptions)
4575     init_exception_processing ();
4576 
4577   if (! supports_one_only ())
4578     flag_weak = 0;
4579 
4580   make_fname_decl = cp_make_fname_decl;
4581   start_fname_decls ();
4582 
4583   /* Show we use EH for cleanups.  */
4584   if (flag_exceptions)
4585     using_eh_for_cleanups ();
4586 }
4587 
4588 /* Generate an initializer for a function naming variable from
4589    NAME. NAME may be NULL, to indicate a dependent name.  TYPE_P is
4590    filled in with the type of the init.  */
4591 
4592 tree
cp_fname_init(const char * name,tree * type_p)4593 cp_fname_init (const char* name, tree *type_p)
4594 {
4595   tree domain = NULL_TREE;
4596   tree type;
4597   tree init = NULL_TREE;
4598   size_t length = 0;
4599 
4600   if (name)
4601     {
4602       length = strlen (name);
4603       domain = build_index_type (size_int (length));
4604       init = build_string (length + 1, name);
4605     }
4606 
4607   type = cp_build_qualified_type (char_type_node, TYPE_QUAL_CONST);
4608   type = build_cplus_array_type (type, domain);
4609 
4610   *type_p = type;
4611 
4612   if (init)
4613     TREE_TYPE (init) = type;
4614   else
4615     init = error_mark_node;
4616 
4617   return init;
4618 }
4619 
4620 /* Create the VAR_DECL for __FUNCTION__ etc. ID is the name to give
4621    the decl, LOC is the location to give the decl, NAME is the
4622    initialization string and TYPE_DEP indicates whether NAME depended
4623    on the type of the function. We make use of that to detect
4624    __PRETTY_FUNCTION__ inside a template fn. This is being done lazily
4625    at the point of first use, so we mustn't push the decl now.  */
4626 
4627 static tree
cp_make_fname_decl(location_t loc,tree id,int type_dep)4628 cp_make_fname_decl (location_t loc, tree id, int type_dep)
4629 {
4630   const char * name = NULL;
4631   bool release_name = false;
4632   if (!(type_dep && in_template_function ()))
4633     {
4634       if (current_function_decl == NULL_TREE)
4635 	name = "top level";
4636       else if (type_dep == 1) /* __PRETTY_FUNCTION__ */
4637 	name = cxx_printable_name (current_function_decl, 2);
4638       else if (type_dep == 0) /* __FUNCTION__ */
4639 	{
4640 	  name = fname_as_string (type_dep);
4641 	  release_name = true;
4642 	}
4643       else
4644 	gcc_unreachable ();
4645     }
4646   tree type;
4647   tree init = cp_fname_init (name, &type);
4648   tree decl = build_decl (loc, VAR_DECL, id, type);
4649 
4650   if (release_name)
4651     free (CONST_CAST (char *, name));
4652 
4653   /* As we're using pushdecl_with_scope, we must set the context.  */
4654   DECL_CONTEXT (decl) = current_function_decl;
4655 
4656   TREE_READONLY (decl) = 1;
4657   DECL_ARTIFICIAL (decl) = 1;
4658   DECL_DECLARED_CONSTEXPR_P (decl) = 1;
4659   TREE_STATIC (decl) = 1;
4660 
4661   TREE_USED (decl) = 1;
4662 
4663   if (init)
4664     {
4665       SET_DECL_VALUE_EXPR (decl, init);
4666       DECL_HAS_VALUE_EXPR_P (decl) = 1;
4667       /* For decl_constant_var_p.  */
4668       DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = 1;
4669     }
4670 
4671   if (current_function_decl)
4672     {
4673       DECL_CONTEXT (decl) = current_function_decl;
4674       decl = pushdecl_outermost_localscope (decl);
4675       if (decl != error_mark_node)
4676 	add_decl_expr (decl);
4677     }
4678   else
4679     {
4680       DECL_THIS_STATIC (decl) = true;
4681       pushdecl_top_level_and_finish (decl, NULL_TREE);
4682     }
4683 
4684   return decl;
4685 }
4686 
4687 /* Install DECL as a builtin function at current (global) scope.
4688    Return the new decl (if we found an existing version).  Also
4689    installs it into ::std, if it's not '_*'.  */
4690 
4691 tree
cxx_builtin_function(tree decl)4692 cxx_builtin_function (tree decl)
4693 {
4694   retrofit_lang_decl (decl);
4695 
4696   DECL_ARTIFICIAL (decl) = 1;
4697   SET_DECL_LANGUAGE (decl, lang_c);
4698   /* Runtime library routines are, by definition, available in an
4699      external shared object.  */
4700   DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
4701   DECL_VISIBILITY_SPECIFIED (decl) = 1;
4702 
4703   tree id = DECL_NAME (decl);
4704   const char *name = IDENTIFIER_POINTER (id);
4705   if (name[0] != '_' || name[1] != '_')
4706     /* In the user's namespace, it must be declared before use.  */
4707     DECL_ANTICIPATED (decl) = 1;
4708   else if (IDENTIFIER_LENGTH (id) > strlen ("___chk")
4709 	   && 0 != strncmp (name + 2, "builtin_", strlen ("builtin_"))
4710 	   && 0 == memcmp (name + IDENTIFIER_LENGTH (id) - strlen ("_chk"),
4711 			   "_chk", strlen ("_chk") + 1))
4712     /* Treat __*_chk fortification functions as anticipated as well,
4713        unless they are __builtin_*_chk.  */
4714     DECL_ANTICIPATED (decl) = 1;
4715 
4716   /* All builtins that don't begin with an '_' should additionally
4717      go in the 'std' namespace.  */
4718   if (name[0] != '_')
4719     {
4720       tree std_decl = copy_decl (decl);
4721 
4722       push_nested_namespace (std_node);
4723       DECL_CONTEXT (std_decl) = FROB_CONTEXT (std_node);
4724       pushdecl (std_decl);
4725       pop_nested_namespace (std_node);
4726     }
4727 
4728   DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4729   decl = pushdecl (decl);
4730 
4731   return decl;
4732 }
4733 
4734 /* Like cxx_builtin_function, but guarantee the function is added to the global
4735    scope.  This is to allow function specific options to add new machine
4736    dependent builtins when the target ISA changes via attribute((target(...)))
4737    which saves space on program startup if the program does not use non-generic
4738    ISAs.  */
4739 
4740 tree
cxx_builtin_function_ext_scope(tree decl)4741 cxx_builtin_function_ext_scope (tree decl)
4742 {
4743   push_nested_namespace (global_namespace);
4744   decl = cxx_builtin_function (decl);
4745   pop_nested_namespace (global_namespace);
4746 
4747   return decl;
4748 }
4749 
4750 /* Implement LANG_HOOKS_SIMULATE_BUILTIN_FUNCTION_DECL.  */
4751 
4752 tree
cxx_simulate_builtin_function_decl(tree decl)4753 cxx_simulate_builtin_function_decl (tree decl)
4754 {
4755   retrofit_lang_decl (decl);
4756 
4757   DECL_ARTIFICIAL (decl) = 1;
4758   SET_DECL_LANGUAGE (decl, lang_cplusplus);
4759   DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4760   return pushdecl (decl);
4761 }
4762 
4763 /* Generate a FUNCTION_DECL with the typical flags for a runtime library
4764    function.  Not called directly.  */
4765 
4766 static tree
build_library_fn(tree name,enum tree_code operator_code,tree type,int ecf_flags)4767 build_library_fn (tree name, enum tree_code operator_code, tree type,
4768 		  int ecf_flags)
4769 {
4770   tree fn = build_lang_decl (FUNCTION_DECL, name, type);
4771   DECL_EXTERNAL (fn) = 1;
4772   TREE_PUBLIC (fn) = 1;
4773   DECL_ARTIFICIAL (fn) = 1;
4774   DECL_OVERLOADED_OPERATOR_CODE_RAW (fn)
4775     = OVL_OP_INFO (false, operator_code)->ovl_op_code;
4776   SET_DECL_LANGUAGE (fn, lang_c);
4777   /* Runtime library routines are, by definition, available in an
4778      external shared object.  */
4779   DECL_VISIBILITY (fn) = VISIBILITY_DEFAULT;
4780   DECL_VISIBILITY_SPECIFIED (fn) = 1;
4781   set_call_expr_flags (fn, ecf_flags);
4782   return fn;
4783 }
4784 
4785 /* Returns the _DECL for a library function with C++ linkage.  */
4786 
4787 static tree
build_cp_library_fn(tree name,enum tree_code operator_code,tree type,int ecf_flags)4788 build_cp_library_fn (tree name, enum tree_code operator_code, tree type,
4789 		     int ecf_flags)
4790 {
4791   tree fn = build_library_fn (name, operator_code, type, ecf_flags);
4792   DECL_CONTEXT (fn) = FROB_CONTEXT (current_namespace);
4793   SET_DECL_LANGUAGE (fn, lang_cplusplus);
4794   return fn;
4795 }
4796 
4797 /* Like build_library_fn, but takes a C string instead of an
4798    IDENTIFIER_NODE.  */
4799 
4800 tree
build_library_fn_ptr(const char * name,tree type,int ecf_flags)4801 build_library_fn_ptr (const char* name, tree type, int ecf_flags)
4802 {
4803   return build_library_fn (get_identifier (name), ERROR_MARK, type, ecf_flags);
4804 }
4805 
4806 /* Like build_cp_library_fn, but takes a C string instead of an
4807    IDENTIFIER_NODE.  */
4808 
4809 tree
build_cp_library_fn_ptr(const char * name,tree type,int ecf_flags)4810 build_cp_library_fn_ptr (const char* name, tree type, int ecf_flags)
4811 {
4812   return build_cp_library_fn (get_identifier (name), ERROR_MARK, type,
4813 			      ecf_flags);
4814 }
4815 
4816 /* Like build_library_fn, but also pushes the function so that we will
4817    be able to find it via get_global_binding.  Also, the function
4818    may throw exceptions listed in RAISES.  */
4819 
4820 tree
push_library_fn(tree name,tree type,tree raises,int ecf_flags)4821 push_library_fn (tree name, tree type, tree raises, int ecf_flags)
4822 {
4823   tree fn;
4824 
4825   if (raises)
4826     type = build_exception_variant (type, raises);
4827 
4828   fn = build_library_fn (name, ERROR_MARK, type, ecf_flags);
4829   pushdecl_top_level (fn);
4830   return fn;
4831 }
4832 
4833 /* Like build_cp_library_fn, but also pushes the function so that it
4834    will be found by normal lookup.  */
4835 
4836 static tree
push_cp_library_fn(enum tree_code operator_code,tree type,int ecf_flags)4837 push_cp_library_fn (enum tree_code operator_code, tree type,
4838 		    int ecf_flags)
4839 {
4840   tree fn = build_cp_library_fn (ovl_op_identifier (false, operator_code),
4841 				 operator_code, type, ecf_flags);
4842   pushdecl (fn);
4843   if (flag_tm)
4844     apply_tm_attr (fn, get_identifier ("transaction_safe"));
4845   return fn;
4846 }
4847 
4848 /* Like push_library_fn, but takes a TREE_LIST of parm types rather than
4849    a FUNCTION_TYPE.  */
4850 
4851 tree
push_void_library_fn(tree name,tree parmtypes,int ecf_flags)4852 push_void_library_fn (tree name, tree parmtypes, int ecf_flags)
4853 {
4854   tree type = build_function_type (void_type_node, parmtypes);
4855   return push_library_fn (name, type, NULL_TREE, ecf_flags);
4856 }
4857 
4858 /* Like push_library_fn, but also note that this function throws
4859    and does not return.  Used for __throw_foo and the like.  */
4860 
4861 tree
push_throw_library_fn(tree name,tree type)4862 push_throw_library_fn (tree name, tree type)
4863 {
4864   tree fn = push_library_fn (name, type, NULL_TREE, ECF_NORETURN | ECF_COLD);
4865   return fn;
4866 }
4867 
4868 /* When we call finish_struct for an anonymous union, we create
4869    default copy constructors and such.  But, an anonymous union
4870    shouldn't have such things; this function undoes the damage to the
4871    anonymous union type T.
4872 
4873    (The reason that we create the synthesized methods is that we don't
4874    distinguish `union { int i; }' from `typedef union { int i; } U'.
4875    The first is an anonymous union; the second is just an ordinary
4876    union type.)  */
4877 
4878 void
fixup_anonymous_aggr(tree t)4879 fixup_anonymous_aggr (tree t)
4880 {
4881   /* Wipe out memory of synthesized methods.  */
4882   TYPE_HAS_USER_CONSTRUCTOR (t) = 0;
4883   TYPE_HAS_DEFAULT_CONSTRUCTOR (t) = 0;
4884   TYPE_HAS_COPY_CTOR (t) = 0;
4885   TYPE_HAS_CONST_COPY_CTOR (t) = 0;
4886   TYPE_HAS_COPY_ASSIGN (t) = 0;
4887   TYPE_HAS_CONST_COPY_ASSIGN (t) = 0;
4888 
4889   /* Splice the implicitly generated functions out of TYPE_FIELDS.  */
4890   for (tree probe, *prev_p = &TYPE_FIELDS (t); (probe = *prev_p);)
4891     if (TREE_CODE (probe) == FUNCTION_DECL && DECL_ARTIFICIAL (probe))
4892       *prev_p = DECL_CHAIN (probe);
4893     else
4894       prev_p = &DECL_CHAIN (probe);
4895 
4896   /* Anonymous aggregates cannot have fields with ctors, dtors or complex
4897      assignment operators (because they cannot have these methods themselves).
4898      For anonymous unions this is already checked because they are not allowed
4899      in any union, otherwise we have to check it.  */
4900   if (TREE_CODE (t) != UNION_TYPE)
4901     {
4902       tree field, type;
4903 
4904       for (field = TYPE_FIELDS (t); field; field = DECL_CHAIN (field))
4905 	if (TREE_CODE (field) == FIELD_DECL)
4906 	  {
4907 	    type = TREE_TYPE (field);
4908 	    if (CLASS_TYPE_P (type))
4909 	      {
4910 		if (TYPE_NEEDS_CONSTRUCTING (type))
4911 		  error ("member %q+#D with constructor not allowed "
4912 			 "in anonymous aggregate", field);
4913 		if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
4914 		  error ("member %q+#D with destructor not allowed "
4915 			 "in anonymous aggregate", field);
4916 		if (TYPE_HAS_COMPLEX_COPY_ASSIGN (type))
4917 		  error ("member %q+#D with copy assignment operator "
4918 			 "not allowed in anonymous aggregate", field);
4919 	      }
4920 	  }
4921     }
4922 }
4923 
4924 /* Warn for an attribute located at LOCATION that appertains to the
4925    class type CLASS_TYPE that has not been properly placed after its
4926    class-key, in it class-specifier.  */
4927 
4928 void
warn_misplaced_attr_for_class_type(location_t location,tree class_type)4929 warn_misplaced_attr_for_class_type (location_t location,
4930 				    tree class_type)
4931 {
4932   gcc_assert (OVERLOAD_TYPE_P (class_type));
4933 
4934   auto_diagnostic_group d;
4935   if (warning_at (location, OPT_Wattributes,
4936 		  "attribute ignored in declaration "
4937 		  "of %q#T", class_type))
4938     inform (location,
4939 	    "attribute for %q#T must follow the %qs keyword",
4940 	    class_type, class_key_or_enum_as_string (class_type));
4941 }
4942 
4943 /* Returns the cv-qualifiers that apply to the type specified
4944    by the DECLSPECS.  */
4945 
4946 static int
get_type_quals(const cp_decl_specifier_seq * declspecs)4947 get_type_quals (const cp_decl_specifier_seq *declspecs)
4948 {
4949   int type_quals = TYPE_UNQUALIFIED;
4950 
4951   if (decl_spec_seq_has_spec_p (declspecs, ds_const))
4952     type_quals |= TYPE_QUAL_CONST;
4953   if (decl_spec_seq_has_spec_p (declspecs, ds_volatile))
4954     type_quals |= TYPE_QUAL_VOLATILE;
4955   if (decl_spec_seq_has_spec_p (declspecs, ds_restrict))
4956     type_quals |= TYPE_QUAL_RESTRICT;
4957 
4958   return type_quals;
4959 }
4960 
4961 /* Make sure that a declaration with no declarator is well-formed, i.e.
4962    just declares a tagged type or anonymous union.
4963 
4964    Returns the type declared; or NULL_TREE if none.  */
4965 
4966 tree
check_tag_decl(cp_decl_specifier_seq * declspecs,bool explicit_type_instantiation_p)4967 check_tag_decl (cp_decl_specifier_seq *declspecs,
4968 		bool explicit_type_instantiation_p)
4969 {
4970   int saw_friend = decl_spec_seq_has_spec_p (declspecs, ds_friend);
4971   int saw_typedef = decl_spec_seq_has_spec_p (declspecs, ds_typedef);
4972   /* If a class, struct, or enum type is declared by the DECLSPECS
4973      (i.e, if a class-specifier, enum-specifier, or non-typename
4974      elaborated-type-specifier appears in the DECLSPECS),
4975      DECLARED_TYPE is set to the corresponding type.  */
4976   tree declared_type = NULL_TREE;
4977   bool error_p = false;
4978 
4979   if (declspecs->multiple_types_p)
4980     error_at (smallest_type_location (declspecs),
4981 	      "multiple types in one declaration");
4982   else if (declspecs->redefined_builtin_type)
4983     {
4984       location_t loc = declspecs->locations[ds_redefined_builtin_type_spec];
4985       if (!in_system_header_at (loc))
4986 	permerror (loc, "redeclaration of C++ built-in type %qT",
4987 		   declspecs->redefined_builtin_type);
4988       return NULL_TREE;
4989     }
4990 
4991   if (declspecs->type
4992       && TYPE_P (declspecs->type)
4993       && ((TREE_CODE (declspecs->type) != TYPENAME_TYPE
4994 	   && MAYBE_CLASS_TYPE_P (declspecs->type))
4995 	  || TREE_CODE (declspecs->type) == ENUMERAL_TYPE))
4996     declared_type = declspecs->type;
4997   else if (declspecs->type == error_mark_node)
4998     error_p = true;
4999 
5000   if (type_uses_auto (declared_type))
5001     {
5002       error_at (declspecs->locations[ds_type_spec],
5003 		"%<auto%> can only be specified for variables "
5004 		"or function declarations");
5005       return error_mark_node;
5006     }
5007 
5008   if (declared_type && !OVERLOAD_TYPE_P (declared_type))
5009     declared_type = NULL_TREE;
5010 
5011   if (!declared_type && !saw_friend && !error_p)
5012     permerror (input_location, "declaration does not declare anything");
5013   /* Check for an anonymous union.  */
5014   else if (declared_type && RECORD_OR_UNION_CODE_P (TREE_CODE (declared_type))
5015 	   && TYPE_UNNAMED_P (declared_type))
5016     {
5017       /* 7/3 In a simple-declaration, the optional init-declarator-list
5018 	 can be omitted only when declaring a class (clause 9) or
5019 	 enumeration (7.2), that is, when the decl-specifier-seq contains
5020 	 either a class-specifier, an elaborated-type-specifier with
5021 	 a class-key (9.1), or an enum-specifier.  In these cases and
5022 	 whenever a class-specifier or enum-specifier is present in the
5023 	 decl-specifier-seq, the identifiers in these specifiers are among
5024 	 the names being declared by the declaration (as class-name,
5025 	 enum-names, or enumerators, depending on the syntax).  In such
5026 	 cases, and except for the declaration of an unnamed bit-field (9.6),
5027 	 the decl-specifier-seq shall introduce one or more names into the
5028 	 program, or shall redeclare a name introduced by a previous
5029 	 declaration.  [Example:
5030 	     enum { };			// ill-formed
5031 	     typedef class { };		// ill-formed
5032 	 --end example]  */
5033       if (saw_typedef)
5034 	{
5035 	  error_at (declspecs->locations[ds_typedef],
5036 		    "missing type-name in typedef-declaration");
5037 	  return NULL_TREE;
5038 	}
5039       /* Anonymous unions are objects, so they can have specifiers.  */;
5040       SET_ANON_AGGR_TYPE_P (declared_type);
5041 
5042       if (TREE_CODE (declared_type) != UNION_TYPE)
5043 	pedwarn (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (declared_type)),
5044 		 OPT_Wpedantic, "ISO C++ prohibits anonymous structs");
5045     }
5046 
5047   else
5048     {
5049       if (decl_spec_seq_has_spec_p (declspecs, ds_inline))
5050 	error_at (declspecs->locations[ds_inline],
5051 		  "%<inline%> can only be specified for functions");
5052       else if (decl_spec_seq_has_spec_p (declspecs, ds_virtual))
5053 	error_at (declspecs->locations[ds_virtual],
5054 		  "%<virtual%> can only be specified for functions");
5055       else if (saw_friend
5056 	       && (!current_class_type
5057 		   || current_scope () != current_class_type))
5058 	error_at (declspecs->locations[ds_friend],
5059 		  "%<friend%> can only be specified inside a class");
5060       else if (decl_spec_seq_has_spec_p (declspecs, ds_explicit))
5061 	error_at (declspecs->locations[ds_explicit],
5062 		  "%<explicit%> can only be specified for constructors");
5063       else if (declspecs->storage_class)
5064 	error_at (declspecs->locations[ds_storage_class],
5065 		  "a storage class can only be specified for objects "
5066 		  "and functions");
5067       else if (decl_spec_seq_has_spec_p (declspecs, ds_const))
5068 	error_at (declspecs->locations[ds_const],
5069 		  "%<const%> can only be specified for objects and "
5070 		  "functions");
5071       else if (decl_spec_seq_has_spec_p (declspecs, ds_volatile))
5072 	error_at (declspecs->locations[ds_volatile],
5073 		  "%<volatile%> can only be specified for objects and "
5074 		  "functions");
5075       else if (decl_spec_seq_has_spec_p (declspecs, ds_restrict))
5076 	error_at (declspecs->locations[ds_restrict],
5077 		  "%<__restrict%> can only be specified for objects and "
5078 		  "functions");
5079       else if (decl_spec_seq_has_spec_p (declspecs, ds_thread))
5080 	error_at (declspecs->locations[ds_thread],
5081 		  "%<__thread%> can only be specified for objects "
5082 		  "and functions");
5083       else if (saw_typedef)
5084 	warning_at (declspecs->locations[ds_typedef], 0,
5085 		    "%<typedef%> was ignored in this declaration");
5086       else if (decl_spec_seq_has_spec_p (declspecs, ds_constexpr))
5087         error_at (declspecs->locations[ds_constexpr],
5088 		  "%qs cannot be used for type declarations", "constexpr");
5089       else if (decl_spec_seq_has_spec_p (declspecs, ds_constinit))
5090 	error_at (declspecs->locations[ds_constinit],
5091 		  "%qs cannot be used for type declarations", "constinit");
5092       else if (decl_spec_seq_has_spec_p (declspecs, ds_consteval))
5093 	error_at (declspecs->locations[ds_consteval],
5094 		  "%qs cannot be used for type declarations", "consteval");
5095     }
5096 
5097   if (declspecs->attributes && warn_attributes && declared_type)
5098     {
5099       location_t loc;
5100       if (!CLASS_TYPE_P (declared_type)
5101 	  || !CLASSTYPE_TEMPLATE_INSTANTIATION (declared_type))
5102 	/* For a non-template class, use the name location.  */
5103 	loc = location_of (declared_type);
5104       else
5105 	/* For a template class (an explicit instantiation), use the
5106 	   current location.  */
5107 	loc = input_location;
5108 
5109       if (explicit_type_instantiation_p)
5110 	/* [dcl.attr.grammar]/4:
5111 
5112 	       No attribute-specifier-seq shall appertain to an explicit
5113 	       instantiation.  */
5114 	{
5115 	  if (warning_at (loc, OPT_Wattributes,
5116 			  "attribute ignored in explicit instantiation %q#T",
5117 			  declared_type))
5118 	    inform (loc,
5119 		    "no attribute can be applied to "
5120 		    "an explicit instantiation");
5121 	}
5122       else
5123 	warn_misplaced_attr_for_class_type (loc, declared_type);
5124     }
5125 
5126   return declared_type;
5127 }
5128 
5129 /* Called when a declaration is seen that contains no names to declare.
5130    If its type is a reference to a structure, union or enum inherited
5131    from a containing scope, shadow that tag name for the current scope
5132    with a forward reference.
5133    If its type defines a new named structure or union
5134    or defines an enum, it is valid but we need not do anything here.
5135    Otherwise, it is an error.
5136 
5137    C++: may have to grok the declspecs to learn about static,
5138    complain for anonymous unions.
5139 
5140    Returns the TYPE declared -- or NULL_TREE if none.  */
5141 
5142 tree
shadow_tag(cp_decl_specifier_seq * declspecs)5143 shadow_tag (cp_decl_specifier_seq *declspecs)
5144 {
5145   tree t = check_tag_decl (declspecs,
5146 			   /*explicit_type_instantiation_p=*/false);
5147 
5148   if (!t)
5149     return NULL_TREE;
5150 
5151   if (maybe_process_partial_specialization (t) == error_mark_node)
5152     return NULL_TREE;
5153 
5154   /* This is where the variables in an anonymous union are
5155      declared.  An anonymous union declaration looks like:
5156      union { ... } ;
5157      because there is no declarator after the union, the parser
5158      sends that declaration here.  */
5159   if (ANON_AGGR_TYPE_P (t))
5160     {
5161       fixup_anonymous_aggr (t);
5162 
5163       if (TYPE_FIELDS (t))
5164 	{
5165 	  tree decl = grokdeclarator (/*declarator=*/NULL,
5166 				      declspecs, NORMAL, 0, NULL);
5167 	  finish_anon_union (decl);
5168 	}
5169     }
5170 
5171   return t;
5172 }
5173 
5174 /* Decode a "typename", such as "int **", returning a ..._TYPE node.  */
5175 
5176 tree
groktypename(cp_decl_specifier_seq * type_specifiers,const cp_declarator * declarator,bool is_template_arg)5177 groktypename (cp_decl_specifier_seq *type_specifiers,
5178 	      const cp_declarator *declarator,
5179 	      bool is_template_arg)
5180 {
5181   tree attrs;
5182   tree type;
5183   enum decl_context context
5184     = is_template_arg ? TEMPLATE_TYPE_ARG : TYPENAME;
5185   attrs = type_specifiers->attributes;
5186   type_specifiers->attributes = NULL_TREE;
5187   type = grokdeclarator (declarator, type_specifiers, context, 0, &attrs);
5188   if (attrs && type != error_mark_node)
5189     {
5190       if (CLASS_TYPE_P (type))
5191 	warning (OPT_Wattributes, "ignoring attributes applied to class type %qT "
5192 		 "outside of definition", type);
5193       else if (MAYBE_CLASS_TYPE_P (type))
5194 	/* A template type parameter or other dependent type.  */
5195 	warning (OPT_Wattributes, "ignoring attributes applied to dependent "
5196 		 "type %qT without an associated declaration", type);
5197       else
5198 	cplus_decl_attributes (&type, attrs, 0);
5199     }
5200   return type;
5201 }
5202 
5203 /* Process a DECLARATOR for a function-scope variable declaration,
5204    namespace-scope variable declaration, or function declaration.
5205    (Function definitions go through start_function; class member
5206    declarations appearing in the body of the class go through
5207    grokfield.)  The DECL corresponding to the DECLARATOR is returned.
5208    If an error occurs, the error_mark_node is returned instead.
5209 
5210    DECLSPECS are the decl-specifiers for the declaration.  INITIALIZED is
5211    SD_INITIALIZED if an explicit initializer is present, or SD_DEFAULTED
5212    for an explicitly defaulted function, or SD_DELETED for an explicitly
5213    deleted function, but 0 (SD_UNINITIALIZED) if this is a variable
5214    implicitly initialized via a default constructor.  ATTRIBUTES and
5215    PREFIX_ATTRIBUTES are GNU attributes associated with this declaration.
5216 
5217    The scope represented by the context of the returned DECL is pushed
5218    (if it is not the global namespace) and is assigned to
5219    *PUSHED_SCOPE_P.  The caller is then responsible for calling
5220    pop_scope on *PUSHED_SCOPE_P if it is set.  */
5221 
5222 tree
start_decl(const cp_declarator * declarator,cp_decl_specifier_seq * declspecs,int initialized,tree attributes,tree prefix_attributes,tree * pushed_scope_p)5223 start_decl (const cp_declarator *declarator,
5224 	    cp_decl_specifier_seq *declspecs,
5225 	    int initialized,
5226 	    tree attributes,
5227 	    tree prefix_attributes,
5228 	    tree *pushed_scope_p)
5229 {
5230   tree decl;
5231   tree context;
5232   bool was_public;
5233   int flags;
5234   bool alias;
5235 
5236   *pushed_scope_p = NULL_TREE;
5237 
5238   /* An object declared as __attribute__((deprecated)) suppresses
5239      warnings of uses of other deprecated items.  */
5240   if (lookup_attribute ("deprecated", attributes))
5241     deprecated_state = DEPRECATED_SUPPRESS;
5242 
5243   attributes = chainon (attributes, prefix_attributes);
5244 
5245   decl = grokdeclarator (declarator, declspecs, NORMAL, initialized,
5246 			 &attributes);
5247 
5248   deprecated_state = DEPRECATED_NORMAL;
5249 
5250   if (decl == NULL_TREE || VOID_TYPE_P (decl)
5251       || decl == error_mark_node)
5252     return error_mark_node;
5253 
5254   context = CP_DECL_CONTEXT (decl);
5255   if (context != global_namespace)
5256     *pushed_scope_p = push_scope (context);
5257 
5258   /* Is it valid for this decl to have an initializer at all?
5259      If not, set INITIALIZED to zero, which will indirectly
5260      tell `cp_finish_decl' to ignore the initializer once it is parsed.  */
5261   if (initialized
5262       && TREE_CODE (decl) == TYPE_DECL)
5263     {
5264       error_at (DECL_SOURCE_LOCATION (decl),
5265 		"typedef %qD is initialized (use %qs instead)",
5266 		decl, "decltype");
5267       return error_mark_node;
5268     }
5269 
5270   if (initialized)
5271     {
5272       if (! toplevel_bindings_p ()
5273 	  && DECL_EXTERNAL (decl))
5274 	warning (0, "declaration of %q#D has %<extern%> and is initialized",
5275 		 decl);
5276       DECL_EXTERNAL (decl) = 0;
5277       if (toplevel_bindings_p ())
5278 	TREE_STATIC (decl) = 1;
5279     }
5280   alias = lookup_attribute ("alias", DECL_ATTRIBUTES (decl)) != 0;
5281 
5282   if (alias && TREE_CODE (decl) == FUNCTION_DECL)
5283     record_key_method_defined (decl);
5284 
5285   /* If this is a typedef that names the class for linkage purposes
5286      (7.1.3p8), apply any attributes directly to the type.  */
5287   if (TREE_CODE (decl) == TYPE_DECL
5288       && OVERLOAD_TYPE_P (TREE_TYPE (decl))
5289       && decl == TYPE_NAME (TYPE_MAIN_VARIANT (TREE_TYPE (decl))))
5290     flags = ATTR_FLAG_TYPE_IN_PLACE;
5291   else
5292     flags = 0;
5293 
5294   /* Set attributes here so if duplicate decl, will have proper attributes.  */
5295   cplus_decl_attributes (&decl, attributes, flags);
5296 
5297   /* Dllimported symbols cannot be defined.  Static data members (which
5298      can be initialized in-class and dllimported) go through grokfield,
5299      not here, so we don't need to exclude those decls when checking for
5300      a definition.  */
5301   if (initialized && DECL_DLLIMPORT_P (decl))
5302     {
5303       error_at (DECL_SOURCE_LOCATION (decl),
5304 		"definition of %q#D is marked %<dllimport%>", decl);
5305       DECL_DLLIMPORT_P (decl) = 0;
5306     }
5307 
5308   /* If #pragma weak was used, mark the decl weak now.  */
5309   if (!processing_template_decl && !DECL_DECOMPOSITION_P (decl))
5310     maybe_apply_pragma_weak (decl);
5311 
5312   if (TREE_CODE (decl) == FUNCTION_DECL
5313       && DECL_DECLARED_INLINE_P (decl)
5314       && DECL_UNINLINABLE (decl)
5315       && lookup_attribute ("noinline", DECL_ATTRIBUTES (decl)))
5316     warning_at (DECL_SOURCE_LOCATION (decl), 0,
5317 		"inline function %qD given attribute %qs", decl, "noinline");
5318 
5319   if (TYPE_P (context) && COMPLETE_TYPE_P (complete_type (context)))
5320     {
5321       bool this_tmpl = (processing_template_decl
5322 			> template_class_depth (context));
5323       if (VAR_P (decl))
5324 	{
5325 	  tree field = lookup_field (context, DECL_NAME (decl), 0, false);
5326 	  if (field == NULL_TREE
5327 	      || !(VAR_P (field) || variable_template_p (field)))
5328 	    error ("%q+#D is not a static data member of %q#T", decl, context);
5329 	  else if (variable_template_p (field)
5330 		   && (DECL_LANG_SPECIFIC (decl)
5331 		       && DECL_TEMPLATE_SPECIALIZATION (decl)))
5332 	    /* OK, specialization was already checked.  */;
5333 	  else if (variable_template_p (field) && !this_tmpl)
5334 	    {
5335 	      error_at (DECL_SOURCE_LOCATION (decl),
5336 			"non-member-template declaration of %qD", decl);
5337 	      inform (DECL_SOURCE_LOCATION (field), "does not match "
5338 		      "member template declaration here");
5339 	      return error_mark_node;
5340 	    }
5341 	  else
5342 	    {
5343 	      if (variable_template_p (field))
5344 		field = DECL_TEMPLATE_RESULT (field);
5345 
5346 	      if (DECL_CONTEXT (field) != context)
5347 		{
5348 		  if (!same_type_p (DECL_CONTEXT (field), context))
5349 		    permerror (input_location, "ISO C++ does not permit %<%T::%D%> "
5350 			       "to be defined as %<%T::%D%>",
5351 			       DECL_CONTEXT (field), DECL_NAME (decl),
5352 			       context, DECL_NAME (decl));
5353 		  DECL_CONTEXT (decl) = DECL_CONTEXT (field);
5354 		}
5355 	      /* Static data member are tricky; an in-class initialization
5356 		 still doesn't provide a definition, so the in-class
5357 		 declaration will have DECL_EXTERNAL set, but will have an
5358 		 initialization.  Thus, duplicate_decls won't warn
5359 		 about this situation, and so we check here.  */
5360 	      if (initialized && DECL_INITIALIZED_IN_CLASS_P (field))
5361 		error ("duplicate initialization of %qD", decl);
5362 	      field = duplicate_decls (decl, field,
5363 				       /*newdecl_is_friend=*/false);
5364 	      if (field == error_mark_node)
5365 		return error_mark_node;
5366 	      else if (field)
5367 		decl = field;
5368 	    }
5369 	}
5370       else
5371 	{
5372 	  tree field = check_classfn (context, decl,
5373 				      this_tmpl
5374 				      ? current_template_parms
5375 				      : NULL_TREE);
5376 	  if (field && field != error_mark_node
5377 	      && duplicate_decls (decl, field,
5378 				 /*newdecl_is_friend=*/false))
5379 	    decl = field;
5380 	}
5381 
5382       /* cp_finish_decl sets DECL_EXTERNAL if DECL_IN_AGGR_P is set.  */
5383       DECL_IN_AGGR_P (decl) = 0;
5384       /* Do not mark DECL as an explicit specialization if it was not
5385 	 already marked as an instantiation; a declaration should
5386 	 never be marked as a specialization unless we know what
5387 	 template is being specialized.  */
5388       if (DECL_LANG_SPECIFIC (decl) && DECL_USE_TEMPLATE (decl))
5389 	{
5390 	  SET_DECL_TEMPLATE_SPECIALIZATION (decl);
5391 	  if (TREE_CODE (decl) == FUNCTION_DECL)
5392 	    DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
5393 				  && DECL_DECLARED_INLINE_P (decl));
5394 	  else
5395 	    DECL_COMDAT (decl) = false;
5396 
5397 	  /* [temp.expl.spec] An explicit specialization of a static data
5398 	     member of a template is a definition if the declaration
5399 	     includes an initializer; otherwise, it is a declaration.
5400 
5401 	     We check for processing_specialization so this only applies
5402 	     to the new specialization syntax.  */
5403 	  if (!initialized && processing_specialization)
5404 	    DECL_EXTERNAL (decl) = 1;
5405 	}
5406 
5407       if (DECL_EXTERNAL (decl) && ! DECL_TEMPLATE_SPECIALIZATION (decl)
5408 	  /* Aliases are definitions. */
5409 	  && !alias)
5410 	permerror (declarator->id_loc,
5411 		   "declaration of %q#D outside of class is not definition",
5412 		   decl);
5413     }
5414 
5415   was_public = TREE_PUBLIC (decl);
5416 
5417   /* Enter this declaration into the symbol table.  Don't push the plain
5418      VAR_DECL for a variable template.  */
5419   if (!template_parm_scope_p ()
5420       || !VAR_P (decl))
5421     decl = maybe_push_decl (decl);
5422 
5423   if (processing_template_decl)
5424     {
5425       /* Make sure that for a `constinit' decl push_template_decl creates
5426 	 a DECL_TEMPLATE_INFO info for us, so that cp_finish_decl can then set
5427 	 TINFO_VAR_DECLARED_CONSTINIT.  */
5428       if (decl_spec_seq_has_spec_p (declspecs, ds_constinit))
5429 	retrofit_lang_decl (decl);
5430       decl = push_template_decl (decl);
5431     }
5432   if (decl == error_mark_node)
5433     return error_mark_node;
5434 
5435   if (VAR_P (decl)
5436       && DECL_NAMESPACE_SCOPE_P (decl) && !TREE_PUBLIC (decl) && !was_public
5437       && !DECL_THIS_STATIC (decl) && !DECL_ARTIFICIAL (decl))
5438     {
5439       /* This is a const variable with implicit 'static'.  Set
5440 	 DECL_THIS_STATIC so we can tell it from variables that are
5441 	 !TREE_PUBLIC because of the anonymous namespace.  */
5442       gcc_assert (CP_TYPE_CONST_P (TREE_TYPE (decl)) || errorcount);
5443       DECL_THIS_STATIC (decl) = 1;
5444     }
5445 
5446   if (current_function_decl && VAR_P (decl)
5447       && DECL_DECLARED_CONSTEXPR_P (current_function_decl))
5448     {
5449       bool ok = false;
5450       if (CP_DECL_THREAD_LOCAL_P (decl))
5451 	error_at (DECL_SOURCE_LOCATION (decl),
5452 		  "%qD declared %<thread_local%> in %qs function", decl,
5453 		  DECL_IMMEDIATE_FUNCTION_P (current_function_decl)
5454 		  ? "consteval" : "constexpr");
5455       else if (TREE_STATIC (decl))
5456 	error_at (DECL_SOURCE_LOCATION (decl),
5457 		  "%qD declared %<static%> in %qs function", decl,
5458 		  DECL_IMMEDIATE_FUNCTION_P (current_function_decl)
5459 		  ? "consteval" : "constexpr");
5460       else
5461 	ok = true;
5462       if (!ok)
5463 	cp_function_chain->invalid_constexpr = true;
5464     }
5465 
5466   if (!processing_template_decl && VAR_P (decl))
5467     start_decl_1 (decl, initialized);
5468 
5469   return decl;
5470 }
5471 
5472 /* Process the declaration of a variable DECL.  INITIALIZED is true
5473    iff DECL is explicitly initialized.  (INITIALIZED is false if the
5474    variable is initialized via an implicitly-called constructor.)
5475    This function must be called for ordinary variables (including, for
5476    example, implicit instantiations of templates), but must not be
5477    called for template declarations.  */
5478 
5479 void
start_decl_1(tree decl,bool initialized)5480 start_decl_1 (tree decl, bool initialized)
5481 {
5482   tree type;
5483   bool complete_p;
5484   bool aggregate_definition_p;
5485 
5486   gcc_assert (!processing_template_decl);
5487 
5488   if (error_operand_p (decl))
5489     return;
5490 
5491   gcc_assert (VAR_P (decl));
5492 
5493   type = TREE_TYPE (decl);
5494   complete_p = COMPLETE_TYPE_P (type);
5495   aggregate_definition_p = MAYBE_CLASS_TYPE_P (type) && !DECL_EXTERNAL (decl);
5496 
5497   /* If an explicit initializer is present, or if this is a definition
5498      of an aggregate, then we need a complete type at this point.
5499      (Scalars are always complete types, so there is nothing to
5500      check.)  This code just sets COMPLETE_P; errors (if necessary)
5501      are issued below.  */
5502   if ((initialized || aggregate_definition_p)
5503       && !complete_p
5504       && COMPLETE_TYPE_P (complete_type (type)))
5505     {
5506       complete_p = true;
5507       /* We will not yet have set TREE_READONLY on DECL if the type
5508 	 was "const", but incomplete, before this point.  But, now, we
5509 	 have a complete type, so we can try again.  */
5510       cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
5511     }
5512 
5513   if (is_global_var (decl))
5514     {
5515       type_context_kind context = (DECL_THREAD_LOCAL_P (decl)
5516 				   ? TCTX_THREAD_STORAGE
5517 				   : TCTX_STATIC_STORAGE);
5518       verify_type_context (input_location, context, TREE_TYPE (decl));
5519     }
5520   if (initialized)
5521     /* Is it valid for this decl to have an initializer at all?  */
5522     {
5523       /* Don't allow initializations for incomplete types except for
5524 	 arrays which might be completed by the initialization.  */
5525       if (complete_p)
5526 	;			/* A complete type is ok.  */
5527       else if (type_uses_auto (type))
5528 	; 			/* An auto type is ok.  */
5529       else if (TREE_CODE (type) != ARRAY_TYPE)
5530 	{
5531 	  error ("variable %q#D has initializer but incomplete type", decl);
5532 	  type = TREE_TYPE (decl) = error_mark_node;
5533 	}
5534       else if (!COMPLETE_TYPE_P (complete_type (TREE_TYPE (type))))
5535 	{
5536 	  if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
5537 	    error ("elements of array %q#D have incomplete type", decl);
5538 	  /* else we already gave an error in start_decl.  */
5539 	}
5540     }
5541   else if (aggregate_definition_p && !complete_p)
5542     {
5543       if (type_uses_auto (type))
5544 	gcc_assert (CLASS_PLACEHOLDER_TEMPLATE (type));
5545       else
5546 	{
5547 	  error ("aggregate %q#D has incomplete type and cannot be defined",
5548 		 decl);
5549 	  /* Change the type so that assemble_variable will give
5550 	     DECL an rtl we can live with: (mem (const_int 0)).  */
5551 	  type = TREE_TYPE (decl) = error_mark_node;
5552 	}
5553     }
5554 
5555   /* Create a new scope to hold this declaration if necessary.
5556      Whether or not a new scope is necessary cannot be determined
5557      until after the type has been completed; if the type is a
5558      specialization of a class template it is not until after
5559      instantiation has occurred that TYPE_HAS_NONTRIVIAL_DESTRUCTOR
5560      will be set correctly.  */
5561   maybe_push_cleanup_level (type);
5562 }
5563 
5564 /* Handle initialization of references.  DECL, TYPE, and INIT have the
5565    same meaning as in cp_finish_decl.  *CLEANUP must be NULL on entry,
5566    but will be set to a new CLEANUP_STMT if a temporary is created
5567    that must be destroyed subsequently.
5568 
5569    Returns an initializer expression to use to initialize DECL, or
5570    NULL if the initialization can be performed statically.
5571 
5572    Quotes on semantics can be found in ARM 8.4.3.  */
5573 
5574 static tree
grok_reference_init(tree decl,tree type,tree init,int flags)5575 grok_reference_init (tree decl, tree type, tree init, int flags)
5576 {
5577   if (init == NULL_TREE)
5578     {
5579       if ((DECL_LANG_SPECIFIC (decl) == 0
5580 	   || DECL_IN_AGGR_P (decl) == 0)
5581 	  && ! DECL_THIS_EXTERN (decl))
5582 	error_at (DECL_SOURCE_LOCATION (decl),
5583 		  "%qD declared as reference but not initialized", decl);
5584       return NULL_TREE;
5585     }
5586 
5587   tree ttype = TREE_TYPE (type);
5588   if (TREE_CODE (init) == TREE_LIST)
5589     {
5590       /* This handles (C++20 only) code like
5591 
5592 	   const A& r(1, 2, 3);
5593 
5594 	 where we treat the parenthesized list as a CONSTRUCTOR.  */
5595       if (TREE_TYPE (init) == NULL_TREE
5596 	  && CP_AGGREGATE_TYPE_P (ttype)
5597 	  && !DECL_DECOMPOSITION_P (decl)
5598 	  && (cxx_dialect >= cxx2a))
5599 	{
5600 	  /* We don't know yet if we should treat const A& r(1) as
5601 	     const A& r{1}.  */
5602 	  if (list_length (init) == 1)
5603 	    {
5604 	      flags |= LOOKUP_AGGREGATE_PAREN_INIT;
5605 	      init = build_x_compound_expr_from_list (init, ELK_INIT,
5606 						      tf_warning_or_error);
5607 	    }
5608 	  /* If the list had more than one element, the code is ill-formed
5609 	     pre-C++20, so we can build a constructor right away.  */
5610 	  else
5611 	    {
5612 	      init = build_constructor_from_list (init_list_type_node, init);
5613 	      CONSTRUCTOR_IS_DIRECT_INIT (init) = true;
5614 	      CONSTRUCTOR_IS_PAREN_INIT (init) = true;
5615 	    }
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
check_array_designated_initializer(constructor_elt * ce,unsigned HOST_WIDE_INT index)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
maybe_deduce_size_from_array_init(tree decl,tree init)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
layout_var_decl(tree decl)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
maybe_commonize_var(tree decl)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
check_for_uninitialized_const_var(tree decl,bool constexpr_context_p,tsubst_flags_t complain)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 < cxx2a
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 >= cxx2a)
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 
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
next_initializable_field(tree field)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
is_direct_enum_init(tree type,tree init)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
reshape_init_array_1(tree elt_type,tree max_index,reshape_iter * d,tree first_initializer_p,tsubst_flags_t complain)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
reshape_init_array(tree type,reshape_iter * d,tree first_initializer_p,tsubst_flags_t complain)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
reshape_init_vector(tree type,reshape_iter * d,tsubst_flags_t complain)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
reshape_init_class(tree type,reshape_iter * d,bool first_initializer_p,tsubst_flags_t complain)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   field = next_initializable_field (TYPE_FIELDS (type));
6171 
6172   if (!field)
6173     {
6174       /* [dcl.init.aggr]
6175 
6176 	An initializer for an aggregate member that is an
6177 	empty class shall have the form of an empty
6178 	initializer-list {}.  */
6179       if (!first_initializer_p)
6180 	{
6181 	  if (complain & tf_error)
6182 	    error ("initializer for %qT must be brace-enclosed", type);
6183 	  return error_mark_node;
6184 	}
6185       return new_init;
6186     }
6187 
6188   /* Loop through the initializable fields, gathering initializers.  */
6189   while (d->cur != d->end)
6190     {
6191       tree field_init;
6192       constructor_elt *old_cur = d->cur;
6193 
6194       /* Handle designated initializers, as an extension.  */
6195       if (d->cur->index)
6196 	{
6197 	  if (d->cur->index == error_mark_node)
6198 	    return error_mark_node;
6199 
6200 	  if (TREE_CODE (d->cur->index) == FIELD_DECL)
6201 	    {
6202 	      /* We already reshaped this.  */
6203 	      if (field != d->cur->index)
6204 		{
6205 		  tree id = DECL_NAME (d->cur->index);
6206 		  gcc_assert (id);
6207 		  gcc_checking_assert (d->cur->index
6208 				       == get_class_binding (type, id));
6209 		  field = d->cur->index;
6210 		}
6211 	    }
6212 	  else if (TREE_CODE (d->cur->index) == IDENTIFIER_NODE)
6213 	    field = get_class_binding (type, d->cur->index);
6214 	  else
6215 	    {
6216 	      if (complain & tf_error)
6217 		error ("%<[%E] =%> used in a GNU-style designated initializer"
6218 		       " for class %qT", d->cur->index, type);
6219 	      return error_mark_node;
6220 	    }
6221 
6222 	  if (!field || TREE_CODE (field) != FIELD_DECL)
6223 	    {
6224 	      if (complain & tf_error)
6225 		error ("%qT has no non-static data member named %qD", type,
6226 		       d->cur->index);
6227 	      return error_mark_node;
6228 	    }
6229 	}
6230 
6231       /* If we processed all the member of the class, we are done.  */
6232       if (!field)
6233 	break;
6234 
6235       field_init = reshape_init_r (TREE_TYPE (field), d,
6236 				   /*first_initializer_p=*/NULL_TREE,
6237 				   complain);
6238       if (field_init == error_mark_node)
6239 	return error_mark_node;
6240 
6241       if (d->cur == old_cur && d->cur->index)
6242 	{
6243 	  /* This can happen with an invalid initializer for a flexible
6244 	     array member (c++/54441).  */
6245 	  if (complain & tf_error)
6246 	    error ("invalid initializer for %q#D", field);
6247 	  return error_mark_node;
6248 	}
6249 
6250       CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (new_init), field, field_init);
6251 
6252       /* [dcl.init.aggr]
6253 
6254 	When a union  is  initialized with a brace-enclosed
6255 	initializer, the braces shall only contain an
6256 	initializer for the first member of the union.  */
6257       if (TREE_CODE (type) == UNION_TYPE)
6258 	break;
6259 
6260       field = next_initializable_field (DECL_CHAIN (field));
6261     }
6262 
6263   return new_init;
6264 }
6265 
6266 /* Subroutine of reshape_init_r.  We're in a context where C99 initializer
6267    designators are not valid; either complain or return true to indicate
6268    that reshape_init_r should return error_mark_node.  */
6269 
6270 static bool
has_designator_problem(reshape_iter * d,tsubst_flags_t complain)6271 has_designator_problem (reshape_iter *d, tsubst_flags_t complain)
6272 {
6273   if (d->cur->index)
6274     {
6275       if (complain & tf_error)
6276 	error_at (cp_expr_loc_or_input_loc (d->cur->index),
6277 		  "C99 designator %qE outside aggregate initializer",
6278 		  d->cur->index);
6279       else
6280 	return true;
6281     }
6282   return false;
6283 }
6284 
6285 /* Subroutine of reshape_init, which processes a single initializer (part of
6286    a CONSTRUCTOR). TYPE is the type of the variable being initialized, D is the
6287    iterator within the CONSTRUCTOR which points to the initializer to process.
6288    If this is the first initializer of the outermost CONSTRUCTOR node,
6289    FIRST_INITIALIZER_P is that CONSTRUCTOR; otherwise, it is NULL_TREE.  */
6290 
6291 static tree
reshape_init_r(tree type,reshape_iter * d,tree first_initializer_p,tsubst_flags_t complain)6292 reshape_init_r (tree type, reshape_iter *d, tree first_initializer_p,
6293 		tsubst_flags_t complain)
6294 {
6295   tree init = d->cur->value;
6296 
6297   if (error_operand_p (init))
6298     return error_mark_node;
6299 
6300   if (first_initializer_p && !CP_AGGREGATE_TYPE_P (type)
6301       && has_designator_problem (d, complain))
6302     return error_mark_node;
6303 
6304   tree stripped_init = tree_strip_any_location_wrapper (init);
6305 
6306   if (TREE_CODE (type) == COMPLEX_TYPE)
6307     {
6308       /* A complex type can be initialized from one or two initializers,
6309 	 but braces are not elided.  */
6310       d->cur++;
6311       if (BRACE_ENCLOSED_INITIALIZER_P (stripped_init))
6312 	{
6313 	  if (CONSTRUCTOR_NELTS (stripped_init) > 2)
6314 	    {
6315 	      if (complain & tf_error)
6316 		error ("too many initializers for %qT", type);
6317 	      else
6318 		return error_mark_node;
6319 	    }
6320 	}
6321       else if (first_initializer_p && d->cur != d->end)
6322 	{
6323 	  vec<constructor_elt, va_gc> *v = 0;
6324 	  CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, init);
6325 	  CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, d->cur->value);
6326 	  if (has_designator_problem (d, complain))
6327 	    return error_mark_node;
6328 	  d->cur++;
6329 	  init = build_constructor (init_list_type_node, v);
6330 	}
6331       return init;
6332     }
6333 
6334   /* A non-aggregate type is always initialized with a single
6335      initializer.  */
6336   if (!CP_AGGREGATE_TYPE_P (type))
6337     {
6338       /* It is invalid to initialize a non-aggregate type with a
6339 	 brace-enclosed initializer before C++0x.
6340 	 We need to check for BRACE_ENCLOSED_INITIALIZER_P here because
6341 	 of g++.old-deja/g++.mike/p7626.C: a pointer-to-member constant is
6342 	 a CONSTRUCTOR (with a record type).  */
6343       if (TREE_CODE (stripped_init) == CONSTRUCTOR
6344 	  /* Don't complain about a capture-init.  */
6345 	  && !CONSTRUCTOR_IS_DIRECT_INIT (stripped_init)
6346 	  && BRACE_ENCLOSED_INITIALIZER_P (stripped_init))  /* p7626.C */
6347 	{
6348 	  if (SCALAR_TYPE_P (type))
6349 	    {
6350 	      if (cxx_dialect < cxx11)
6351 		{
6352 		  if (complain & tf_error)
6353 		    error ("braces around scalar initializer for type %qT",
6354 			   type);
6355 		  init = error_mark_node;
6356 		}
6357 	      else if (first_initializer_p
6358 		       || (CONSTRUCTOR_NELTS (stripped_init) > 0
6359 			   && (BRACE_ENCLOSED_INITIALIZER_P
6360 			       (CONSTRUCTOR_ELT (stripped_init,0)->value))))
6361 		{
6362 		  if (complain & tf_error)
6363 		    error ("too many braces around scalar initializer "
6364 		           "for type %qT", type);
6365 		  init = error_mark_node;
6366 		}
6367 	    }
6368 	  else
6369 	    maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
6370 	}
6371 
6372       d->cur++;
6373       return init;
6374     }
6375 
6376   /* "If T is a class type and the initializer list has a single element of
6377      type cv U, where U is T or a class derived from T, the object is
6378      initialized from that element."  Even if T is an aggregate.  */
6379   if (cxx_dialect >= cxx11 && (CLASS_TYPE_P (type) || VECTOR_TYPE_P (type))
6380       && first_initializer_p
6381       && d->end - d->cur == 1
6382       && reference_related_p (type, TREE_TYPE (init)))
6383     {
6384       d->cur++;
6385       return init;
6386     }
6387 
6388   /* [dcl.init.aggr]
6389 
6390      All implicit type conversions (clause _conv_) are considered when
6391      initializing the aggregate member with an initializer from an
6392      initializer-list.  If the initializer can initialize a member,
6393      the member is initialized.  Otherwise, if the member is itself a
6394      non-empty subaggregate, brace elision is assumed and the
6395      initializer is considered for the initialization of the first
6396      member of the subaggregate.  */
6397   if ((TREE_CODE (init) != CONSTRUCTOR || COMPOUND_LITERAL_P (init))
6398       /* But don't try this for the first initializer, since that would be
6399 	 looking through the outermost braces; A a2 = { a1 }; is not a
6400 	 valid aggregate initialization.  */
6401       && !first_initializer_p
6402       && (same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (init))
6403 	  || can_convert_arg (type, TREE_TYPE (init), init, LOOKUP_NORMAL,
6404 			      complain)))
6405     {
6406       d->cur++;
6407       return init;
6408     }
6409 
6410   /* [dcl.init.string]
6411 
6412       A char array (whether plain char, signed char, or unsigned char)
6413       can be initialized by a string-literal (optionally enclosed in
6414       braces); a wchar_t array can be initialized by a wide
6415       string-literal (optionally enclosed in braces).  */
6416   if (TREE_CODE (type) == ARRAY_TYPE
6417       && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type))))
6418     {
6419       tree str_init = init;
6420       tree stripped_str_init = stripped_init;
6421 
6422       /* Strip one level of braces if and only if they enclose a single
6423 	 element (as allowed by [dcl.init.string]).  */
6424       if (!first_initializer_p
6425 	  && TREE_CODE (stripped_str_init) == CONSTRUCTOR
6426 	  && CONSTRUCTOR_NELTS (stripped_str_init) == 1)
6427 	{
6428 	  str_init = (*CONSTRUCTOR_ELTS (stripped_str_init))[0].value;
6429 	  stripped_str_init = tree_strip_any_location_wrapper (str_init);
6430 	}
6431 
6432       /* If it's a string literal, then it's the initializer for the array
6433 	 as a whole. Otherwise, continue with normal initialization for
6434 	 array types (one value per array element).  */
6435       if (TREE_CODE (stripped_str_init) == STRING_CST)
6436 	{
6437 	  if (has_designator_problem (d, complain))
6438 	    return error_mark_node;
6439 	  d->cur++;
6440 	  return str_init;
6441 	}
6442     }
6443 
6444   /* The following cases are about aggregates. If we are not within a full
6445      initializer already, and there is not a CONSTRUCTOR, it means that there
6446      is a missing set of braces (that is, we are processing the case for
6447      which reshape_init exists).  */
6448   if (!first_initializer_p)
6449     {
6450       if (TREE_CODE (stripped_init) == CONSTRUCTOR)
6451 	{
6452 	  tree init_type = TREE_TYPE (init);
6453 	  if (init_type && TYPE_PTRMEMFUNC_P (init_type))
6454 	    /* There is no need to call reshape_init for pointer-to-member
6455 	       function initializers, as they are always constructed correctly
6456 	       by the front end.  Here we have e.g. {.__pfn=0B, .__delta=0},
6457 	       which is missing outermost braces.  We should warn below, and
6458 	       one of the routines below will wrap it in additional { }.  */;
6459 	  /* For a nested compound literal, proceed to specialized routines,
6460 	     to handle initialization of arrays and similar.  */
6461 	  else if (COMPOUND_LITERAL_P (stripped_init))
6462 	    gcc_assert (!BRACE_ENCLOSED_INITIALIZER_P (stripped_init));
6463 	  /* A CONSTRUCTOR of the target's type is a previously
6464 	     digested initializer.  */
6465 	  else if (same_type_ignoring_top_level_qualifiers_p (type, init_type))
6466 	    {
6467 	      ++d->cur;
6468 	      return init;
6469 	    }
6470 	  else
6471 	    {
6472 	      /* Something that hasn't been reshaped yet.  */
6473 	      ++d->cur;
6474 	      gcc_assert (BRACE_ENCLOSED_INITIALIZER_P (stripped_init));
6475 	      return reshape_init (type, init, complain);
6476 	    }
6477 	}
6478 
6479       if (complain & tf_warning)
6480 	warning (OPT_Wmissing_braces,
6481 		 "missing braces around initializer for %qT",
6482 		 type);
6483     }
6484 
6485   /* Dispatch to specialized routines.  */
6486   if (CLASS_TYPE_P (type))
6487     return reshape_init_class (type, d, first_initializer_p, complain);
6488   else if (TREE_CODE (type) == ARRAY_TYPE)
6489     return reshape_init_array (type, d, first_initializer_p, complain);
6490   else if (VECTOR_TYPE_P (type))
6491     return reshape_init_vector (type, d, complain);
6492   else
6493     gcc_unreachable();
6494 }
6495 
6496 /* Undo the brace-elision allowed by [dcl.init.aggr] in a
6497    brace-enclosed aggregate initializer.
6498 
6499    INIT is the CONSTRUCTOR containing the list of initializers describing
6500    a brace-enclosed initializer for an entity of the indicated aggregate TYPE.
6501    It may not presently match the shape of the TYPE; for example:
6502 
6503      struct S { int a; int b; };
6504      struct S a[] = { 1, 2, 3, 4 };
6505 
6506    Here INIT will hold a vector of four elements, rather than a
6507    vector of two elements, each itself a vector of two elements.  This
6508    routine transforms INIT from the former form into the latter.  The
6509    revised CONSTRUCTOR node is returned.  */
6510 
6511 tree
reshape_init(tree type,tree init,tsubst_flags_t complain)6512 reshape_init (tree type, tree init, tsubst_flags_t complain)
6513 {
6514   vec<constructor_elt, va_gc> *v;
6515   reshape_iter d;
6516   tree new_init;
6517 
6518   gcc_assert (BRACE_ENCLOSED_INITIALIZER_P (init));
6519 
6520   v = CONSTRUCTOR_ELTS (init);
6521 
6522   /* An empty constructor does not need reshaping, and it is always a valid
6523      initializer.  */
6524   if (vec_safe_is_empty (v))
6525     return init;
6526 
6527   /* Brace elision is not performed for a CONSTRUCTOR representing
6528      parenthesized aggregate initialization.  */
6529   if (CONSTRUCTOR_IS_PAREN_INIT (init))
6530     return init;
6531 
6532   /* Handle [dcl.init.list] direct-list-initialization from
6533      single element of enumeration with a fixed underlying type.  */
6534   if (is_direct_enum_init (type, init))
6535     {
6536       tree elt = CONSTRUCTOR_ELT (init, 0)->value;
6537       type = cv_unqualified (type);
6538       if (check_narrowing (ENUM_UNDERLYING_TYPE (type), elt, complain))
6539 	{
6540 	  warning_sentinel w (warn_useless_cast);
6541 	  warning_sentinel w2 (warn_ignored_qualifiers);
6542 	  return cp_build_c_cast (input_location, type, elt,
6543 				  tf_warning_or_error);
6544 	}
6545       else
6546 	return error_mark_node;
6547     }
6548 
6549   /* Recurse on this CONSTRUCTOR.  */
6550   d.cur = &(*v)[0];
6551   d.end = d.cur + v->length ();
6552 
6553   new_init = reshape_init_r (type, &d, init, complain);
6554   if (new_init == error_mark_node)
6555     return error_mark_node;
6556 
6557   /* Make sure all the element of the constructor were used. Otherwise,
6558      issue an error about exceeding initializers.  */
6559   if (d.cur != d.end)
6560     {
6561       if (complain & tf_error)
6562 	error ("too many initializers for %qT", type);
6563       return error_mark_node;
6564     }
6565 
6566   if (CONSTRUCTOR_IS_DIRECT_INIT (init)
6567       && BRACE_ENCLOSED_INITIALIZER_P (new_init))
6568     CONSTRUCTOR_IS_DIRECT_INIT (new_init) = true;
6569   if (CONSTRUCTOR_IS_DESIGNATED_INIT (init)
6570       && BRACE_ENCLOSED_INITIALIZER_P (new_init))
6571     CONSTRUCTOR_IS_DESIGNATED_INIT (new_init) = true;
6572 
6573   return new_init;
6574 }
6575 
6576 /* Verify array initializer.  Returns true if errors have been reported.  */
6577 
6578 bool
check_array_initializer(tree decl,tree type,tree init)6579 check_array_initializer (tree decl, tree type, tree init)
6580 {
6581   tree element_type = TREE_TYPE (type);
6582 
6583   /* Structured binding when initialized with an array type needs
6584      to have complete type.  */
6585   if (decl
6586       && DECL_DECOMPOSITION_P (decl)
6587       && !DECL_DECOMP_BASE (decl)
6588       && !COMPLETE_TYPE_P (type))
6589     {
6590       error_at (DECL_SOURCE_LOCATION (decl),
6591 		"structured binding has incomplete type %qT", type);
6592       TREE_TYPE (decl) = error_mark_node;
6593       return true;
6594     }
6595 
6596   /* The array type itself need not be complete, because the
6597      initializer may tell us how many elements are in the array.
6598      But, the elements of the array must be complete.  */
6599   if (!COMPLETE_TYPE_P (complete_type (element_type)))
6600     {
6601       if (decl)
6602 	error_at (DECL_SOURCE_LOCATION (decl),
6603 		  "elements of array %q#D have incomplete type", decl);
6604       else
6605 	error ("elements of array %q#T have incomplete type", type);
6606       return true;
6607     }
6608 
6609   location_t loc = (decl ? location_of (decl) : input_location);
6610   if (!verify_type_context (loc, TCTX_ARRAY_ELEMENT, element_type))
6611     return true;
6612 
6613   /* A compound literal can't have variable size.  */
6614   if (init && !decl
6615       && ((COMPLETE_TYPE_P (type) && !TREE_CONSTANT (TYPE_SIZE (type)))
6616 	  || !TREE_CONSTANT (TYPE_SIZE (element_type))))
6617     {
6618       error ("variable-sized compound literal");
6619       return true;
6620     }
6621   return false;
6622 }
6623 
6624 /* Subroutine of check_initializer; args are passed down from that function.
6625    Set stmts_are_full_exprs_p to 1 across a call to build_aggr_init.  */
6626 
6627 static tree
build_aggr_init_full_exprs(tree decl,tree init,int flags)6628 build_aggr_init_full_exprs (tree decl, tree init, int flags)
6629 
6630 {
6631   gcc_assert (stmts_are_full_exprs_p ());
6632   return build_aggr_init (decl, init, flags, tf_warning_or_error);
6633 }
6634 
6635 /* Verify INIT (the initializer for DECL), and record the
6636    initialization in DECL_INITIAL, if appropriate.  CLEANUP is as for
6637    grok_reference_init.
6638 
6639    If the return value is non-NULL, it is an expression that must be
6640    evaluated dynamically to initialize DECL.  */
6641 
6642 static tree
check_initializer(tree decl,tree init,int flags,vec<tree,va_gc> ** cleanups)6643 check_initializer (tree decl, tree init, int flags, vec<tree, va_gc> **cleanups)
6644 {
6645   tree type;
6646   tree init_code = NULL;
6647   tree core_type;
6648 
6649   /* Things that are going to be initialized need to have complete
6650      type.  */
6651   TREE_TYPE (decl) = type = complete_type (TREE_TYPE (decl));
6652 
6653   if (DECL_HAS_VALUE_EXPR_P (decl))
6654     {
6655       /* A variable with DECL_HAS_VALUE_EXPR_P set is just a placeholder,
6656 	 it doesn't have storage to be initialized.  */
6657       gcc_assert (init == NULL_TREE);
6658       return NULL_TREE;
6659     }
6660 
6661   if (type == error_mark_node)
6662     /* We will have already complained.  */
6663     return NULL_TREE;
6664 
6665   if (TREE_CODE (type) == ARRAY_TYPE)
6666     {
6667       if (check_array_initializer (decl, type, init))
6668 	return NULL_TREE;
6669     }
6670   else if (!COMPLETE_TYPE_P (type))
6671     {
6672       error_at (DECL_SOURCE_LOCATION (decl),
6673 		"%q#D has incomplete type", decl);
6674       TREE_TYPE (decl) = error_mark_node;
6675       return NULL_TREE;
6676     }
6677   else
6678     /* There is no way to make a variable-sized class type in GNU C++.  */
6679     gcc_assert (TREE_CONSTANT (TYPE_SIZE (type)));
6680 
6681   if (init && BRACE_ENCLOSED_INITIALIZER_P (init))
6682     {
6683       int init_len = CONSTRUCTOR_NELTS (init);
6684       if (SCALAR_TYPE_P (type))
6685 	{
6686 	  if (init_len == 0)
6687 	    {
6688 	      maybe_warn_cpp0x (CPP0X_INITIALIZER_LISTS);
6689 	      init = build_zero_init (type, NULL_TREE, false);
6690 	    }
6691 	  else if (init_len != 1 && TREE_CODE (type) != COMPLEX_TYPE)
6692 	    {
6693 	      error_at (cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (decl)),
6694 			"scalar object %qD requires one element in "
6695 			"initializer", decl);
6696 	      TREE_TYPE (decl) = error_mark_node;
6697 	      return NULL_TREE;
6698 	    }
6699 	}
6700     }
6701 
6702   if (TREE_CODE (decl) == CONST_DECL)
6703     {
6704       gcc_assert (!TYPE_REF_P (type));
6705 
6706       DECL_INITIAL (decl) = init;
6707 
6708       gcc_assert (init != NULL_TREE);
6709       init = NULL_TREE;
6710     }
6711   else if (!init && DECL_REALLY_EXTERN (decl))
6712     ;
6713   else if (init || type_build_ctor_call (type)
6714 	   || TYPE_REF_P (type))
6715     {
6716       if (TYPE_REF_P (type))
6717 	{
6718 	  init = grok_reference_init (decl, type, init, flags);
6719 	  flags |= LOOKUP_ALREADY_DIGESTED;
6720 	}
6721       else if (!init)
6722 	check_for_uninitialized_const_var (decl, /*constexpr_context_p=*/false,
6723 					   tf_warning_or_error);
6724       /* Do not reshape constructors of vectors (they don't need to be
6725 	 reshaped.  */
6726       else if (BRACE_ENCLOSED_INITIALIZER_P (init))
6727 	{
6728 	  if (is_std_init_list (type))
6729 	    {
6730 	      init = perform_implicit_conversion (type, init,
6731 						  tf_warning_or_error);
6732 	      flags |= LOOKUP_ALREADY_DIGESTED;
6733 	    }
6734 	  else if (TYPE_NON_AGGREGATE_CLASS (type))
6735 	    {
6736 	      /* Don't reshape if the class has constructors.  */
6737 	      if (cxx_dialect == cxx98)
6738 		error_at (cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (decl)),
6739 			  "in C++98 %qD must be initialized by "
6740 			  "constructor, not by %<{...}%>",
6741 			  decl);
6742 	    }
6743 	  else if (VECTOR_TYPE_P (type) && TYPE_VECTOR_OPAQUE (type))
6744 	    {
6745 	      error ("opaque vector types cannot be initialized");
6746 	      init = error_mark_node;
6747 	    }
6748 	  else
6749 	    {
6750 	      init = reshape_init (type, init, tf_warning_or_error);
6751 	      flags |= LOOKUP_NO_NARROWING;
6752 	    }
6753 	}
6754       /* [dcl.init] "Otherwise, if the destination type is an array, the object
6755 	 is initialized as follows..."  So handle things like
6756 
6757 	  int a[](1, 2, 3);
6758 
6759 	 which is permitted in C++20 by P0960.  */
6760       else if (TREE_CODE (init) == TREE_LIST
6761 	       && TREE_TYPE (init) == NULL_TREE
6762 	       && TREE_CODE (type) == ARRAY_TYPE
6763 	       && !DECL_DECOMPOSITION_P (decl)
6764 	       && (cxx_dialect >= cxx2a))
6765 	{
6766 	  /* [dcl.init.string] "An array of ordinary character type [...]
6767 	     can be initialized by an ordinary string literal [...] by an
6768 	     appropriately-typed string literal enclosed in braces" only
6769 	     talks about braces, but GCC has always accepted
6770 
6771 	       char a[]("foobar");
6772 
6773 	     so we continue to do so.  */
6774 	  tree val = TREE_VALUE (init);
6775 	  if (TREE_CHAIN (init) == NULL_TREE
6776 	      && char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (type)))
6777 	      && TREE_CODE (tree_strip_any_location_wrapper (val))
6778 		 == STRING_CST)
6779 	    /* If the list has a single element and it's a string literal,
6780 	       then it's the initializer for the array as a whole.  */
6781 	    init = val;
6782 	  else
6783 	    {
6784 	      init = build_constructor_from_list (init_list_type_node, init);
6785 	      CONSTRUCTOR_IS_DIRECT_INIT (init) = true;
6786 	      CONSTRUCTOR_IS_PAREN_INIT (init) = true;
6787 	    }
6788 	}
6789       else if (TREE_CODE (init) == TREE_LIST
6790 	       && TREE_TYPE (init) != unknown_type_node
6791 	       && !MAYBE_CLASS_TYPE_P (type))
6792 	{
6793 	  gcc_assert (TREE_CODE (decl) != RESULT_DECL);
6794 
6795 	  /* We get here with code like `int a (2);' */
6796 	  init = build_x_compound_expr_from_list (init, ELK_INIT,
6797 						  tf_warning_or_error);
6798 	}
6799 
6800       /* If DECL has an array type without a specific bound, deduce the
6801 	 array size from the initializer.  */
6802       maybe_deduce_size_from_array_init (decl, init);
6803       type = TREE_TYPE (decl);
6804       if (type == error_mark_node)
6805 	return NULL_TREE;
6806 
6807       if (((type_build_ctor_call (type) || CLASS_TYPE_P (type))
6808 	   && !(flags & LOOKUP_ALREADY_DIGESTED)
6809 	   && !(init && BRACE_ENCLOSED_INITIALIZER_P (init)
6810 		&& CP_AGGREGATE_TYPE_P (type)
6811 		&& (CLASS_TYPE_P (type)
6812 		    || !TYPE_NEEDS_CONSTRUCTING (type)
6813 		    || type_has_extended_temps (type))))
6814 	  || (DECL_DECOMPOSITION_P (decl) && TREE_CODE (type) == ARRAY_TYPE))
6815 	{
6816 	  init_code = build_aggr_init_full_exprs (decl, init, flags);
6817 
6818 	  /* A constructor call is a non-trivial initializer even if
6819 	     it isn't explicitly written.  */
6820 	  if (TREE_SIDE_EFFECTS (init_code))
6821 	    DECL_NONTRIVIALLY_INITIALIZED_P (decl) = true;
6822 
6823 	  /* If this is a constexpr initializer, expand_default_init will
6824 	     have returned an INIT_EXPR rather than a CALL_EXPR.  In that
6825 	     case, pull the initializer back out and pass it down into
6826 	     store_init_value.  */
6827 	  while (TREE_CODE (init_code) == EXPR_STMT
6828 		 || TREE_CODE (init_code) == CONVERT_EXPR)
6829 	    init_code = TREE_OPERAND (init_code, 0);
6830 	  if (TREE_CODE (init_code) == INIT_EXPR)
6831 	    {
6832 	      /* In C++20, the call to build_aggr_init could have created
6833 		 an INIT_EXPR with a CONSTRUCTOR as the RHS to handle
6834 		 A(1, 2).  */
6835 	      init = TREE_OPERAND (init_code, 1);
6836 	      init_code = NULL_TREE;
6837 	      /* Don't call digest_init; it's unnecessary and will complain
6838 		 about aggregate initialization of non-aggregate classes.  */
6839 	      flags |= LOOKUP_ALREADY_DIGESTED;
6840 	    }
6841 	  else if (DECL_DECLARED_CONSTEXPR_P (decl)
6842 		   || (flags & LOOKUP_CONSTINIT))
6843 	    {
6844 	      /* Declared constexpr or constinit, but no suitable initializer;
6845 		 massage init appropriately so we can pass it into
6846 		 store_init_value for the error.  */
6847 	      if (CLASS_TYPE_P (type)
6848 		  && (!init || TREE_CODE (init) == TREE_LIST))
6849 		{
6850 		  init = build_functional_cast (input_location, type,
6851 						init, tf_none);
6852 		  if (TREE_CODE (init) == TARGET_EXPR)
6853 		    TARGET_EXPR_DIRECT_INIT_P (init) = true;
6854 		}
6855 	      init_code = NULL_TREE;
6856 	    }
6857 	  else
6858 	    init = NULL_TREE;
6859 	}
6860 
6861       if (init && TREE_CODE (init) != TREE_VEC)
6862 	{
6863 	  /* In aggregate initialization of a variable, each element
6864 	     initialization is a full-expression because there is no
6865 	     enclosing expression.  */
6866 	  gcc_assert (stmts_are_full_exprs_p ());
6867 
6868 	  init_code = store_init_value (decl, init, cleanups, flags);
6869 
6870 	  if (DECL_INITIAL (decl)
6871 	      && TREE_CODE (DECL_INITIAL (decl)) == CONSTRUCTOR
6872 	      && !vec_safe_is_empty (CONSTRUCTOR_ELTS (DECL_INITIAL (decl))))
6873 	    {
6874 	      tree elt = CONSTRUCTOR_ELTS (DECL_INITIAL (decl))->last ().value;
6875 	      if (TREE_CODE (TREE_TYPE (elt)) == ARRAY_TYPE
6876 		  && TYPE_SIZE (TREE_TYPE (elt)) == NULL_TREE)
6877 		cp_complete_array_type (&TREE_TYPE (elt), elt, false);
6878 	    }
6879 
6880 	  if (pedantic && TREE_CODE (type) == ARRAY_TYPE
6881 	      && DECL_INITIAL (decl)
6882 	      && TREE_CODE (DECL_INITIAL (decl)) == STRING_CST
6883 	      && PAREN_STRING_LITERAL_P (DECL_INITIAL (decl)))
6884 	    warning_at (cp_expr_loc_or_loc (DECL_INITIAL (decl),
6885 					 DECL_SOURCE_LOCATION (decl)),
6886 			0, "array %qD initialized by parenthesized "
6887 			"string literal %qE",
6888 			decl, DECL_INITIAL (decl));
6889 	  init = NULL_TREE;
6890 	}
6891     }
6892   else
6893     {
6894       if (CLASS_TYPE_P (core_type = strip_array_types (type))
6895 	  && (CLASSTYPE_READONLY_FIELDS_NEED_INIT (core_type)
6896 	      || CLASSTYPE_REF_FIELDS_NEED_INIT (core_type)))
6897 	diagnose_uninitialized_cst_or_ref_member (core_type, /*using_new=*/false,
6898 						  /*complain=*/true);
6899 
6900       check_for_uninitialized_const_var (decl, /*constexpr_context_p=*/false,
6901 					 tf_warning_or_error);
6902     }
6903 
6904   if (init && init != error_mark_node)
6905     init_code = build2 (INIT_EXPR, type, decl, init);
6906 
6907   if (init_code)
6908     {
6909       /* We might have set these in cp_finish_decl.  */
6910       DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = false;
6911       TREE_CONSTANT (decl) = false;
6912     }
6913 
6914   if (init_code
6915       && DECL_IN_AGGR_P (decl)
6916       && DECL_INITIALIZED_IN_CLASS_P (decl))
6917     {
6918       static int explained = 0;
6919 
6920       if (cxx_dialect < cxx11)
6921 	error ("initializer invalid for static member with constructor");
6922       else if (cxx_dialect < cxx17)
6923 	error ("non-constant in-class initialization invalid for static "
6924 	       "member %qD", decl);
6925       else
6926 	error ("non-constant in-class initialization invalid for non-inline "
6927 	       "static member %qD", decl);
6928       if (!explained)
6929 	{
6930 	  inform (input_location,
6931 		  "(an out of class initialization is required)");
6932 	  explained = 1;
6933 	}
6934       return NULL_TREE;
6935     }
6936 
6937   return init_code;
6938 }
6939 
6940 /* If DECL is not a local variable, give it RTL.  */
6941 
6942 static void
make_rtl_for_nonlocal_decl(tree decl,tree init,const char * asmspec)6943 make_rtl_for_nonlocal_decl (tree decl, tree init, const char* asmspec)
6944 {
6945   int toplev = toplevel_bindings_p ();
6946   int defer_p;
6947 
6948   /* Set the DECL_ASSEMBLER_NAME for the object.  */
6949   if (asmspec)
6950     {
6951       /* The `register' keyword, when used together with an
6952 	 asm-specification, indicates that the variable should be
6953 	 placed in a particular register.  */
6954       if (VAR_P (decl) && DECL_REGISTER (decl))
6955 	{
6956 	  set_user_assembler_name (decl, asmspec);
6957 	  DECL_HARD_REGISTER (decl) = 1;
6958 	}
6959       else
6960 	{
6961 	  if (TREE_CODE (decl) == FUNCTION_DECL
6962 	      && fndecl_built_in_p (decl, BUILT_IN_NORMAL))
6963 	    set_builtin_user_assembler_name (decl, asmspec);
6964 	  set_user_assembler_name (decl, asmspec);
6965 	}
6966     }
6967 
6968   /* Handle non-variables up front.  */
6969   if (!VAR_P (decl))
6970     {
6971       rest_of_decl_compilation (decl, toplev, at_eof);
6972       return;
6973     }
6974 
6975   /* If we see a class member here, it should be a static data
6976      member.  */
6977   if (DECL_LANG_SPECIFIC (decl) && DECL_IN_AGGR_P (decl))
6978     {
6979       gcc_assert (TREE_STATIC (decl));
6980       /* An in-class declaration of a static data member should be
6981 	 external; it is only a declaration, and not a definition.  */
6982       if (init == NULL_TREE)
6983 	gcc_assert (DECL_EXTERNAL (decl)
6984 		    || !TREE_PUBLIC (decl));
6985     }
6986 
6987   /* We don't create any RTL for local variables.  */
6988   if (DECL_FUNCTION_SCOPE_P (decl) && !TREE_STATIC (decl))
6989     return;
6990 
6991   /* We defer emission of local statics until the corresponding
6992      DECL_EXPR is expanded.  But with constexpr its function might never
6993      be expanded, so go ahead and tell cgraph about the variable now.  */
6994   defer_p = ((DECL_FUNCTION_SCOPE_P (decl)
6995 	      && !var_in_maybe_constexpr_fn (decl))
6996 	     || DECL_VIRTUAL_P (decl));
6997 
6998   /* Defer template instantiations.  */
6999   if (DECL_LANG_SPECIFIC (decl)
7000       && DECL_IMPLICIT_INSTANTIATION (decl))
7001     defer_p = 1;
7002 
7003   /* If we're not deferring, go ahead and assemble the variable.  */
7004   if (!defer_p)
7005     rest_of_decl_compilation (decl, toplev, at_eof);
7006 }
7007 
7008 /* walk_tree helper for wrap_temporary_cleanups, below.  */
7009 
7010 static tree
wrap_cleanups_r(tree * stmt_p,int * walk_subtrees,void * data)7011 wrap_cleanups_r (tree *stmt_p, int *walk_subtrees, void *data)
7012 {
7013   /* Stop at types or full-expression boundaries.  */
7014   if (TYPE_P (*stmt_p)
7015       || TREE_CODE (*stmt_p) == CLEANUP_POINT_EXPR)
7016     {
7017       *walk_subtrees = 0;
7018       return NULL_TREE;
7019     }
7020 
7021   if (TREE_CODE (*stmt_p) == TARGET_EXPR)
7022     {
7023       tree guard = (tree)data;
7024       tree tcleanup = TARGET_EXPR_CLEANUP (*stmt_p);
7025 
7026       tcleanup = build2 (TRY_CATCH_EXPR, void_type_node, tcleanup, guard);
7027       /* Tell honor_protect_cleanup_actions to handle this as a separate
7028 	 cleanup.  */
7029       TRY_CATCH_IS_CLEANUP (tcleanup) = 1;
7030 
7031       TARGET_EXPR_CLEANUP (*stmt_p) = tcleanup;
7032     }
7033 
7034   return NULL_TREE;
7035 }
7036 
7037 /* We're initializing a local variable which has a cleanup GUARD.  If there
7038    are any temporaries used in the initializer INIT of this variable, we
7039    need to wrap their cleanups with TRY_CATCH_EXPR (, GUARD) so that the
7040    variable will be cleaned up properly if one of them throws.
7041 
7042    Unfortunately, there's no way to express this properly in terms of
7043    nesting, as the regions for the temporaries overlap the region for the
7044    variable itself; if there are two temporaries, the variable needs to be
7045    the first thing destroyed if either of them throws.  However, we only
7046    want to run the variable's cleanup if it actually got constructed.  So
7047    we need to guard the temporary cleanups with the variable's cleanup if
7048    they are run on the normal path, but not if they are run on the
7049    exceptional path.  We implement this by telling
7050    honor_protect_cleanup_actions to strip the variable cleanup from the
7051    exceptional path.  */
7052 
7053 static void
wrap_temporary_cleanups(tree init,tree guard)7054 wrap_temporary_cleanups (tree init, tree guard)
7055 {
7056   cp_walk_tree_without_duplicates (&init, wrap_cleanups_r, (void *)guard);
7057 }
7058 
7059 /* Generate code to initialize DECL (a local variable).  */
7060 
7061 static void
initialize_local_var(tree decl,tree init)7062 initialize_local_var (tree decl, tree init)
7063 {
7064   tree type = TREE_TYPE (decl);
7065   tree cleanup;
7066   int already_used;
7067 
7068   gcc_assert (VAR_P (decl)
7069 	      || TREE_CODE (decl) == RESULT_DECL);
7070   gcc_assert (!TREE_STATIC (decl));
7071 
7072   if (DECL_SIZE (decl) == NULL_TREE)
7073     {
7074       /* If we used it already as memory, it must stay in memory.  */
7075       DECL_INITIAL (decl) = NULL_TREE;
7076       TREE_ADDRESSABLE (decl) = TREE_USED (decl);
7077       return;
7078     }
7079 
7080   if (type == error_mark_node)
7081     return;
7082 
7083   /* Compute and store the initial value.  */
7084   already_used = TREE_USED (decl) || TREE_USED (type);
7085   if (TREE_USED (type))
7086     DECL_READ_P (decl) = 1;
7087 
7088   /* Generate a cleanup, if necessary.  */
7089   cleanup = cxx_maybe_build_cleanup (decl, tf_warning_or_error);
7090 
7091   /* Perform the initialization.  */
7092   if (init)
7093     {
7094       tree rinit = (TREE_CODE (init) == INIT_EXPR
7095 		    ? TREE_OPERAND (init, 1) : NULL_TREE);
7096       if (rinit && !TREE_SIDE_EFFECTS (rinit))
7097 	{
7098 	  /* Stick simple initializers in DECL_INITIAL so that
7099 	     -Wno-init-self works (c++/34772).  */
7100 	  gcc_assert (TREE_OPERAND (init, 0) == decl);
7101 	  DECL_INITIAL (decl) = rinit;
7102 
7103 	  if (warn_init_self && TYPE_REF_P (type))
7104 	    {
7105 	      STRIP_NOPS (rinit);
7106 	      if (rinit == decl)
7107 		warning_at (DECL_SOURCE_LOCATION (decl),
7108 			    OPT_Winit_self,
7109 			    "reference %qD is initialized with itself", decl);
7110 	    }
7111 	}
7112       else
7113 	{
7114 	  int saved_stmts_are_full_exprs_p;
7115 
7116 	  /* If we're only initializing a single object, guard the
7117 	     destructors of any temporaries used in its initializer with
7118 	     its destructor.  This isn't right for arrays because each
7119 	     element initialization is a full-expression.  */
7120 	  if (cleanup && TREE_CODE (type) != ARRAY_TYPE)
7121 	    wrap_temporary_cleanups (init, cleanup);
7122 
7123 	  gcc_assert (building_stmt_list_p ());
7124 	  saved_stmts_are_full_exprs_p = stmts_are_full_exprs_p ();
7125 	  current_stmt_tree ()->stmts_are_full_exprs_p = 1;
7126 	  finish_expr_stmt (init);
7127 	  current_stmt_tree ()->stmts_are_full_exprs_p =
7128 	    saved_stmts_are_full_exprs_p;
7129 	}
7130     }
7131 
7132   /* Set this to 0 so we can tell whether an aggregate which was
7133      initialized was ever used.  Don't do this if it has a
7134      destructor, so we don't complain about the 'resource
7135      allocation is initialization' idiom.  Now set
7136      attribute((unused)) on types so decls of that type will be
7137      marked used. (see TREE_USED, above.)  */
7138   if (TYPE_NEEDS_CONSTRUCTING (type)
7139       && ! already_used
7140       && TYPE_HAS_TRIVIAL_DESTRUCTOR (type)
7141       && DECL_NAME (decl))
7142     TREE_USED (decl) = 0;
7143   else if (already_used)
7144     TREE_USED (decl) = 1;
7145 
7146   if (cleanup)
7147     finish_decl_cleanup (decl, cleanup);
7148 }
7149 
7150 /* DECL is a VAR_DECL for a compiler-generated variable with static
7151    storage duration (like a virtual table) whose initializer is a
7152    compile-time constant.  Initialize the variable and provide it to the
7153    back end.  */
7154 
7155 void
initialize_artificial_var(tree decl,vec<constructor_elt,va_gc> * v)7156 initialize_artificial_var (tree decl, vec<constructor_elt, va_gc> *v)
7157 {
7158   tree init;
7159   gcc_assert (DECL_ARTIFICIAL (decl));
7160   init = build_constructor (TREE_TYPE (decl), v);
7161   gcc_assert (TREE_CODE (init) == CONSTRUCTOR);
7162   DECL_INITIAL (decl) = init;
7163   DECL_INITIALIZED_P (decl) = 1;
7164   /* Mark the decl as constexpr so that we can access its content
7165      at compile time.  */
7166   DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = true;
7167   DECL_DECLARED_CONSTEXPR_P (decl) = true;
7168   determine_visibility (decl);
7169   layout_var_decl (decl);
7170   maybe_commonize_var (decl);
7171   make_rtl_for_nonlocal_decl (decl, init, /*asmspec=*/NULL);
7172 }
7173 
7174 /* INIT is the initializer for a variable, as represented by the
7175    parser.  Returns true iff INIT is value-dependent.  */
7176 
7177 static bool
value_dependent_init_p(tree init)7178 value_dependent_init_p (tree init)
7179 {
7180   if (TREE_CODE (init) == TREE_LIST)
7181     /* A parenthesized initializer, e.g.: int i (3, 2); ? */
7182     return any_value_dependent_elements_p (init);
7183   else if (TREE_CODE (init) == CONSTRUCTOR)
7184   /* A brace-enclosed initializer, e.g.: int i = { 3 }; ? */
7185     {
7186       if (dependent_type_p (TREE_TYPE (init)))
7187 	return true;
7188 
7189       vec<constructor_elt, va_gc> *elts;
7190       size_t nelts;
7191       size_t i;
7192 
7193       elts = CONSTRUCTOR_ELTS (init);
7194       nelts = vec_safe_length (elts);
7195       for (i = 0; i < nelts; ++i)
7196 	if (value_dependent_init_p ((*elts)[i].value))
7197 	  return true;
7198     }
7199   else
7200     /* It must be a simple expression, e.g., int i = 3;  */
7201     return value_dependent_expression_p (init);
7202 
7203   return false;
7204 }
7205 
7206 // Returns true if a DECL is VAR_DECL with the concept specifier.
7207 static inline bool
is_concept_var(tree decl)7208 is_concept_var (tree decl)
7209 {
7210   return (VAR_P (decl)
7211 	  // Not all variables have DECL_LANG_SPECIFIC.
7212           && DECL_LANG_SPECIFIC (decl)
7213           && DECL_DECLARED_CONCEPT_P (decl));
7214 }
7215 
7216 /* A helper function to be called via walk_tree.  If any label exists
7217    under *TP, it is (going to be) forced.  Set has_forced_label_in_static.  */
7218 
7219 static tree
notice_forced_label_r(tree * tp,int * walk_subtrees,void *)7220 notice_forced_label_r (tree *tp, int *walk_subtrees, void *)
7221 {
7222   if (TYPE_P (*tp))
7223     *walk_subtrees = 0;
7224   if (TREE_CODE (*tp) == LABEL_DECL)
7225     cfun->has_forced_label_in_static = 1;
7226   return NULL_TREE;
7227 }
7228 
7229 /* Return true if DECL has either a trivial destructor, or for C++2A
7230    is constexpr and has a constexpr destructor.  */
7231 
7232 static bool
decl_maybe_constant_destruction(tree decl,tree type)7233 decl_maybe_constant_destruction (tree decl, tree type)
7234 {
7235   return (TYPE_HAS_TRIVIAL_DESTRUCTOR (type)
7236 	  || (cxx_dialect >= cxx2a
7237 	      && VAR_P (decl)
7238 	      && DECL_DECLARED_CONSTEXPR_P (decl)
7239 	      && type_has_constexpr_destructor (strip_array_types (type))));
7240 }
7241 
7242 static tree declare_simd_adjust_this (tree *, int *, void *);
7243 
7244 /* Helper function of omp_declare_variant_finalize.  Finalize one
7245    "omp declare variant base" attribute.  Return true if it should be
7246    removed.  */
7247 
7248 static bool
omp_declare_variant_finalize_one(tree decl,tree attr)7249 omp_declare_variant_finalize_one (tree decl, tree attr)
7250 {
7251   if (TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
7252     {
7253       walk_tree (&TREE_VALUE (TREE_VALUE (attr)), declare_simd_adjust_this,
7254 		 DECL_ARGUMENTS (decl), NULL);
7255       walk_tree (&TREE_PURPOSE (TREE_VALUE (attr)), declare_simd_adjust_this,
7256 		 DECL_ARGUMENTS (decl), NULL);
7257     }
7258 
7259   tree ctx = TREE_VALUE (TREE_VALUE (attr));
7260   tree simd = omp_get_context_selector (ctx, "construct", "simd");
7261   if (simd)
7262     {
7263       TREE_VALUE (simd)
7264 	= c_omp_declare_simd_clauses_to_numbers (DECL_ARGUMENTS (decl),
7265 						 TREE_VALUE (simd));
7266       /* FIXME, adjusting simd args unimplemented.  */
7267       return true;
7268     }
7269 
7270   tree chain = TREE_CHAIN (TREE_VALUE (attr));
7271   location_t varid_loc
7272     = cp_expr_loc_or_input_loc (TREE_PURPOSE (TREE_CHAIN (chain)));
7273   location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
7274   cp_id_kind idk = (cp_id_kind) tree_to_uhwi (TREE_VALUE (chain));
7275   tree variant = TREE_PURPOSE (TREE_VALUE (attr));
7276 
7277   location_t save_loc = input_location;
7278   input_location = varid_loc;
7279 
7280   releasing_vec args;
7281   tree parm = DECL_ARGUMENTS (decl);
7282   if (TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
7283     parm = DECL_CHAIN (parm);
7284   for (; parm; parm = DECL_CHAIN (parm))
7285     if (type_dependent_expression_p (parm))
7286       vec_safe_push (args, build_constructor (TREE_TYPE (parm), NULL));
7287     else if (MAYBE_CLASS_TYPE_P (TREE_TYPE (parm)))
7288       vec_safe_push (args, build_local_temp (TREE_TYPE (parm)));
7289     else
7290       vec_safe_push (args, build_zero_cst (TREE_TYPE (parm)));
7291 
7292   bool koenig_p = false;
7293   if (idk == CP_ID_KIND_UNQUALIFIED || idk == CP_ID_KIND_TEMPLATE_ID)
7294     {
7295       if (identifier_p (variant)
7296 	  /* In C++2A, we may need to perform ADL for a template
7297 	     name.  */
7298 	  || (TREE_CODE (variant) == TEMPLATE_ID_EXPR
7299 	      && identifier_p (TREE_OPERAND (variant, 0))))
7300 	{
7301 	  if (!args->is_empty ())
7302 	    {
7303 	      koenig_p = true;
7304 	      if (!any_type_dependent_arguments_p (args))
7305 		variant = perform_koenig_lookup (variant, args,
7306 						 tf_warning_or_error);
7307 	    }
7308 	  else
7309 	    variant = unqualified_fn_lookup_error (variant);
7310 	}
7311       else if (!args->is_empty () && is_overloaded_fn (variant))
7312 	{
7313 	  tree fn = get_first_fn (variant);
7314 	  fn = STRIP_TEMPLATE (fn);
7315 	  if (!((TREE_CODE (fn) == USING_DECL && DECL_DEPENDENT_P (fn))
7316 		 || DECL_FUNCTION_MEMBER_P (fn)
7317 		 || DECL_LOCAL_FUNCTION_P (fn)))
7318 	    {
7319 	      koenig_p = true;
7320 	      if (!any_type_dependent_arguments_p (args))
7321 		variant = perform_koenig_lookup (variant, args,
7322 						 tf_warning_or_error);
7323 	    }
7324 	}
7325     }
7326 
7327   if (idk == CP_ID_KIND_QUALIFIED)
7328     variant = finish_call_expr (variant, &args, /*disallow_virtual=*/true,
7329 				koenig_p, tf_warning_or_error);
7330   else
7331     variant = finish_call_expr (variant, &args, /*disallow_virtual=*/false,
7332 				koenig_p, tf_warning_or_error);
7333   if (variant == error_mark_node && !processing_template_decl)
7334     return true;
7335 
7336   variant = cp_get_callee_fndecl_nofold (variant);
7337   input_location = save_loc;
7338 
7339   if (variant)
7340     {
7341       const char *varname = IDENTIFIER_POINTER (DECL_NAME (variant));
7342       if (!comptypes (TREE_TYPE (decl), TREE_TYPE (variant), 0))
7343 	{
7344 	  error_at (varid_loc, "variant %qD and base %qD have incompatible "
7345 			       "types", variant, decl);
7346 	  return true;
7347 	}
7348       if (fndecl_built_in_p (variant)
7349 	  && (strncmp (varname, "__builtin_", strlen ("__builtin_")) == 0
7350 	      || strncmp (varname, "__sync_", strlen ("__sync_")) == 0
7351 	      || strncmp (varname, "__atomic_", strlen ("__atomic_")) == 0))
7352 	{
7353 	  error_at (varid_loc, "variant %qD is a built-in", variant);
7354 	  return true;
7355 	}
7356       else
7357 	{
7358 	  tree construct = omp_get_context_selector (ctx, "construct", NULL);
7359 	  c_omp_mark_declare_variant (match_loc, variant, construct);
7360 	  if (!omp_context_selector_matches (ctx))
7361 	    return true;
7362 	  TREE_PURPOSE (TREE_VALUE (attr)) = variant;
7363 	}
7364     }
7365   else if (!processing_template_decl)
7366     {
7367       error_at (varid_loc, "could not find variant declaration");
7368       return true;
7369     }
7370 
7371   return false;
7372 }
7373 
7374 /* Helper function, finish up "omp declare variant base" attribute
7375    now that there is a DECL.  ATTR is the first "omp declare variant base"
7376    attribute.  */
7377 
7378 void
omp_declare_variant_finalize(tree decl,tree attr)7379 omp_declare_variant_finalize (tree decl, tree attr)
7380 {
7381   size_t attr_len = strlen ("omp declare variant base");
7382   tree *list = &DECL_ATTRIBUTES (decl);
7383   bool remove_all = false;
7384   location_t match_loc = DECL_SOURCE_LOCATION (decl);
7385   if (TREE_CHAIN (TREE_VALUE (attr))
7386       && TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr)))
7387       && EXPR_HAS_LOCATION (TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr)))))
7388     match_loc = EXPR_LOCATION (TREE_PURPOSE (TREE_CHAIN (TREE_VALUE (attr))));
7389   if (DECL_CONSTRUCTOR_P (decl))
7390     {
7391       error_at (match_loc, "%<declare variant%> on constructor %qD", decl);
7392       remove_all = true;
7393     }
7394   else if (DECL_DESTRUCTOR_P (decl))
7395     {
7396       error_at (match_loc, "%<declare variant%> on destructor %qD", decl);
7397       remove_all = true;
7398     }
7399   else if (DECL_DEFAULTED_FN (decl))
7400     {
7401       error_at (match_loc, "%<declare variant%> on defaulted %qD", decl);
7402       remove_all = true;
7403     }
7404   else if (DECL_DELETED_FN (decl))
7405     {
7406       error_at (match_loc, "%<declare variant%> on deleted %qD", decl);
7407       remove_all = true;
7408     }
7409   else if (DECL_VIRTUAL_P (decl))
7410     {
7411       error_at (match_loc, "%<declare variant%> on virtual %qD", decl);
7412       remove_all = true;
7413     }
7414   /* This loop is like private_lookup_attribute, except that it works
7415      with tree * rather than tree, as we might want to remove the
7416      attributes that are diagnosed as errorneous.  */
7417   while (*list)
7418     {
7419       tree attr = get_attribute_name (*list);
7420       size_t ident_len = IDENTIFIER_LENGTH (attr);
7421       if (cmp_attribs ("omp declare variant base", attr_len,
7422 		       IDENTIFIER_POINTER (attr), ident_len))
7423 	{
7424 	  if (remove_all || omp_declare_variant_finalize_one (decl, *list))
7425 	    {
7426 	      *list = TREE_CHAIN (*list);
7427 	      continue;
7428 	    }
7429 	}
7430       list = &TREE_CHAIN (*list);
7431     }
7432 }
7433 
7434 /* Finish processing of a declaration;
7435    install its line number and initial value.
7436    If the length of an array type is not known before,
7437    it must be determined now, from the initial value, or it is an error.
7438 
7439    INIT is the initializer (if any) for DECL.  If INIT_CONST_EXPR_P is
7440    true, then INIT is an integral constant expression.
7441 
7442    FLAGS is LOOKUP_ONLYCONVERTING if the = init syntax was used, else 0
7443    if the (init) syntax was used.  */
7444 
7445 void
cp_finish_decl(tree decl,tree init,bool init_const_expr_p,tree asmspec_tree,int flags)7446 cp_finish_decl (tree decl, tree init, bool init_const_expr_p,
7447 		tree asmspec_tree, int flags)
7448 {
7449   tree type;
7450   vec<tree, va_gc> *cleanups = NULL;
7451   const char *asmspec = NULL;
7452   int was_readonly = 0;
7453   bool var_definition_p = false;
7454   tree auto_node;
7455 
7456   if (decl == error_mark_node)
7457     return;
7458   else if (! decl)
7459     {
7460       if (init)
7461 	error ("assignment (not initialization) in declaration");
7462       return;
7463     }
7464 
7465   gcc_assert (TREE_CODE (decl) != RESULT_DECL);
7466   /* Parameters are handled by store_parm_decls, not cp_finish_decl.  */
7467   gcc_assert (TREE_CODE (decl) != PARM_DECL);
7468 
7469   type = TREE_TYPE (decl);
7470   if (type == error_mark_node)
7471     return;
7472 
7473   /* Warn about register storage specifiers except when in GNU global
7474      or local register variable extension.  */
7475   if (VAR_P (decl) && DECL_REGISTER (decl) && asmspec_tree == NULL_TREE)
7476     {
7477       if (cxx_dialect >= cxx17)
7478 	pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
7479 		 "ISO C++17 does not allow %<register%> storage "
7480 		 "class specifier");
7481       else
7482 	warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
7483 		    "%<register%> storage class specifier used");
7484     }
7485 
7486   /* If a name was specified, get the string.  */
7487   if (at_namespace_scope_p ())
7488     asmspec_tree = maybe_apply_renaming_pragma (decl, asmspec_tree);
7489   if (asmspec_tree && asmspec_tree != error_mark_node)
7490     asmspec = TREE_STRING_POINTER (asmspec_tree);
7491 
7492   bool in_class_decl
7493     = (current_class_type
7494        && CP_DECL_CONTEXT (decl) == current_class_type
7495        && TYPE_BEING_DEFINED (current_class_type)
7496        && !CLASSTYPE_TEMPLATE_INSTANTIATION (current_class_type));
7497 
7498   if (in_class_decl
7499       && (DECL_INITIAL (decl) || init))
7500     DECL_INITIALIZED_IN_CLASS_P (decl) = 1;
7501 
7502   /* Do auto deduction unless decl is a function or an uninstantiated
7503      template specialization.  */
7504   if (TREE_CODE (decl) != FUNCTION_DECL
7505       && !(init == NULL_TREE
7506 	   && DECL_LANG_SPECIFIC (decl)
7507 	   && DECL_TEMPLATE_INSTANTIATION (decl)
7508 	   && !DECL_TEMPLATE_INSTANTIATED (decl))
7509       && (auto_node = type_uses_auto (type)))
7510     {
7511       tree d_init;
7512       if (init == NULL_TREE)
7513 	gcc_assert (CLASS_PLACEHOLDER_TEMPLATE (auto_node));
7514       d_init = init;
7515       if (d_init)
7516 	{
7517 	  if (TREE_CODE (d_init) == TREE_LIST
7518 	      && !CLASS_PLACEHOLDER_TEMPLATE (auto_node))
7519 	    d_init = build_x_compound_expr_from_list (d_init, ELK_INIT,
7520 						      tf_warning_or_error);
7521 	  d_init = resolve_nondeduced_context (d_init, tf_warning_or_error);
7522 	}
7523       enum auto_deduction_context adc = adc_variable_type;
7524       if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
7525 	adc = adc_decomp_type;
7526       type = TREE_TYPE (decl) = do_auto_deduction (type, d_init, auto_node,
7527 						   tf_warning_or_error, adc,
7528 						   NULL_TREE, flags);
7529       if (type == error_mark_node)
7530 	return;
7531       if (TREE_CODE (type) == FUNCTION_TYPE)
7532 	{
7533 	  error ("initializer for %<decltype(auto) %D%> has function type; "
7534 		 "did you forget the %<()%>?", decl);
7535 	  TREE_TYPE (decl) = error_mark_node;
7536 	  return;
7537 	}
7538       cp_apply_type_quals_to_decl (cp_type_quals (type), decl);
7539     }
7540 
7541   if (ensure_literal_type_for_constexpr_object (decl) == error_mark_node)
7542     {
7543       DECL_DECLARED_CONSTEXPR_P (decl) = 0;
7544       if (VAR_P (decl) && DECL_CLASS_SCOPE_P (decl))
7545 	{
7546 	  init = NULL_TREE;
7547 	  DECL_EXTERNAL (decl) = 1;
7548 	}
7549     }
7550 
7551   if (VAR_P (decl)
7552       && DECL_CLASS_SCOPE_P (decl)
7553       && verify_type_context (DECL_SOURCE_LOCATION (decl),
7554 			      TCTX_STATIC_STORAGE, type)
7555       && DECL_INITIALIZED_IN_CLASS_P (decl))
7556     check_static_variable_definition (decl, type);
7557 
7558   if (init && TREE_CODE (decl) == FUNCTION_DECL)
7559     {
7560       tree clone;
7561       if (init == ridpointers[(int)RID_DELETE])
7562 	{
7563 	  /* FIXME check this is 1st decl.  */
7564 	  DECL_DELETED_FN (decl) = 1;
7565 	  DECL_DECLARED_INLINE_P (decl) = 1;
7566 	  DECL_INITIAL (decl) = error_mark_node;
7567 	  FOR_EACH_CLONE (clone, decl)
7568 	    {
7569 	      DECL_DELETED_FN (clone) = 1;
7570 	      DECL_DECLARED_INLINE_P (clone) = 1;
7571 	      DECL_INITIAL (clone) = error_mark_node;
7572 	    }
7573 	  init = NULL_TREE;
7574 	}
7575       else if (init == ridpointers[(int)RID_DEFAULT])
7576 	{
7577 	  if (defaultable_fn_check (decl))
7578 	    DECL_DEFAULTED_FN (decl) = 1;
7579 	  else
7580 	    DECL_INITIAL (decl) = NULL_TREE;
7581 	}
7582     }
7583 
7584   if (init && VAR_P (decl))
7585     {
7586       DECL_NONTRIVIALLY_INITIALIZED_P (decl) = 1;
7587       /* If DECL is a reference, then we want to know whether init is a
7588 	 reference constant; init_const_expr_p as passed tells us whether
7589 	 it's an rvalue constant.  */
7590       if (TYPE_REF_P (type))
7591 	init_const_expr_p = potential_constant_expression (init);
7592       if (init_const_expr_p)
7593 	{
7594 	  /* Set these flags now for templates.  We'll update the flags in
7595 	     store_init_value for instantiations.  */
7596 	  DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl) = 1;
7597 	  if (decl_maybe_constant_var_p (decl)
7598 	      /* FIXME setting TREE_CONSTANT on refs breaks the back end.  */
7599 	      && !TYPE_REF_P (type))
7600 	    TREE_CONSTANT (decl) = 1;
7601 	}
7602     }
7603 
7604   if (flag_openmp
7605       && TREE_CODE (decl) == FUNCTION_DECL
7606       /* #pragma omp declare variant on methods handled in finish_struct
7607 	 instead.  */
7608       && (!DECL_NONSTATIC_MEMBER_FUNCTION_P (decl)
7609 	  || COMPLETE_TYPE_P (DECL_CONTEXT (decl))))
7610     if (tree attr = lookup_attribute ("omp declare variant base",
7611 				      DECL_ATTRIBUTES (decl)))
7612       omp_declare_variant_finalize (decl, attr);
7613 
7614   if (processing_template_decl)
7615     {
7616       bool type_dependent_p;
7617 
7618       /* Add this declaration to the statement-tree.  */
7619       if (at_function_scope_p ())
7620 	add_decl_expr (decl);
7621 
7622       type_dependent_p = dependent_type_p (type);
7623 
7624       if (check_for_bare_parameter_packs (init))
7625 	{
7626 	  init = NULL_TREE;
7627 	  DECL_INITIAL (decl) = NULL_TREE;
7628 	}
7629 
7630       /* Handle `constinit' on variable templates.  */
7631       if (flags & LOOKUP_CONSTINIT)
7632 	TINFO_VAR_DECLARED_CONSTINIT (DECL_TEMPLATE_INFO (decl)) = true;
7633 
7634       /* Generally, initializers in templates are expanded when the
7635 	 template is instantiated.  But, if DECL is a variable constant
7636 	 then it can be used in future constant expressions, so its value
7637 	 must be available. */
7638 
7639       bool dep_init = false;
7640 
7641       if (!VAR_P (decl) || type_dependent_p)
7642 	/* We can't do anything if the decl has dependent type.  */;
7643       else if (!init && is_concept_var (decl))
7644 	{
7645 	  error ("variable concept has no initializer");
7646 	  init = boolean_true_node;
7647 	}
7648       else if (init
7649 	       && init_const_expr_p
7650 	       && !TYPE_REF_P (type)
7651 	       && decl_maybe_constant_var_p (decl)
7652 	       && !(dep_init = value_dependent_init_p (init)))
7653 	{
7654 	  /* This variable seems to be a non-dependent constant, so process
7655 	     its initializer.  If check_initializer returns non-null the
7656 	     initialization wasn't constant after all.  */
7657 	  tree init_code;
7658 	  cleanups = make_tree_vector ();
7659 	  init_code = check_initializer (decl, init, flags, &cleanups);
7660 	  if (init_code == NULL_TREE)
7661 	    init = NULL_TREE;
7662 	  release_tree_vector (cleanups);
7663 	}
7664       else
7665 	{
7666 	  gcc_assert (!DECL_PRETTY_FUNCTION_P (decl));
7667 	  /* Deduce array size even if the initializer is dependent.  */
7668 	  maybe_deduce_size_from_array_init (decl, init);
7669 	  /* And complain about multiple initializers.  */
7670 	  if (init && TREE_CODE (init) == TREE_LIST && TREE_CHAIN (init)
7671 	      && !MAYBE_CLASS_TYPE_P (type))
7672 	    init = build_x_compound_expr_from_list (init, ELK_INIT,
7673 						    tf_warning_or_error);
7674 	}
7675 
7676       if (init)
7677 	DECL_INITIAL (decl) = init;
7678 
7679       if (dep_init)
7680 	{
7681 	  retrofit_lang_decl (decl);
7682 	  SET_DECL_DEPENDENT_INIT_P (decl, true);
7683 	}
7684 
7685       if (VAR_P (decl) && DECL_REGISTER (decl) && asmspec)
7686 	{
7687 	  set_user_assembler_name (decl, asmspec);
7688 	  DECL_HARD_REGISTER (decl) = 1;
7689 	}
7690       return;
7691     }
7692 
7693   /* Just store non-static data member initializers for later.  */
7694   if (init && TREE_CODE (decl) == FIELD_DECL)
7695     DECL_INITIAL (decl) = init;
7696 
7697   /* Take care of TYPE_DECLs up front.  */
7698   if (TREE_CODE (decl) == TYPE_DECL)
7699     {
7700       if (type != error_mark_node
7701 	  && MAYBE_CLASS_TYPE_P (type) && DECL_NAME (decl))
7702 	{
7703 	  if (TREE_TYPE (DECL_NAME (decl)) && TREE_TYPE (decl) != type)
7704 	    warning (0, "shadowing previous type declaration of %q#D", decl);
7705 	  set_identifier_type_value (DECL_NAME (decl), decl);
7706 	}
7707 
7708       /* If we have installed this as the canonical typedef for this
7709 	 type, and that type has not been defined yet, delay emitting
7710 	 the debug information for it, as we will emit it later.  */
7711       if (TYPE_MAIN_DECL (TREE_TYPE (decl)) == decl
7712 	  && !COMPLETE_TYPE_P (TREE_TYPE (decl)))
7713 	TYPE_DECL_SUPPRESS_DEBUG (decl) = 1;
7714 
7715       rest_of_decl_compilation (decl, DECL_FILE_SCOPE_P (decl),
7716 				at_eof);
7717       return;
7718     }
7719 
7720   /* A reference will be modified here, as it is initialized.  */
7721   if (! DECL_EXTERNAL (decl)
7722       && TREE_READONLY (decl)
7723       && TYPE_REF_P (type))
7724     {
7725       was_readonly = 1;
7726       TREE_READONLY (decl) = 0;
7727     }
7728 
7729   /* This needs to happen before extend_ref_init_temps.  */
7730   if (VAR_OR_FUNCTION_DECL_P (decl))
7731     {
7732       if (VAR_P (decl))
7733 	maybe_commonize_var (decl);
7734       determine_visibility (decl);
7735     }
7736 
7737   if (VAR_P (decl))
7738     {
7739       duration_kind dk = decl_storage_duration (decl);
7740       /* [dcl.constinit]/1 "The constinit specifier shall be applied
7741 	 only to a declaration of a variable with static or thread storage
7742 	 duration."  */
7743       if ((flags & LOOKUP_CONSTINIT)
7744 	  && !(dk == dk_thread || dk == dk_static))
7745 	{
7746 	  error_at (DECL_SOURCE_LOCATION (decl),
7747 		    "%<constinit%> can only be applied to a variable with "
7748 		    "static or thread storage duration");
7749 	  return;
7750 	}
7751 
7752       /* If this is a local variable that will need a mangled name,
7753 	 register it now.  We must do this before processing the
7754 	 initializer for the variable, since the initialization might
7755 	 require a guard variable, and since the mangled name of the
7756 	 guard variable will depend on the mangled name of this
7757 	 variable.  */
7758       if (DECL_FUNCTION_SCOPE_P (decl)
7759 	  && TREE_STATIC (decl)
7760 	  && !DECL_ARTIFICIAL (decl))
7761 	{
7762 	  /* The variable holding an anonymous union will have had its
7763 	     discriminator set in finish_anon_union, after which it's
7764 	     NAME will have been cleared.  */
7765 	  if (DECL_NAME (decl))
7766 	    determine_local_discriminator (decl);
7767 	  /* Normally has_forced_label_in_static is set during GIMPLE
7768 	     lowering, but [cd]tors are never actually compiled directly.
7769 	     We need to set this early so we can deal with the label
7770 	     address extension.  */
7771 	  if ((DECL_CONSTRUCTOR_P (current_function_decl)
7772 	       || DECL_DESTRUCTOR_P (current_function_decl))
7773 	      && init)
7774 	    {
7775 	      walk_tree (&init, notice_forced_label_r, NULL, NULL);
7776 	      add_local_decl (cfun, decl);
7777 	    }
7778 	  /* And make sure it's in the symbol table for
7779 	     c_parse_final_cleanups to find.  */
7780 	  varpool_node::get_create (decl);
7781 	}
7782 
7783       /* Convert the initializer to the type of DECL, if we have not
7784 	 already initialized DECL.  */
7785       if (!DECL_INITIALIZED_P (decl)
7786 	  /* If !DECL_EXTERNAL then DECL is being defined.  In the
7787 	     case of a static data member initialized inside the
7788 	     class-specifier, there can be an initializer even if DECL
7789 	     is *not* defined.  */
7790 	  && (!DECL_EXTERNAL (decl) || init))
7791 	{
7792 	  cleanups = make_tree_vector ();
7793 	  init = check_initializer (decl, init, flags, &cleanups);
7794 
7795 	  /* Handle:
7796 
7797 	     [dcl.init]
7798 
7799 	     The memory occupied by any object of static storage
7800 	     duration is zero-initialized at program startup before
7801 	     any other initialization takes place.
7802 
7803 	     We cannot create an appropriate initializer until after
7804 	     the type of DECL is finalized.  If DECL_INITIAL is set,
7805 	     then the DECL is statically initialized, and any
7806 	     necessary zero-initialization has already been performed.  */
7807 	  if (TREE_STATIC (decl) && !DECL_INITIAL (decl))
7808 	    DECL_INITIAL (decl) = build_zero_init (TREE_TYPE (decl),
7809 						   /*nelts=*/NULL_TREE,
7810 						   /*static_storage_p=*/true);
7811 	  /* Remember that the initialization for this variable has
7812 	     taken place.  */
7813 	  DECL_INITIALIZED_P (decl) = 1;
7814 	  /* This declaration is the definition of this variable,
7815 	     unless we are initializing a static data member within
7816 	     the class specifier.  */
7817 	  if (!DECL_EXTERNAL (decl))
7818 	    var_definition_p = true;
7819 	}
7820       /* If the variable has an array type, lay out the type, even if
7821 	 there is no initializer.  It is valid to index through the
7822 	 array, and we must get TYPE_ALIGN set correctly on the array
7823 	 type.  */
7824       else if (TREE_CODE (type) == ARRAY_TYPE)
7825 	layout_type (type);
7826 
7827       if (TREE_STATIC (decl)
7828 	  && !at_function_scope_p ()
7829 	  && current_function_decl == NULL)
7830 	/* So decl is a global variable or a static member of a
7831 	   non local class. Record the types it uses
7832 	   so that we can decide later to emit debug info for them.  */
7833 	record_types_used_by_current_var_decl (decl);
7834     }
7835 
7836   /* Add this declaration to the statement-tree.  This needs to happen
7837      after the call to check_initializer so that the DECL_EXPR for a
7838      reference temp is added before the DECL_EXPR for the reference itself.  */
7839   if (DECL_FUNCTION_SCOPE_P (decl))
7840     {
7841       /* If we're building a variable sized type, and we might be
7842 	 reachable other than via the top of the current binding
7843 	 level, then create a new BIND_EXPR so that we deallocate
7844 	 the object at the right time.  */
7845       if (VAR_P (decl)
7846 	  && DECL_SIZE (decl)
7847 	  && !TREE_CONSTANT (DECL_SIZE (decl))
7848 	  && STATEMENT_LIST_HAS_LABEL (cur_stmt_list))
7849 	{
7850 	  tree bind;
7851 	  bind = build3 (BIND_EXPR, void_type_node, NULL, NULL, NULL);
7852 	  TREE_SIDE_EFFECTS (bind) = 1;
7853 	  add_stmt (bind);
7854 	  BIND_EXPR_BODY (bind) = push_stmt_list ();
7855 	}
7856       add_decl_expr (decl);
7857     }
7858 
7859   /* Let the middle end know about variables and functions -- but not
7860      static data members in uninstantiated class templates.  */
7861   if (VAR_OR_FUNCTION_DECL_P (decl))
7862     {
7863       if (VAR_P (decl))
7864 	{
7865 	  layout_var_decl (decl);
7866 	  if (!flag_weak)
7867 	    /* Check again now that we have an initializer.  */
7868 	    maybe_commonize_var (decl);
7869 	  /* A class-scope constexpr variable with an out-of-class declaration.
7870 	     C++17 makes them implicitly inline, but still force it out.  */
7871 	  if (DECL_INLINE_VAR_P (decl)
7872 	      && !DECL_VAR_DECLARED_INLINE_P (decl)
7873 	      && !DECL_TEMPLATE_INSTANTIATION (decl)
7874 	      && !in_class_decl)
7875 	    mark_needed (decl);
7876 	}
7877 
7878       if (var_definition_p
7879 	  /* With -fmerge-all-constants, gimplify_init_constructor
7880 	     might add TREE_STATIC to the variable.  */
7881 	  && (TREE_STATIC (decl) || flag_merge_constants >= 2))
7882 	{
7883 	  /* If a TREE_READONLY variable needs initialization
7884 	     at runtime, it is no longer readonly and we need to
7885 	     avoid MEM_READONLY_P being set on RTL created for it.  */
7886 	  if (init)
7887 	    {
7888 	      if (TREE_READONLY (decl))
7889 		TREE_READONLY (decl) = 0;
7890 	      was_readonly = 0;
7891 	    }
7892 	  else if (was_readonly)
7893 	    TREE_READONLY (decl) = 1;
7894 
7895 	  /* Likewise if it needs destruction.  */
7896 	  if (!decl_maybe_constant_destruction (decl, type))
7897 	    TREE_READONLY (decl) = 0;
7898 	}
7899 
7900       make_rtl_for_nonlocal_decl (decl, init, asmspec);
7901 
7902       /* Check for abstractness of the type. Notice that there is no
7903 	 need to strip array types here since the check for those types
7904 	 is already done within create_array_type_for_decl.  */
7905       abstract_virtuals_error (decl, type);
7906 
7907       if (TREE_TYPE (decl) == error_mark_node)
7908 	/* No initialization required.  */
7909 	;
7910       else if (TREE_CODE (decl) == FUNCTION_DECL)
7911 	{
7912 	  if (init)
7913 	    {
7914 	      if (init == ridpointers[(int)RID_DEFAULT])
7915 		{
7916 		  /* An out-of-class default definition is defined at
7917 		     the point where it is explicitly defaulted.  */
7918 		  if (DECL_DELETED_FN (decl))
7919 		    maybe_explain_implicit_delete (decl);
7920 		  else if (DECL_INITIAL (decl) == error_mark_node)
7921 		    synthesize_method (decl);
7922 		}
7923 	      else
7924 		error_at (cp_expr_loc_or_loc (init,
7925 					      DECL_SOURCE_LOCATION (decl)),
7926 			  "function %q#D is initialized like a variable",
7927 			  decl);
7928 	    }
7929 	  /* else no initialization required.  */
7930 	}
7931       else if (DECL_EXTERNAL (decl)
7932 	       && ! (DECL_LANG_SPECIFIC (decl)
7933 		     && DECL_NOT_REALLY_EXTERN (decl)))
7934 	{
7935 	  /* check_initializer will have done any constant initialization.  */
7936 	}
7937       /* A variable definition.  */
7938       else if (DECL_FUNCTION_SCOPE_P (decl) && !TREE_STATIC (decl))
7939 	/* Initialize the local variable.  */
7940 	initialize_local_var (decl, init);
7941 
7942       /* If a variable is defined, and then a subsequent
7943 	 definition with external linkage is encountered, we will
7944 	 get here twice for the same variable.  We want to avoid
7945 	 calling expand_static_init more than once.  For variables
7946 	 that are not static data members, we can call
7947 	 expand_static_init only when we actually process the
7948 	 initializer.  It is not legal to redeclare a static data
7949 	 member, so this issue does not arise in that case.  */
7950       else if (var_definition_p && TREE_STATIC (decl))
7951 	expand_static_init (decl, init);
7952     }
7953 
7954   /* If a CLEANUP_STMT was created to destroy a temporary bound to a
7955      reference, insert it in the statement-tree now.  */
7956   if (cleanups)
7957     {
7958       unsigned i; tree t;
7959       FOR_EACH_VEC_ELT (*cleanups, i, t)
7960 	push_cleanup (decl, t, false);
7961       release_tree_vector (cleanups);
7962     }
7963 
7964   if (was_readonly)
7965     TREE_READONLY (decl) = 1;
7966 
7967   if (flag_openmp
7968       && VAR_P (decl)
7969       && lookup_attribute ("omp declare target implicit",
7970 			   DECL_ATTRIBUTES (decl)))
7971     {
7972       DECL_ATTRIBUTES (decl)
7973 	= remove_attribute ("omp declare target implicit",
7974 			    DECL_ATTRIBUTES (decl));
7975       complete_type (TREE_TYPE (decl));
7976       if (!cp_omp_mappable_type (TREE_TYPE (decl)))
7977 	{
7978 	  error ("%q+D in declare target directive does not have mappable"
7979 		 " type", decl);
7980 	  cp_omp_emit_unmappable_type_notes (TREE_TYPE (decl));
7981 	}
7982       else if (!lookup_attribute ("omp declare target",
7983 				  DECL_ATTRIBUTES (decl))
7984 	       && !lookup_attribute ("omp declare target link",
7985 				     DECL_ATTRIBUTES (decl)))
7986 	DECL_ATTRIBUTES (decl)
7987 	  = tree_cons (get_identifier ("omp declare target"),
7988 		       NULL_TREE, DECL_ATTRIBUTES (decl));
7989     }
7990 
7991   invoke_plugin_callbacks (PLUGIN_FINISH_DECL, decl);
7992 }
7993 
7994 /* For class TYPE return itself or some its bases that contain
7995    any direct non-static data members.  Return error_mark_node if an
7996    error has been diagnosed.  */
7997 
7998 static tree
find_decomp_class_base(location_t loc,tree type,tree ret)7999 find_decomp_class_base (location_t loc, tree type, tree ret)
8000 {
8001   bool member_seen = false;
8002   for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
8003     if (TREE_CODE (field) != FIELD_DECL
8004 	|| DECL_ARTIFICIAL (field)
8005 	|| DECL_UNNAMED_BIT_FIELD (field))
8006       continue;
8007     else if (ret)
8008       return type;
8009     else if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
8010       {
8011 	if (TREE_CODE (TREE_TYPE (field)) == RECORD_TYPE)
8012 	  error_at (loc, "cannot decompose class type %qT because it has an "
8013 			 "anonymous struct member", type);
8014 	else
8015 	  error_at (loc, "cannot decompose class type %qT because it has an "
8016 			 "anonymous union member", type);
8017 	inform (DECL_SOURCE_LOCATION (field), "declared here");
8018 	return error_mark_node;
8019       }
8020     else if (!accessible_p (type, field, true))
8021       {
8022 	error_at (loc, "cannot decompose inaccessible member %qD of %qT",
8023 		  field, type);
8024 	inform (DECL_SOURCE_LOCATION (field),
8025 		TREE_PRIVATE (field)
8026 		? G_("declared private here")
8027 		: G_("declared protected here"));
8028 	return error_mark_node;
8029       }
8030     else
8031       member_seen = true;
8032 
8033   tree base_binfo, binfo;
8034   tree orig_ret = ret;
8035   int i;
8036   if (member_seen)
8037     ret = type;
8038   for (binfo = TYPE_BINFO (type), i = 0;
8039        BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
8040     {
8041       tree t = find_decomp_class_base (loc, TREE_TYPE (base_binfo), ret);
8042       if (t == error_mark_node)
8043 	return error_mark_node;
8044       if (t != NULL_TREE && t != ret)
8045 	{
8046 	  if (ret == type)
8047 	    {
8048 	      error_at (loc, "cannot decompose class type %qT: both it and "
8049 			     "its base class %qT have non-static data members",
8050 			type, t);
8051 	      return error_mark_node;
8052 	    }
8053 	  else if (orig_ret != NULL_TREE)
8054 	    return t;
8055 	  else if (ret != NULL_TREE)
8056 	    {
8057 	      error_at (loc, "cannot decompose class type %qT: its base "
8058 			     "classes %qT and %qT have non-static data "
8059 			     "members", type, ret, t);
8060 	      return error_mark_node;
8061 	    }
8062 	  else
8063 	    ret = t;
8064 	}
8065     }
8066   return ret;
8067 }
8068 
8069 /* Return std::tuple_size<TYPE>::value.  */
8070 
8071 static tree
get_tuple_size(tree type)8072 get_tuple_size (tree type)
8073 {
8074   tree args = make_tree_vec (1);
8075   TREE_VEC_ELT (args, 0) = type;
8076   tree inst = lookup_template_class (tuple_size_identifier, args,
8077 				     /*in_decl*/NULL_TREE,
8078 				     /*context*/std_node,
8079 				     /*entering_scope*/false, tf_none);
8080   inst = complete_type (inst);
8081   if (inst == error_mark_node || !COMPLETE_TYPE_P (inst))
8082     return NULL_TREE;
8083   tree val = lookup_qualified_name (inst, value_identifier,
8084 				    /*type*/false, /*complain*/false);
8085   if (TREE_CODE (val) == VAR_DECL || TREE_CODE (val) == CONST_DECL)
8086     val = maybe_constant_value (val);
8087   if (TREE_CODE (val) == INTEGER_CST)
8088     return val;
8089   else
8090     return error_mark_node;
8091 }
8092 
8093 /* Return std::tuple_element<I,TYPE>::type.  */
8094 
8095 static tree
get_tuple_element_type(tree type,unsigned i)8096 get_tuple_element_type (tree type, unsigned i)
8097 {
8098   tree args = make_tree_vec (2);
8099   TREE_VEC_ELT (args, 0) = build_int_cst (integer_type_node, i);
8100   TREE_VEC_ELT (args, 1) = type;
8101   tree inst = lookup_template_class (tuple_element_identifier, args,
8102 				     /*in_decl*/NULL_TREE,
8103 				     /*context*/std_node,
8104 				     /*entering_scope*/false,
8105 				     tf_warning_or_error);
8106   return make_typename_type (inst, type_identifier,
8107 			     none_type, tf_warning_or_error);
8108 }
8109 
8110 /* Return e.get<i>() or get<i>(e).  */
8111 
8112 static tree
get_tuple_decomp_init(tree decl,unsigned i)8113 get_tuple_decomp_init (tree decl, unsigned i)
8114 {
8115   tree targs = make_tree_vec (1);
8116   TREE_VEC_ELT (targs, 0) = build_int_cst (integer_type_node, i);
8117 
8118   tree etype = TREE_TYPE (decl);
8119   tree e = convert_from_reference (decl);
8120 
8121   /* [The id-expression] e is an lvalue if the type of the entity e is an
8122      lvalue reference and an xvalue otherwise.  */
8123   if (!TYPE_REF_P (etype)
8124       || TYPE_REF_IS_RVALUE (etype))
8125     e = move (e);
8126 
8127   tree fns = lookup_qualified_name (TREE_TYPE (e), get__identifier,
8128 				    /*type*/false, /*complain*/false);
8129   bool use_member_get = false;
8130 
8131   /* To use a member get, member lookup must find at least one
8132      declaration that is a function template
8133      whose first template parameter is a non-type parameter.  */
8134   for (lkp_iterator iter (MAYBE_BASELINK_FUNCTIONS (fns)); iter; ++iter)
8135     {
8136       tree fn = *iter;
8137       if (TREE_CODE (fn) == TEMPLATE_DECL)
8138 	{
8139 	  tree tparms = DECL_TEMPLATE_PARMS (fn);
8140 	  tree parm = TREE_VEC_ELT (INNERMOST_TEMPLATE_PARMS (tparms), 0);
8141 	  if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
8142 	    {
8143 	      use_member_get = true;
8144 	      break;
8145 	    }
8146 	}
8147     }
8148 
8149   if (use_member_get)
8150     {
8151       fns = lookup_template_function (fns, targs);
8152       return build_new_method_call (e, fns, /*args*/NULL,
8153 				    /*path*/NULL_TREE, LOOKUP_NORMAL,
8154 				    /*fn_p*/NULL, tf_warning_or_error);
8155     }
8156   else
8157     {
8158       releasing_vec args (make_tree_vector_single (e));
8159       fns = lookup_template_function (get__identifier, targs);
8160       fns = perform_koenig_lookup (fns, args, tf_warning_or_error);
8161       return finish_call_expr (fns, &args, /*novirt*/false,
8162 			       /*koenig*/true, tf_warning_or_error);
8163     }
8164 }
8165 
8166 /* It's impossible to recover the decltype of a tuple decomposition variable
8167    based on the actual type of the variable, so store it in a hash table.  */
8168 
8169 static GTY((cache)) decl_tree_cache_map *decomp_type_table;
8170 
8171 tree
lookup_decomp_type(tree v)8172 lookup_decomp_type (tree v)
8173 {
8174   return *decomp_type_table->get (v);
8175 }
8176 
8177 /* Mangle a decomposition declaration if needed.  Arguments like
8178    in cp_finish_decomp.  */
8179 
8180 void
cp_maybe_mangle_decomp(tree decl,tree first,unsigned int count)8181 cp_maybe_mangle_decomp (tree decl, tree first, unsigned int count)
8182 {
8183   if (!processing_template_decl
8184       && !error_operand_p (decl)
8185       && TREE_STATIC (decl))
8186     {
8187       auto_vec<tree, 16> v;
8188       v.safe_grow (count);
8189       tree d = first;
8190       for (unsigned int i = 0; i < count; i++, d = DECL_CHAIN (d))
8191 	v[count - i - 1] = d;
8192       SET_DECL_ASSEMBLER_NAME (decl, mangle_decomp (decl, v));
8193       maybe_apply_pragma_weak (decl);
8194     }
8195 }
8196 
8197 /* Finish a decomposition declaration.  DECL is the underlying declaration
8198    "e", FIRST is the head of a chain of decls for the individual identifiers
8199    chained through DECL_CHAIN in reverse order and COUNT is the number of
8200    those decls.  */
8201 
8202 void
cp_finish_decomp(tree decl,tree first,unsigned int count)8203 cp_finish_decomp (tree decl, tree first, unsigned int count)
8204 {
8205   if (error_operand_p (decl))
8206     {
8207      error_out:
8208       while (count--)
8209 	{
8210 	  TREE_TYPE (first) = error_mark_node;
8211 	  if (DECL_HAS_VALUE_EXPR_P (first))
8212 	    {
8213 	      SET_DECL_VALUE_EXPR (first, NULL_TREE);
8214 	      DECL_HAS_VALUE_EXPR_P (first) = 0;
8215 	    }
8216 	  first = DECL_CHAIN (first);
8217 	}
8218       if (DECL_P (decl) && DECL_NAMESPACE_SCOPE_P (decl))
8219 	SET_DECL_ASSEMBLER_NAME (decl, get_identifier ("<decomp>"));
8220       return;
8221     }
8222 
8223   location_t loc = DECL_SOURCE_LOCATION (decl);
8224   if (type_dependent_expression_p (decl)
8225       /* This happens for range for when not in templates.
8226 	 Still add the DECL_VALUE_EXPRs for later processing.  */
8227       || (!processing_template_decl
8228 	  && type_uses_auto (TREE_TYPE (decl))))
8229     {
8230       for (unsigned int i = 0; i < count; i++)
8231 	{
8232 	  if (!DECL_HAS_VALUE_EXPR_P (first))
8233 	    {
8234 	      tree v = build_nt (ARRAY_REF, decl,
8235 				 size_int (count - i - 1),
8236 				 NULL_TREE, NULL_TREE);
8237 	      SET_DECL_VALUE_EXPR (first, v);
8238 	      DECL_HAS_VALUE_EXPR_P (first) = 1;
8239 	    }
8240 	  if (processing_template_decl)
8241 	    fit_decomposition_lang_decl (first, decl);
8242 	  first = DECL_CHAIN (first);
8243 	}
8244       return;
8245     }
8246 
8247   auto_vec<tree, 16> v;
8248   v.safe_grow (count);
8249   tree d = first;
8250   for (unsigned int i = 0; i < count; i++, d = DECL_CHAIN (d))
8251     {
8252       v[count - i - 1] = d;
8253       fit_decomposition_lang_decl (d, decl);
8254     }
8255 
8256   tree type = TREE_TYPE (decl);
8257   tree dexp = decl;
8258 
8259   if (TYPE_REF_P (type))
8260     {
8261       dexp = convert_from_reference (dexp);
8262       type = complete_type (TREE_TYPE (type));
8263       if (type == error_mark_node)
8264 	goto error_out;
8265       if (!COMPLETE_TYPE_P (type))
8266 	{
8267 	  error_at (loc, "structured binding refers to incomplete type %qT",
8268 		    type);
8269 	  goto error_out;
8270 	}
8271     }
8272 
8273   tree eltype = NULL_TREE;
8274   unsigned HOST_WIDE_INT eltscnt = 0;
8275   if (TREE_CODE (type) == ARRAY_TYPE)
8276     {
8277       tree nelts;
8278       nelts = array_type_nelts_top (type);
8279       if (nelts == error_mark_node)
8280 	goto error_out;
8281       if (!tree_fits_uhwi_p (nelts))
8282 	{
8283 	  error_at (loc, "cannot decompose variable length array %qT", type);
8284 	  goto error_out;
8285 	}
8286       eltscnt = tree_to_uhwi (nelts);
8287       if (count != eltscnt)
8288 	{
8289        cnt_mismatch:
8290 	  if (count > eltscnt)
8291 	    error_n (loc, count,
8292 		     "%u name provided for structured binding",
8293 		     "%u names provided for structured binding", count);
8294 	  else
8295 	    error_n (loc, count,
8296 		     "only %u name provided for structured binding",
8297 		     "only %u names provided for structured binding", count);
8298 	  inform_n (loc, eltscnt,
8299 		    "while %qT decomposes into %wu element",
8300 		    "while %qT decomposes into %wu elements",
8301 		    type, eltscnt);
8302 	  goto error_out;
8303 	}
8304       eltype = TREE_TYPE (type);
8305       for (unsigned int i = 0; i < count; i++)
8306 	{
8307 	  TREE_TYPE (v[i]) = eltype;
8308 	  layout_decl (v[i], 0);
8309 	  if (processing_template_decl)
8310 	    continue;
8311 	  tree t = unshare_expr (dexp);
8312 	  t = build4_loc (DECL_SOURCE_LOCATION (v[i]), ARRAY_REF,
8313 			  eltype, t, size_int (i), NULL_TREE,
8314 			  NULL_TREE);
8315 	  SET_DECL_VALUE_EXPR (v[i], t);
8316 	  DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
8317 	}
8318     }
8319   /* 2 GNU extensions.  */
8320   else if (TREE_CODE (type) == COMPLEX_TYPE)
8321     {
8322       eltscnt = 2;
8323       if (count != eltscnt)
8324 	goto cnt_mismatch;
8325       eltype = cp_build_qualified_type (TREE_TYPE (type), TYPE_QUALS (type));
8326       for (unsigned int i = 0; i < count; i++)
8327 	{
8328 	  TREE_TYPE (v[i]) = eltype;
8329 	  layout_decl (v[i], 0);
8330 	  if (processing_template_decl)
8331 	    continue;
8332 	  tree t = unshare_expr (dexp);
8333 	  t = build1_loc (DECL_SOURCE_LOCATION (v[i]),
8334 			  i ? IMAGPART_EXPR : REALPART_EXPR, eltype,
8335 			  t);
8336 	  SET_DECL_VALUE_EXPR (v[i], t);
8337 	  DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
8338 	}
8339     }
8340   else if (TREE_CODE (type) == VECTOR_TYPE)
8341     {
8342       if (!TYPE_VECTOR_SUBPARTS (type).is_constant (&eltscnt))
8343 	{
8344 	  error_at (loc, "cannot decompose variable length vector %qT", type);
8345 	  goto error_out;
8346 	}
8347       if (count != eltscnt)
8348 	goto cnt_mismatch;
8349       eltype = cp_build_qualified_type (TREE_TYPE (type), TYPE_QUALS (type));
8350       for (unsigned int i = 0; i < count; i++)
8351 	{
8352 	  TREE_TYPE (v[i]) = eltype;
8353 	  layout_decl (v[i], 0);
8354 	  if (processing_template_decl)
8355 	    continue;
8356 	  tree t = unshare_expr (dexp);
8357 	  convert_vector_to_array_for_subscript (DECL_SOURCE_LOCATION (v[i]),
8358 						 &t, size_int (i));
8359 	  t = build4_loc (DECL_SOURCE_LOCATION (v[i]), ARRAY_REF,
8360 			  eltype, t, size_int (i), NULL_TREE,
8361 			  NULL_TREE);
8362 	  SET_DECL_VALUE_EXPR (v[i], t);
8363 	  DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
8364 	}
8365     }
8366   else if (tree tsize = get_tuple_size (type))
8367     {
8368       if (tsize == error_mark_node)
8369 	{
8370 	  error_at (loc, "%<std::tuple_size<%T>::value%> is not an integral "
8371 			 "constant expression", type);
8372 	  goto error_out;
8373 	}
8374       if (!tree_fits_uhwi_p (tsize))
8375 	{
8376 	  error_n (loc, count,
8377 		   "%u name provided for structured binding",
8378 		   "%u names provided for structured binding", count);
8379 	  inform (loc, "while %qT decomposes into %E elements",
8380 		  type, tsize);
8381 	  goto error_out;
8382 	}
8383       eltscnt = tree_to_uhwi (tsize);
8384       if (count != eltscnt)
8385 	goto cnt_mismatch;
8386       int save_read = DECL_READ_P (decl);
8387       for (unsigned i = 0; i < count; ++i)
8388 	{
8389 	  location_t sloc = input_location;
8390 	  location_t dloc = DECL_SOURCE_LOCATION (v[i]);
8391 
8392 	  input_location = dloc;
8393 	  tree init = get_tuple_decomp_init (decl, i);
8394 	  tree eltype = (init == error_mark_node ? error_mark_node
8395 			 : get_tuple_element_type (type, i));
8396 	  input_location = sloc;
8397 
8398 	  if (VOID_TYPE_P (eltype))
8399 	    {
8400 	      error ("%<std::tuple_element<%u, %T>::type%> is %<void%>",
8401 		     i, type);
8402 	      eltype = error_mark_node;
8403 	    }
8404 	  if (init == error_mark_node || eltype == error_mark_node)
8405 	    {
8406 	      inform (dloc, "in initialization of structured binding "
8407 		      "variable %qD", v[i]);
8408 	      goto error_out;
8409 	    }
8410 	  /* Save the decltype away before reference collapse.  */
8411 	  hash_map_safe_put<hm_ggc> (decomp_type_table, v[i], eltype);
8412 	  eltype = cp_build_reference_type (eltype, !lvalue_p (init));
8413 	  TREE_TYPE (v[i]) = eltype;
8414 	  layout_decl (v[i], 0);
8415 	  if (DECL_HAS_VALUE_EXPR_P (v[i]))
8416 	    {
8417 	      /* In this case the names are variables, not just proxies.  */
8418 	      SET_DECL_VALUE_EXPR (v[i], NULL_TREE);
8419 	      DECL_HAS_VALUE_EXPR_P (v[i]) = 0;
8420 	    }
8421 	  if (!processing_template_decl)
8422 	    {
8423 	      copy_linkage (v[i], decl);
8424 	      cp_finish_decl (v[i], init, /*constexpr*/false,
8425 			      /*asm*/NULL_TREE, LOOKUP_NORMAL);
8426 	    }
8427 	}
8428       /* Ignore reads from the underlying decl performed during initialization
8429 	 of the individual variables.  If those will be read, we'll mark
8430 	 the underlying decl as read at that point.  */
8431       DECL_READ_P (decl) = save_read;
8432     }
8433   else if (TREE_CODE (type) == UNION_TYPE)
8434     {
8435       error_at (loc, "cannot decompose union type %qT", type);
8436       goto error_out;
8437     }
8438   else if (!CLASS_TYPE_P (type))
8439     {
8440       error_at (loc, "cannot decompose non-array non-class type %qT", type);
8441       goto error_out;
8442     }
8443   else if (LAMBDA_TYPE_P (type))
8444     {
8445       error_at (loc, "cannot decompose lambda closure type %qT", type);
8446       goto error_out;
8447     }
8448   else if (processing_template_decl && complete_type (type) == error_mark_node)
8449     goto error_out;
8450   else if (processing_template_decl && !COMPLETE_TYPE_P (type))
8451     pedwarn (loc, 0, "structured binding refers to incomplete class type %qT",
8452 	     type);
8453   else
8454     {
8455       tree btype = find_decomp_class_base (loc, type, NULL_TREE);
8456       if (btype == error_mark_node)
8457 	goto error_out;
8458       else if (btype == NULL_TREE)
8459 	{
8460 	  error_at (loc, "cannot decompose class type %qT without non-static "
8461 			 "data members", type);
8462 	  goto error_out;
8463 	}
8464       for (tree field = TYPE_FIELDS (btype); field; field = TREE_CHAIN (field))
8465 	if (TREE_CODE (field) != FIELD_DECL
8466 	    || DECL_ARTIFICIAL (field)
8467 	    || DECL_UNNAMED_BIT_FIELD (field))
8468 	  continue;
8469 	else
8470 	  eltscnt++;
8471       if (count != eltscnt)
8472 	goto cnt_mismatch;
8473       tree t = dexp;
8474       if (type != btype)
8475 	{
8476 	  t = convert_to_base (t, btype, /*check_access*/true,
8477 			       /*nonnull*/false, tf_warning_or_error);
8478 	  type = btype;
8479 	}
8480       unsigned int i = 0;
8481       for (tree field = TYPE_FIELDS (btype); field; field = TREE_CHAIN (field))
8482 	if (TREE_CODE (field) != FIELD_DECL
8483 	    || DECL_ARTIFICIAL (field)
8484 	    || DECL_UNNAMED_BIT_FIELD (field))
8485 	  continue;
8486 	else
8487 	  {
8488 	    tree tt = finish_non_static_data_member (field, unshare_expr (t),
8489 						     NULL_TREE);
8490 	    if (REFERENCE_REF_P (tt))
8491 	      tt = TREE_OPERAND (tt, 0);
8492 	    TREE_TYPE (v[i]) = TREE_TYPE (tt);
8493 	    layout_decl (v[i], 0);
8494 	    if (!processing_template_decl)
8495 	      {
8496 		SET_DECL_VALUE_EXPR (v[i], tt);
8497 		DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
8498 	      }
8499 	    i++;
8500 	  }
8501     }
8502   if (processing_template_decl)
8503     {
8504       for (unsigned int i = 0; i < count; i++)
8505 	if (!DECL_HAS_VALUE_EXPR_P (v[i]))
8506 	  {
8507 	    tree a = build_nt (ARRAY_REF, decl, size_int (i),
8508 			       NULL_TREE, NULL_TREE);
8509 	    SET_DECL_VALUE_EXPR (v[i], a);
8510 	    DECL_HAS_VALUE_EXPR_P (v[i]) = 1;
8511 	  }
8512     }
8513 }
8514 
8515 /* Returns a declaration for a VAR_DECL as if:
8516 
8517      extern "C" TYPE NAME;
8518 
8519    had been seen.  Used to create compiler-generated global
8520    variables.  */
8521 
8522 static tree
declare_global_var(tree name,tree type)8523 declare_global_var (tree name, tree type)
8524 {
8525   tree decl;
8526 
8527   push_to_top_level ();
8528   decl = build_decl (input_location, VAR_DECL, name, type);
8529   TREE_PUBLIC (decl) = 1;
8530   DECL_EXTERNAL (decl) = 1;
8531   DECL_ARTIFICIAL (decl) = 1;
8532   DECL_CONTEXT (decl) = FROB_CONTEXT (global_namespace);
8533   /* If the user has explicitly declared this variable (perhaps
8534      because the code we are compiling is part of a low-level runtime
8535      library), then it is possible that our declaration will be merged
8536      with theirs by pushdecl.  */
8537   decl = pushdecl (decl);
8538   cp_finish_decl (decl, NULL_TREE, false, NULL_TREE, 0);
8539   pop_from_top_level ();
8540 
8541   return decl;
8542 }
8543 
8544 /* Returns the type for the argument to "__cxa_atexit" (or "atexit",
8545    if "__cxa_atexit" is not being used) corresponding to the function
8546    to be called when the program exits.  */
8547 
8548 static tree
get_atexit_fn_ptr_type(void)8549 get_atexit_fn_ptr_type (void)
8550 {
8551   tree fn_type;
8552 
8553   if (!atexit_fn_ptr_type_node)
8554     {
8555       tree arg_type;
8556       if (flag_use_cxa_atexit
8557 	  && !targetm.cxx.use_atexit_for_cxa_atexit ())
8558 	/* The parameter to "__cxa_atexit" is "void (*)(void *)".  */
8559 	arg_type = ptr_type_node;
8560       else
8561 	/* The parameter to "atexit" is "void (*)(void)".  */
8562 	arg_type = NULL_TREE;
8563 
8564       fn_type = build_function_type_list (void_type_node,
8565 					  arg_type, NULL_TREE);
8566       atexit_fn_ptr_type_node = build_pointer_type (fn_type);
8567     }
8568 
8569   return atexit_fn_ptr_type_node;
8570 }
8571 
8572 /* Returns a pointer to the `atexit' function.  Note that if
8573    FLAG_USE_CXA_ATEXIT is nonzero, then this will actually be the new
8574    `__cxa_atexit' function specified in the IA64 C++ ABI.  */
8575 
8576 static tree
get_atexit_node(void)8577 get_atexit_node (void)
8578 {
8579   tree atexit_fndecl;
8580   tree fn_type;
8581   tree fn_ptr_type;
8582   const char *name;
8583   bool use_aeabi_atexit;
8584 
8585   if (atexit_node)
8586     return atexit_node;
8587 
8588   if (flag_use_cxa_atexit && !targetm.cxx.use_atexit_for_cxa_atexit ())
8589     {
8590       /* The declaration for `__cxa_atexit' is:
8591 
8592 	   int __cxa_atexit (void (*)(void *), void *, void *)
8593 
8594 	 We build up the argument types and then the function type
8595 	 itself.  */
8596       tree argtype0, argtype1, argtype2;
8597 
8598       use_aeabi_atexit = targetm.cxx.use_aeabi_atexit ();
8599       /* First, build the pointer-to-function type for the first
8600 	 argument.  */
8601       fn_ptr_type = get_atexit_fn_ptr_type ();
8602       /* Then, build the rest of the argument types.  */
8603       argtype2 = ptr_type_node;
8604       if (use_aeabi_atexit)
8605 	{
8606 	  argtype1 = fn_ptr_type;
8607 	  argtype0 = ptr_type_node;
8608 	}
8609       else
8610 	{
8611 	  argtype1 = ptr_type_node;
8612 	  argtype0 = fn_ptr_type;
8613 	}
8614       /* And the final __cxa_atexit type.  */
8615       fn_type = build_function_type_list (integer_type_node,
8616 					  argtype0, argtype1, argtype2,
8617 					  NULL_TREE);
8618       if (use_aeabi_atexit)
8619 	name = "__aeabi_atexit";
8620       else
8621 	name = "__cxa_atexit";
8622     }
8623   else
8624     {
8625       /* The declaration for `atexit' is:
8626 
8627 	   int atexit (void (*)());
8628 
8629 	 We build up the argument types and then the function type
8630 	 itself.  */
8631       fn_ptr_type = get_atexit_fn_ptr_type ();
8632       /* Build the final atexit type.  */
8633       fn_type = build_function_type_list (integer_type_node,
8634 					  fn_ptr_type, NULL_TREE);
8635       name = "atexit";
8636     }
8637 
8638   /* Now, build the function declaration.  */
8639   push_lang_context (lang_name_c);
8640   atexit_fndecl = build_library_fn_ptr (name, fn_type, ECF_LEAF | ECF_NOTHROW);
8641   mark_used (atexit_fndecl);
8642   pop_lang_context ();
8643   atexit_node = decay_conversion (atexit_fndecl, tf_warning_or_error);
8644 
8645   return atexit_node;
8646 }
8647 
8648 /* Like get_atexit_node, but for thread-local cleanups.  */
8649 
8650 static tree
get_thread_atexit_node(void)8651 get_thread_atexit_node (void)
8652 {
8653   /* The declaration for `__cxa_thread_atexit' is:
8654 
8655      int __cxa_thread_atexit (void (*)(void *), void *, void *) */
8656   tree fn_type = build_function_type_list (integer_type_node,
8657 					   get_atexit_fn_ptr_type (),
8658 					   ptr_type_node, ptr_type_node,
8659 					   NULL_TREE);
8660 
8661   /* Now, build the function declaration.  */
8662   tree atexit_fndecl = build_library_fn_ptr ("__cxa_thread_atexit", fn_type,
8663 					     ECF_LEAF | ECF_NOTHROW);
8664   return decay_conversion (atexit_fndecl, tf_warning_or_error);
8665 }
8666 
8667 /* Returns the __dso_handle VAR_DECL.  */
8668 
8669 static tree
get_dso_handle_node(void)8670 get_dso_handle_node (void)
8671 {
8672   if (dso_handle_node)
8673     return dso_handle_node;
8674 
8675   /* Declare the variable.  */
8676   dso_handle_node = declare_global_var (get_identifier ("__dso_handle"),
8677 					ptr_type_node);
8678 
8679 #ifdef HAVE_GAS_HIDDEN
8680   if (dso_handle_node != error_mark_node)
8681     {
8682       DECL_VISIBILITY (dso_handle_node) = VISIBILITY_HIDDEN;
8683       DECL_VISIBILITY_SPECIFIED (dso_handle_node) = 1;
8684     }
8685 #endif
8686 
8687   return dso_handle_node;
8688 }
8689 
8690 /* Begin a new function with internal linkage whose job will be simply
8691    to destroy some particular variable.  */
8692 
8693 static GTY(()) int start_cleanup_cnt;
8694 
8695 static tree
start_cleanup_fn(void)8696 start_cleanup_fn (void)
8697 {
8698   char name[32];
8699   tree fntype;
8700   tree fndecl;
8701   bool use_cxa_atexit = flag_use_cxa_atexit
8702 			&& !targetm.cxx.use_atexit_for_cxa_atexit ();
8703 
8704   push_to_top_level ();
8705 
8706   /* No need to mangle this.  */
8707   push_lang_context (lang_name_c);
8708 
8709   /* Build the name of the function.  */
8710   sprintf (name, "__tcf_%d", start_cleanup_cnt++);
8711   /* Build the function declaration.  */
8712   fntype = TREE_TYPE (get_atexit_fn_ptr_type ());
8713   fndecl = build_lang_decl (FUNCTION_DECL, get_identifier (name), fntype);
8714   /* It's a function with internal linkage, generated by the
8715      compiler.  */
8716   TREE_PUBLIC (fndecl) = 0;
8717   DECL_ARTIFICIAL (fndecl) = 1;
8718   /* Make the function `inline' so that it is only emitted if it is
8719      actually needed.  It is unlikely that it will be inlined, since
8720      it is only called via a function pointer, but we avoid unnecessary
8721      emissions this way.  */
8722   DECL_DECLARED_INLINE_P (fndecl) = 1;
8723   DECL_INTERFACE_KNOWN (fndecl) = 1;
8724   /* Build the parameter.  */
8725   if (use_cxa_atexit)
8726     {
8727       tree parmdecl = cp_build_parm_decl (fndecl, NULL_TREE, ptr_type_node);
8728       TREE_USED (parmdecl) = 1;
8729       DECL_READ_P (parmdecl) = 1;
8730       DECL_ARGUMENTS (fndecl) = parmdecl;
8731     }
8732 
8733   pushdecl (fndecl);
8734   start_preparsed_function (fndecl, NULL_TREE, SF_PRE_PARSED);
8735 
8736   pop_lang_context ();
8737 
8738   return current_function_decl;
8739 }
8740 
8741 /* Finish the cleanup function begun by start_cleanup_fn.  */
8742 
8743 static void
end_cleanup_fn(void)8744 end_cleanup_fn (void)
8745 {
8746   expand_or_defer_fn (finish_function (/*inline_p=*/false));
8747 
8748   pop_from_top_level ();
8749 }
8750 
8751 /* Generate code to handle the destruction of DECL, an object with
8752    static storage duration.  */
8753 
8754 tree
register_dtor_fn(tree decl)8755 register_dtor_fn (tree decl)
8756 {
8757   tree cleanup;
8758   tree addr;
8759   tree compound_stmt;
8760   tree fcall;
8761   tree type;
8762   bool ob_parm, dso_parm, use_dtor;
8763   tree arg0, arg1, arg2;
8764   tree atex_node;
8765 
8766   type = TREE_TYPE (decl);
8767   if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
8768     return void_node;
8769 
8770   if (decl_maybe_constant_destruction (decl, type)
8771       && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
8772     {
8773       cxx_maybe_build_cleanup (decl, tf_warning_or_error);
8774       return void_node;
8775     }
8776 
8777   /* If we're using "__cxa_atexit" (or "__cxa_thread_atexit" or
8778      "__aeabi_atexit"), and DECL is a class object, we can just pass the
8779      destructor to "__cxa_atexit"; we don't have to build a temporary
8780      function to do the cleanup.  */
8781   dso_parm = (flag_use_cxa_atexit
8782 	      && !targetm.cxx.use_atexit_for_cxa_atexit ());
8783   ob_parm = (CP_DECL_THREAD_LOCAL_P (decl) || dso_parm);
8784   use_dtor = ob_parm && CLASS_TYPE_P (type);
8785   if (use_dtor)
8786     {
8787       cleanup = get_class_binding (type, complete_dtor_identifier);
8788 
8789       /* Make sure it is accessible.  */
8790       perform_or_defer_access_check (TYPE_BINFO (type), cleanup, cleanup,
8791 				     tf_warning_or_error);
8792     }
8793   else
8794     {
8795       /* Call build_cleanup before we enter the anonymous function so
8796 	 that any access checks will be done relative to the current
8797 	 scope, rather than the scope of the anonymous function.  */
8798       build_cleanup (decl);
8799 
8800       /* Now start the function.  */
8801       cleanup = start_cleanup_fn ();
8802 
8803       /* Now, recompute the cleanup.  It may contain SAVE_EXPRs that refer
8804 	 to the original function, rather than the anonymous one.  That
8805 	 will make the back end think that nested functions are in use,
8806 	 which causes confusion.  */
8807       push_deferring_access_checks (dk_no_check);
8808       fcall = build_cleanup (decl);
8809       pop_deferring_access_checks ();
8810 
8811       /* Create the body of the anonymous function.  */
8812       compound_stmt = begin_compound_stmt (BCS_FN_BODY);
8813       finish_expr_stmt (fcall);
8814       finish_compound_stmt (compound_stmt);
8815       end_cleanup_fn ();
8816     }
8817 
8818   /* Call atexit with the cleanup function.  */
8819   mark_used (cleanup);
8820   cleanup = build_address (cleanup);
8821 
8822   if (CP_DECL_THREAD_LOCAL_P (decl))
8823     atex_node = get_thread_atexit_node ();
8824   else
8825     atex_node = get_atexit_node ();
8826 
8827   if (use_dtor)
8828     {
8829       /* We must convert CLEANUP to the type that "__cxa_atexit"
8830 	 expects.  */
8831       cleanup = build_nop (get_atexit_fn_ptr_type (), cleanup);
8832       /* "__cxa_atexit" will pass the address of DECL to the
8833 	 cleanup function.  */
8834       mark_used (decl);
8835       addr = build_address (decl);
8836       /* The declared type of the parameter to "__cxa_atexit" is
8837 	 "void *".  For plain "T*", we could just let the
8838 	 machinery in cp_build_function_call convert it -- but if the
8839 	 type is "cv-qualified T *", then we need to convert it
8840 	 before passing it in, to avoid spurious errors.  */
8841       addr = build_nop (ptr_type_node, addr);
8842     }
8843   else
8844     /* Since the cleanup functions we build ignore the address
8845        they're given, there's no reason to pass the actual address
8846        in, and, in general, it's cheaper to pass NULL than any
8847        other value.  */
8848     addr = null_pointer_node;
8849 
8850   if (dso_parm)
8851     arg2 = cp_build_addr_expr (get_dso_handle_node (),
8852 			       tf_warning_or_error);
8853   else if (ob_parm)
8854     /* Just pass NULL to the dso handle parm if we don't actually
8855        have a DSO handle on this target.  */
8856     arg2 = null_pointer_node;
8857   else
8858     arg2 = NULL_TREE;
8859 
8860   if (ob_parm)
8861     {
8862       if (!CP_DECL_THREAD_LOCAL_P (decl)
8863 	  && targetm.cxx.use_aeabi_atexit ())
8864 	{
8865 	  arg1 = cleanup;
8866 	  arg0 = addr;
8867 	}
8868       else
8869 	{
8870 	  arg1 = addr;
8871 	  arg0 = cleanup;
8872 	}
8873     }
8874   else
8875     {
8876       arg0 = cleanup;
8877       arg1 = NULL_TREE;
8878     }
8879   return cp_build_function_call_nary (atex_node, tf_warning_or_error,
8880 				      arg0, arg1, arg2, NULL_TREE);
8881 }
8882 
8883 /* DECL is a VAR_DECL with static storage duration.  INIT, if present,
8884    is its initializer.  Generate code to handle the construction
8885    and destruction of DECL.  */
8886 
8887 static void
expand_static_init(tree decl,tree init)8888 expand_static_init (tree decl, tree init)
8889 {
8890   gcc_assert (VAR_P (decl));
8891   gcc_assert (TREE_STATIC (decl));
8892 
8893   /* Some variables require no dynamic initialization.  */
8894   if (decl_maybe_constant_destruction (decl, TREE_TYPE (decl)))
8895     {
8896       /* Make sure the destructor is callable.  */
8897       cxx_maybe_build_cleanup (decl, tf_warning_or_error);
8898       if (!init)
8899 	return;
8900     }
8901 
8902   if (CP_DECL_THREAD_LOCAL_P (decl) && DECL_GNU_TLS_P (decl)
8903       && !DECL_FUNCTION_SCOPE_P (decl))
8904     {
8905       location_t dloc = DECL_SOURCE_LOCATION (decl);
8906       if (init)
8907 	error_at (dloc, "non-local variable %qD declared %<__thread%> "
8908 		  "needs dynamic initialization", decl);
8909       else
8910 	error_at (dloc, "non-local variable %qD declared %<__thread%> "
8911 		  "has a non-trivial destructor", decl);
8912       static bool informed;
8913       if (!informed)
8914 	{
8915 	  inform (dloc, "C++11 %<thread_local%> allows dynamic "
8916 		  "initialization and destruction");
8917 	  informed = true;
8918 	}
8919       return;
8920     }
8921 
8922   if (DECL_FUNCTION_SCOPE_P (decl))
8923     {
8924       /* Emit code to perform this initialization but once.  */
8925       tree if_stmt = NULL_TREE, inner_if_stmt = NULL_TREE;
8926       tree then_clause = NULL_TREE, inner_then_clause = NULL_TREE;
8927       tree guard, guard_addr;
8928       tree flag, begin;
8929       /* We don't need thread-safety code for thread-local vars.  */
8930       bool thread_guard = (flag_threadsafe_statics
8931 			   && !CP_DECL_THREAD_LOCAL_P (decl));
8932 
8933       /* Emit code to perform this initialization but once.  This code
8934 	 looks like:
8935 
8936 	   static <type> guard;
8937 	   if (!__atomic_load (guard.first_byte)) {
8938 	     if (__cxa_guard_acquire (&guard)) {
8939 	       bool flag = false;
8940 	       try {
8941 		 // Do initialization.
8942 		 flag = true; __cxa_guard_release (&guard);
8943 		 // Register variable for destruction at end of program.
8944 	       } catch {
8945 		 if (!flag) __cxa_guard_abort (&guard);
8946 	       }
8947 	     }
8948 	   }
8949 
8950 	 Note that the `flag' variable is only set to 1 *after* the
8951 	 initialization is complete.  This ensures that an exception,
8952 	 thrown during the construction, will cause the variable to
8953 	 reinitialized when we pass through this code again, as per:
8954 
8955 	   [stmt.dcl]
8956 
8957 	   If the initialization exits by throwing an exception, the
8958 	   initialization is not complete, so it will be tried again
8959 	   the next time control enters the declaration.
8960 
8961 	 This process should be thread-safe, too; multiple threads
8962 	 should not be able to initialize the variable more than
8963 	 once.  */
8964 
8965       /* Create the guard variable.  */
8966       guard = get_guard (decl);
8967 
8968       /* Begin the conditional initialization.  */
8969       if_stmt = begin_if_stmt ();
8970 
8971       finish_if_stmt_cond (get_guard_cond (guard, thread_guard), if_stmt);
8972       then_clause = begin_compound_stmt (BCS_NO_SCOPE);
8973 
8974       if (thread_guard)
8975 	{
8976 	  tree vfntype = NULL_TREE;
8977 	  tree acquire_name, release_name, abort_name;
8978 	  tree acquire_fn, release_fn, abort_fn;
8979 	  guard_addr = build_address (guard);
8980 
8981 	  acquire_name = get_identifier ("__cxa_guard_acquire");
8982 	  release_name = get_identifier ("__cxa_guard_release");
8983 	  abort_name = get_identifier ("__cxa_guard_abort");
8984 	  acquire_fn = get_global_binding (acquire_name);
8985 	  release_fn = get_global_binding (release_name);
8986 	  abort_fn = get_global_binding (abort_name);
8987 	  if (!acquire_fn)
8988 	    acquire_fn = push_library_fn
8989 	      (acquire_name, build_function_type_list (integer_type_node,
8990 						       TREE_TYPE (guard_addr),
8991 						       NULL_TREE),
8992 	       NULL_TREE, ECF_NOTHROW);
8993 	  if (!release_fn || !abort_fn)
8994 	    vfntype = build_function_type_list (void_type_node,
8995 						TREE_TYPE (guard_addr),
8996 						NULL_TREE);
8997 	  if (!release_fn)
8998 	    release_fn = push_library_fn (release_name, vfntype, NULL_TREE,
8999 					  ECF_NOTHROW);
9000 	  if (!abort_fn)
9001 	    abort_fn = push_library_fn (abort_name, vfntype, NULL_TREE,
9002 					ECF_NOTHROW | ECF_LEAF);
9003 
9004 	  inner_if_stmt = begin_if_stmt ();
9005 	  finish_if_stmt_cond (build_call_n (acquire_fn, 1, guard_addr),
9006 			       inner_if_stmt);
9007 
9008 	  inner_then_clause = begin_compound_stmt (BCS_NO_SCOPE);
9009 	  begin = get_target_expr (boolean_false_node);
9010 	  flag = TARGET_EXPR_SLOT (begin);
9011 
9012 	  TARGET_EXPR_CLEANUP (begin)
9013 	    = build3 (COND_EXPR, void_type_node, flag,
9014 		      void_node,
9015 		      build_call_n (abort_fn, 1, guard_addr));
9016 	  CLEANUP_EH_ONLY (begin) = 1;
9017 
9018 	  /* Do the initialization itself.  */
9019 	  init = add_stmt_to_compound (begin, init);
9020 	  init = add_stmt_to_compound (init,
9021 				       build2 (MODIFY_EXPR, void_type_node,
9022 					       flag, boolean_true_node));
9023 
9024 	  /* Use atexit to register a function for destroying this static
9025 	     variable.  Do this before calling __cxa_guard_release.  */
9026 	  init = add_stmt_to_compound (init, register_dtor_fn (decl));
9027 
9028 	  init = add_stmt_to_compound (init, build_call_n (release_fn, 1,
9029 							   guard_addr));
9030 	}
9031       else
9032 	{
9033 	  init = add_stmt_to_compound (init, set_guard (guard));
9034 
9035 	  /* Use atexit to register a function for destroying this static
9036 	     variable.  */
9037 	  init = add_stmt_to_compound (init, register_dtor_fn (decl));
9038 	}
9039 
9040       finish_expr_stmt (init);
9041 
9042       if (thread_guard)
9043 	{
9044 	  finish_compound_stmt (inner_then_clause);
9045 	  finish_then_clause (inner_if_stmt);
9046 	  finish_if_stmt (inner_if_stmt);
9047 	}
9048 
9049       finish_compound_stmt (then_clause);
9050       finish_then_clause (if_stmt);
9051       finish_if_stmt (if_stmt);
9052     }
9053   else if (CP_DECL_THREAD_LOCAL_P (decl))
9054     tls_aggregates = tree_cons (init, decl, tls_aggregates);
9055   else
9056     static_aggregates = tree_cons (init, decl, static_aggregates);
9057 }
9058 
9059 
9060 /* Make TYPE a complete type based on INITIAL_VALUE.
9061    Return 0 if successful, 1 if INITIAL_VALUE can't be deciphered,
9062    2 if there was no information (in which case assume 0 if DO_DEFAULT),
9063    3 if the initializer list is empty (in pedantic mode). */
9064 
9065 int
cp_complete_array_type(tree * ptype,tree initial_value,bool do_default)9066 cp_complete_array_type (tree *ptype, tree initial_value, bool do_default)
9067 {
9068   int failure;
9069   tree type, elt_type;
9070 
9071   /* Don't get confused by a CONSTRUCTOR for some other type.  */
9072   if (initial_value && TREE_CODE (initial_value) == CONSTRUCTOR
9073       && !BRACE_ENCLOSED_INITIALIZER_P (initial_value)
9074       && TREE_CODE (TREE_TYPE (initial_value)) != ARRAY_TYPE)
9075     return 1;
9076 
9077   if (initial_value)
9078     {
9079       unsigned HOST_WIDE_INT i;
9080       tree value;
9081 
9082       /* An array of character type can be initialized from a
9083 	 brace-enclosed string constant.
9084 
9085 	 FIXME: this code is duplicated from reshape_init. Probably
9086 	 we should just call reshape_init here?  */
9087       if (char_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (*ptype)))
9088 	  && TREE_CODE (initial_value) == CONSTRUCTOR
9089 	  && !vec_safe_is_empty (CONSTRUCTOR_ELTS (initial_value)))
9090 	{
9091 	  vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (initial_value);
9092 	  tree value = (*v)[0].value;
9093 	  STRIP_ANY_LOCATION_WRAPPER (value);
9094 
9095 	  if (TREE_CODE (value) == STRING_CST
9096 	      && v->length () == 1)
9097 	    initial_value = value;
9098 	}
9099 
9100       /* If any of the elements are parameter packs, we can't actually
9101 	 complete this type now because the array size is dependent.  */
9102       if (TREE_CODE (initial_value) == CONSTRUCTOR)
9103 	{
9104 	  FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (initial_value),
9105 				      i, value)
9106 	    {
9107 	      if (PACK_EXPANSION_P (value))
9108 		return 0;
9109 	    }
9110 	}
9111     }
9112 
9113   failure = complete_array_type (ptype, initial_value, do_default);
9114 
9115   /* We can create the array before the element type is complete, which
9116      means that we didn't have these two bits set in the original type
9117      either.  In completing the type, we are expected to propagate these
9118      bits.  See also complete_type which does the same thing for arrays
9119      of fixed size.  */
9120   type = *ptype;
9121   if (type != error_mark_node && TYPE_DOMAIN (type))
9122     {
9123       elt_type = TREE_TYPE (type);
9124       TYPE_NEEDS_CONSTRUCTING (type) = TYPE_NEEDS_CONSTRUCTING (elt_type);
9125       TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
9126 	= TYPE_HAS_NONTRIVIAL_DESTRUCTOR (elt_type);
9127     }
9128 
9129   return failure;
9130 }
9131 
9132 /* As above, but either give an error or reject zero-size arrays, depending
9133    on COMPLAIN.  */
9134 
9135 int
cp_complete_array_type_or_error(tree * ptype,tree initial_value,bool do_default,tsubst_flags_t complain)9136 cp_complete_array_type_or_error (tree *ptype, tree initial_value,
9137 				 bool do_default, tsubst_flags_t complain)
9138 {
9139   int failure;
9140   bool sfinae = !(complain & tf_error);
9141   /* In SFINAE context we can't be lenient about zero-size arrays.  */
9142   if (sfinae)
9143     ++pedantic;
9144   failure = cp_complete_array_type (ptype, initial_value, do_default);
9145   if (sfinae)
9146     --pedantic;
9147   if (failure)
9148     {
9149       if (sfinae)
9150 	/* Not an error.  */;
9151       else if (failure == 1)
9152 	error ("initializer fails to determine size of %qT", *ptype);
9153       else if (failure == 2)
9154 	{
9155 	  if (do_default)
9156 	    error ("array size missing in %qT", *ptype);
9157 	}
9158       else if (failure == 3)
9159 	error ("zero-size array %qT", *ptype);
9160       *ptype = error_mark_node;
9161     }
9162   return failure;
9163 }
9164 
9165 /* Return zero if something is declared to be a member of type
9166    CTYPE when in the context of CUR_TYPE.  STRING is the error
9167    message to print in that case.  Otherwise, quietly return 1.  */
9168 
9169 static int
member_function_or_else(tree ctype,tree cur_type,enum overload_flags flags)9170 member_function_or_else (tree ctype, tree cur_type, enum overload_flags flags)
9171 {
9172   if (ctype && ctype != cur_type)
9173     {
9174       if (flags == DTOR_FLAG)
9175 	error ("destructor for alien class %qT cannot be a member", ctype);
9176       else
9177 	error ("constructor for alien class %qT cannot be a member", ctype);
9178       return 0;
9179     }
9180   return 1;
9181 }
9182 
9183 /* Subroutine of `grokdeclarator'.  */
9184 
9185 /* Generate errors possibly applicable for a given set of specifiers.
9186    This is for ARM $7.1.2.  */
9187 
9188 static void
bad_specifiers(tree object,enum bad_spec_place type,int virtualp,int quals,int inlinep,int friendp,int raises,const location_t * locations)9189 bad_specifiers (tree object,
9190 		enum bad_spec_place type,
9191 		int virtualp,
9192 		int quals,
9193 		int inlinep,
9194 		int friendp,
9195 		int raises,
9196 		const location_t* locations)
9197 {
9198   switch (type)
9199     {
9200       case BSP_VAR:
9201 	if (virtualp)
9202 	  error_at (locations[ds_virtual],
9203 		    "%qD declared as a %<virtual%> variable", object);
9204 	if (quals)
9205 	  error ("%<const%> and %<volatile%> function specifiers on "
9206 	         "%qD invalid in variable declaration", object);
9207 	break;
9208       case BSP_PARM:
9209 	if (virtualp)
9210 	  error_at (locations[ds_virtual],
9211 		    "%qD declared as a %<virtual%> parameter", object);
9212 	if (inlinep)
9213 	  error_at (locations[ds_inline],
9214 		    "%qD declared as an %<inline%> parameter", object);
9215 	if (quals)
9216 	  error ("%<const%> and %<volatile%> function specifiers on "
9217 	  	 "%qD invalid in parameter declaration", object);
9218 	break;
9219       case BSP_TYPE:
9220 	if (virtualp)
9221 	  error_at (locations[ds_virtual],
9222 		    "%qD declared as a %<virtual%> type", object);
9223 	if (inlinep)
9224 	  error_at (locations[ds_inline],
9225 		    "%qD declared as an %<inline%> type", object);
9226 	if (quals)
9227 	  error ("%<const%> and %<volatile%> function specifiers on "
9228 	  	 "%qD invalid in type declaration", object);
9229 	break;
9230       case BSP_FIELD:
9231 	if (virtualp)
9232 	  error_at (locations[ds_virtual],
9233 		    "%qD declared as a %<virtual%> field", object);
9234 	if (inlinep)
9235 	  error_at (locations[ds_inline],
9236 		    "%qD declared as an %<inline%> field", object);
9237 	if (quals)
9238 	  error ("%<const%> and %<volatile%> function specifiers on "
9239 	  	 "%qD invalid in field declaration", object);
9240 	break;
9241       default:
9242         gcc_unreachable();
9243     }
9244   if (friendp)
9245     error ("%q+D declared as a friend", object);
9246   if (raises
9247       && !flag_noexcept_type
9248       && (TREE_CODE (object) == TYPE_DECL
9249 	  || (!TYPE_PTRFN_P (TREE_TYPE (object))
9250 	      && !TYPE_REFFN_P (TREE_TYPE (object))
9251 	      && !TYPE_PTRMEMFUNC_P (TREE_TYPE (object)))))
9252     error ("%q+D declared with an exception specification", object);
9253 }
9254 
9255 /* DECL is a member function or static data member and is presently
9256    being defined.  Check that the definition is taking place in a
9257    valid namespace.  */
9258 
9259 static void
check_class_member_definition_namespace(tree decl)9260 check_class_member_definition_namespace (tree decl)
9261 {
9262   /* These checks only apply to member functions and static data
9263      members.  */
9264   gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
9265   /* We check for problems with specializations in pt.c in
9266      check_specialization_namespace, where we can issue better
9267      diagnostics.  */
9268   if (processing_specialization)
9269     return;
9270   /* We check this in check_explicit_instantiation_namespace.  */
9271   if (processing_explicit_instantiation)
9272     return;
9273   /* [class.mfct]
9274 
9275      A member function definition that appears outside of the
9276      class definition shall appear in a namespace scope enclosing
9277      the class definition.
9278 
9279      [class.static.data]
9280 
9281      The definition for a static data member shall appear in a
9282      namespace scope enclosing the member's class definition.  */
9283   if (!is_ancestor (current_namespace, DECL_CONTEXT (decl)))
9284     permerror (input_location, "definition of %qD is not in namespace enclosing %qT",
9285 	       decl, DECL_CONTEXT (decl));
9286 }
9287 
9288 /* Build a PARM_DECL for the "this" parameter of FN.  TYPE is the
9289    METHOD_TYPE for a non-static member function; QUALS are the
9290    cv-qualifiers that apply to the function.  */
9291 
9292 tree
build_this_parm(tree fn,tree type,cp_cv_quals quals)9293 build_this_parm (tree fn, tree type, cp_cv_quals quals)
9294 {
9295   tree this_type;
9296   tree qual_type;
9297   tree parm;
9298   cp_cv_quals this_quals;
9299 
9300   if (CLASS_TYPE_P (type))
9301     {
9302       this_type
9303 	= cp_build_qualified_type (type, quals & ~TYPE_QUAL_RESTRICT);
9304       this_type = build_pointer_type (this_type);
9305     }
9306   else
9307     this_type = type_of_this_parm (type);
9308   /* The `this' parameter is implicitly `const'; it cannot be
9309      assigned to.  */
9310   this_quals = (quals & TYPE_QUAL_RESTRICT) | TYPE_QUAL_CONST;
9311   qual_type = cp_build_qualified_type (this_type, this_quals);
9312   parm = build_artificial_parm (fn, this_identifier, qual_type);
9313   cp_apply_type_quals_to_decl (this_quals, parm);
9314   return parm;
9315 }
9316 
9317 /* DECL is a static member function.  Complain if it was declared
9318    with function-cv-quals.  */
9319 
9320 static void
check_static_quals(tree decl,cp_cv_quals quals)9321 check_static_quals (tree decl, cp_cv_quals quals)
9322 {
9323   if (quals != TYPE_UNQUALIFIED)
9324     error ("static member function %q#D declared with type qualifiers",
9325 	   decl);
9326 }
9327 
9328 // Check that FN takes no arguments and returns bool.
9329 static void
check_concept_fn(tree fn)9330 check_concept_fn (tree fn)
9331 {
9332   // A constraint is nullary.
9333   if (DECL_ARGUMENTS (fn))
9334     error_at (DECL_SOURCE_LOCATION (fn),
9335 	      "concept %q#D declared with function parameters", fn);
9336 
9337   // The declared return type of the concept shall be bool, and
9338   // it shall not be deduced from it definition.
9339   tree type = TREE_TYPE (TREE_TYPE (fn));
9340   if (is_auto (type))
9341     error_at (DECL_SOURCE_LOCATION (fn),
9342 	      "concept %q#D declared with a deduced return type", fn);
9343   else if (type != boolean_type_node)
9344     error_at (DECL_SOURCE_LOCATION (fn),
9345 	      "concept %q#D with non-%<bool%> return type %qT", fn, type);
9346 }
9347 
9348 /* Helper function.  Replace the temporary this parameter injected
9349    during cp_finish_omp_declare_simd with the real this parameter.  */
9350 
9351 static tree
declare_simd_adjust_this(tree * tp,int * walk_subtrees,void * data)9352 declare_simd_adjust_this (tree *tp, int *walk_subtrees, void *data)
9353 {
9354   tree this_parm = (tree) data;
9355   if (TREE_CODE (*tp) == PARM_DECL
9356       && DECL_NAME (*tp) == this_identifier
9357       && *tp != this_parm)
9358     *tp = this_parm;
9359   else if (TYPE_P (*tp))
9360     *walk_subtrees = 0;
9361   return NULL_TREE;
9362 }
9363 
9364 /* CTYPE is class type, or null if non-class.
9365    TYPE is type this FUNCTION_DECL should have, either FUNCTION_TYPE
9366    or METHOD_TYPE.
9367    DECLARATOR is the function's name.
9368    PARMS is a chain of PARM_DECLs for the function.
9369    VIRTUALP is truthvalue of whether the function is virtual or not.
9370    FLAGS are to be passed through to `grokclassfn'.
9371    QUALS are qualifiers indicating whether the function is `const'
9372    or `volatile'.
9373    RAISES is a list of exceptions that this function can raise.
9374    CHECK is 1 if we must find this method in CTYPE, 0 if we should
9375    not look, and -1 if we should not call `grokclassfn' at all.
9376 
9377    SFK is the kind of special function (if any) for the new function.
9378 
9379    Returns `NULL_TREE' if something goes wrong, after issuing
9380    applicable error messages.  */
9381 
9382 static tree
grokfndecl(tree ctype,tree type,tree declarator,tree parms,tree orig_declarator,const cp_decl_specifier_seq * declspecs,tree decl_reqs,int virtualp,enum overload_flags flags,cp_cv_quals quals,cp_ref_qualifier rqual,tree raises,int check,int friendp,int publicp,int inlinep,bool deletedp,special_function_kind sfk,bool funcdef_flag,bool late_return_type_p,int initialized,int template_count,tree in_namespace,tree * attrlist,location_t location)9383 grokfndecl (tree ctype,
9384 	    tree type,
9385 	    tree declarator,
9386 	    tree parms,
9387 	    tree orig_declarator,
9388 	    const cp_decl_specifier_seq *declspecs,
9389 	    tree decl_reqs,
9390 	    int virtualp,
9391 	    enum overload_flags flags,
9392 	    cp_cv_quals quals,
9393 	    cp_ref_qualifier rqual,
9394 	    tree raises,
9395 	    int check,
9396 	    int friendp,
9397 	    int publicp,
9398 	    int inlinep,
9399 	    bool deletedp,
9400 	    special_function_kind sfk,
9401 	    bool funcdef_flag,
9402 	    bool late_return_type_p,
9403 	    int initialized,
9404 	    int template_count,
9405 	    tree in_namespace,
9406 	    tree* attrlist,
9407 	    location_t location)
9408 {
9409   tree decl;
9410   int staticp = ctype && TREE_CODE (type) == FUNCTION_TYPE;
9411   tree t;
9412 
9413   if (location == UNKNOWN_LOCATION)
9414     location = input_location;
9415 
9416   /* Was the concept specifier present?  */
9417   bool concept_p = inlinep & 4;
9418 
9419   /* Concept declarations must have a corresponding definition.  */
9420   if (concept_p && !funcdef_flag)
9421     {
9422       error_at (location, "concept %qD has no definition", declarator);
9423       return NULL_TREE;
9424     }
9425 
9426   type = build_cp_fntype_variant (type, rqual, raises, late_return_type_p);
9427 
9428   decl = build_lang_decl_loc (location, FUNCTION_DECL, declarator, type);
9429 
9430   /* Set the constraints on the declaration. */
9431   if (flag_concepts)
9432     {
9433       tree tmpl_reqs = NULL_TREE;
9434       tree ctx = friendp ? current_class_type : ctype;
9435       bool memtmpl = (processing_template_decl > template_class_depth (ctx));
9436       if (memtmpl)
9437         tmpl_reqs = TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
9438       tree ci = build_constraints (tmpl_reqs, decl_reqs);
9439       if (concept_p && ci)
9440         {
9441           error_at (location, "a function concept cannot be constrained");
9442           ci = NULL_TREE;
9443         }
9444       /* C++20 CA378: Remove non-templated constrained functions.  */
9445       if (ci && !flag_concepts_ts
9446 	  && (!processing_template_decl
9447 	      || (friendp && !memtmpl && !initialized && !funcdef_flag)))
9448 	{
9449 	  error_at (location, "constraints on a non-templated function");
9450 	  ci = NULL_TREE;
9451 	}
9452       set_constraints (decl, ci);
9453     }
9454 
9455   if (TREE_CODE (type) == METHOD_TYPE)
9456     {
9457       tree parm = build_this_parm (decl, type, quals);
9458       DECL_CHAIN (parm) = parms;
9459       parms = parm;
9460 
9461       /* Allocate space to hold the vptr bit if needed.  */
9462       SET_DECL_ALIGN (decl, MINIMUM_METHOD_BOUNDARY);
9463     }
9464 
9465   DECL_ARGUMENTS (decl) = parms;
9466   for (t = parms; t; t = DECL_CHAIN (t))
9467     DECL_CONTEXT (t) = decl;
9468 
9469   /* Propagate volatile out from type to decl.  */
9470   if (TYPE_VOLATILE (type))
9471     TREE_THIS_VOLATILE (decl) = 1;
9472 
9473   /* Setup decl according to sfk.  */
9474   switch (sfk)
9475     {
9476     case sfk_constructor:
9477     case sfk_copy_constructor:
9478     case sfk_move_constructor:
9479       DECL_CXX_CONSTRUCTOR_P (decl) = 1;
9480       DECL_NAME (decl) = ctor_identifier;
9481       break;
9482     case sfk_destructor:
9483       DECL_CXX_DESTRUCTOR_P (decl) = 1;
9484       DECL_NAME (decl) = dtor_identifier;
9485       break;
9486     default:
9487       break;
9488     }
9489 
9490   if (friendp && TREE_CODE (orig_declarator) == TEMPLATE_ID_EXPR)
9491     {
9492       if (funcdef_flag)
9493 	error_at (location,
9494 		  "defining explicit specialization %qD in friend declaration",
9495 		  orig_declarator);
9496       else
9497 	{
9498 	  tree fns = TREE_OPERAND (orig_declarator, 0);
9499 	  tree args = TREE_OPERAND (orig_declarator, 1);
9500 
9501 	  if (PROCESSING_REAL_TEMPLATE_DECL_P ())
9502 	    {
9503 	      /* Something like `template <class T> friend void f<T>()'.  */
9504 	      error_at (location,
9505 			"invalid use of template-id %qD in declaration "
9506 			"of primary template",
9507 			orig_declarator);
9508 	      return NULL_TREE;
9509 	    }
9510 
9511 
9512 	  /* A friend declaration of the form friend void f<>().  Record
9513 	     the information in the TEMPLATE_ID_EXPR.  */
9514 	  SET_DECL_IMPLICIT_INSTANTIATION (decl);
9515 
9516 	  gcc_assert (identifier_p (fns) || OVL_P (fns));
9517 	  DECL_TEMPLATE_INFO (decl) = build_template_info (fns, args);
9518 
9519 	  for (t = TYPE_ARG_TYPES (TREE_TYPE (decl)); t; t = TREE_CHAIN (t))
9520 	    if (TREE_PURPOSE (t)
9521 		&& TREE_CODE (TREE_PURPOSE (t)) == DEFERRED_PARSE)
9522 	    {
9523 	      error_at (defparse_location (TREE_PURPOSE (t)),
9524 			"default arguments are not allowed in declaration "
9525 			"of friend template specialization %qD",
9526 			decl);
9527 	      return NULL_TREE;
9528 	    }
9529 
9530 	  if (inlinep & 1)
9531 	    {
9532 	      error_at (declspecs->locations[ds_inline],
9533 			"%<inline%> is not allowed in declaration of friend "
9534 			"template specialization %qD",
9535 			decl);
9536 	      return NULL_TREE;
9537 	    }
9538 	}
9539     }
9540 
9541   /* C++17 11.3.6/4: "If a friend declaration specifies a default argument
9542      expression, that declaration shall be a definition..."  */
9543   if (friendp && !funcdef_flag)
9544     {
9545       for (tree t = FUNCTION_FIRST_USER_PARMTYPE (decl);
9546 	   t && t != void_list_node; t = TREE_CHAIN (t))
9547 	if (TREE_PURPOSE (t))
9548 	  {
9549 	    permerror (DECL_SOURCE_LOCATION (decl),
9550 		       "friend declaration of %qD specifies default "
9551 		       "arguments and isn%'t a definition", decl);
9552 	    break;
9553 	  }
9554     }
9555 
9556   /* FIXME: For now.  */
9557   if (virtualp && (inlinep & 8) != 0)
9558     {
9559       sorry_at (DECL_SOURCE_LOCATION (decl),
9560 		"%<virtual%> %<consteval%> method %qD not supported yet",
9561 		decl);
9562       inlinep &= ~8;
9563     }
9564 
9565   /* If this decl has namespace scope, set that up.  */
9566   if (in_namespace)
9567     set_decl_namespace (decl, in_namespace, friendp);
9568   else if (!ctype)
9569     DECL_CONTEXT (decl) = FROB_CONTEXT (current_decl_namespace ());
9570 
9571   /* `main' and builtins have implicit 'C' linkage.  */
9572   if (ctype == NULL_TREE
9573       && DECL_FILE_SCOPE_P (decl)
9574       && current_lang_name == lang_name_cplusplus
9575       && (MAIN_NAME_P (declarator)
9576 	  || (IDENTIFIER_LENGTH (declarator) > 10
9577 	      && IDENTIFIER_POINTER (declarator)[0] == '_'
9578 	      && IDENTIFIER_POINTER (declarator)[1] == '_'
9579 	      && strncmp (IDENTIFIER_POINTER (declarator)+2,
9580 			  "builtin_", 8) == 0)
9581 	  || (targetcm.cxx_implicit_extern_c
9582 	      && (targetcm.cxx_implicit_extern_c
9583 		  (IDENTIFIER_POINTER (declarator))))))
9584     SET_DECL_LANGUAGE (decl, lang_c);
9585 
9586   /* Should probably propagate const out from type to decl I bet (mrs).  */
9587   if (staticp)
9588     {
9589       DECL_STATIC_FUNCTION_P (decl) = 1;
9590       DECL_CONTEXT (decl) = ctype;
9591     }
9592 
9593   if (deletedp)
9594     DECL_DELETED_FN (decl) = 1;
9595 
9596   if (ctype)
9597     {
9598       DECL_CONTEXT (decl) = ctype;
9599       if (funcdef_flag)
9600 	check_class_member_definition_namespace (decl);
9601     }
9602 
9603   if (ctype == NULL_TREE && DECL_MAIN_P (decl))
9604     {
9605       if (PROCESSING_REAL_TEMPLATE_DECL_P())
9606 	error_at (location, "cannot declare %<::main%> to be a template");
9607       if (inlinep & 1)
9608 	error_at (declspecs->locations[ds_inline],
9609 		  "cannot declare %<::main%> to be inline");
9610       if (inlinep & 2)
9611 	error_at (declspecs->locations[ds_constexpr],
9612 		  "cannot declare %<::main%> to be %qs", "constexpr");
9613       if (inlinep & 8)
9614 	error_at (declspecs->locations[ds_consteval],
9615 		  "cannot declare %<::main%> to be %qs", "consteval");
9616       if (!publicp)
9617 	error_at (location, "cannot declare %<::main%> to be static");
9618       inlinep = 0;
9619       publicp = 1;
9620     }
9621 
9622   /* Members of anonymous types and local classes have no linkage; make
9623      them internal.  If a typedef is made later, this will be changed.  */
9624   if (ctype && (!TREE_PUBLIC (TYPE_MAIN_DECL (ctype))
9625 		|| decl_function_context (TYPE_MAIN_DECL (ctype))))
9626     publicp = 0;
9627 
9628   if (publicp && cxx_dialect == cxx98)
9629     {
9630       /* [basic.link]: A name with no linkage (notably, the name of a class
9631 	 or enumeration declared in a local scope) shall not be used to
9632 	 declare an entity with linkage.
9633 
9634 	 DR 757 relaxes this restriction for C++0x.  */
9635       no_linkage_error (decl);
9636     }
9637 
9638   TREE_PUBLIC (decl) = publicp;
9639   if (! publicp)
9640     {
9641       DECL_INTERFACE_KNOWN (decl) = 1;
9642       DECL_NOT_REALLY_EXTERN (decl) = 1;
9643     }
9644 
9645   /* If the declaration was declared inline, mark it as such.  */
9646   if (inlinep)
9647     {
9648       DECL_DECLARED_INLINE_P (decl) = 1;
9649       if (publicp)
9650 	DECL_COMDAT (decl) = 1;
9651     }
9652   if (inlinep & 2)
9653     DECL_DECLARED_CONSTEXPR_P (decl) = true;
9654   else if (inlinep & 8)
9655     {
9656       DECL_DECLARED_CONSTEXPR_P (decl) = true;
9657       SET_DECL_IMMEDIATE_FUNCTION_P (decl);
9658     }
9659 
9660   // If the concept declaration specifier was found, check
9661   // that the declaration satisfies the necessary requirements.
9662   if (concept_p)
9663     {
9664       DECL_DECLARED_CONCEPT_P (decl) = true;
9665       check_concept_fn (decl);
9666     }
9667 
9668   DECL_EXTERNAL (decl) = 1;
9669   if (TREE_CODE (type) == FUNCTION_TYPE)
9670     {
9671       if (quals || rqual)
9672 	TREE_TYPE (decl) = apply_memfn_quals (TREE_TYPE (decl),
9673 					      TYPE_UNQUALIFIED,
9674 					      REF_QUAL_NONE);
9675 
9676       if (quals)
9677 	{
9678 	  error (ctype
9679 		 ? G_("static member function %qD cannot have cv-qualifier")
9680 		 : G_("non-member function %qD cannot have cv-qualifier"),
9681 		 decl);
9682 	  quals = TYPE_UNQUALIFIED;
9683 	}
9684 
9685       if (rqual)
9686 	{
9687 	  error (ctype
9688 		 ? G_("static member function %qD cannot have ref-qualifier")
9689 		 : G_("non-member function %qD cannot have ref-qualifier"),
9690 		 decl);
9691 	  rqual = REF_QUAL_NONE;
9692 	}
9693     }
9694 
9695   if (deduction_guide_p (decl))
9696     {
9697       if (!DECL_NAMESPACE_SCOPE_P (decl))
9698 	{
9699 	  error_at (location, "deduction guide %qD must be declared at "
9700 		    "namespace scope", decl);
9701 	  return NULL_TREE;
9702 	}
9703       tree type = TREE_TYPE (DECL_NAME (decl));
9704       if (in_namespace == NULL_TREE
9705 	  && CP_DECL_CONTEXT (decl) != CP_TYPE_CONTEXT (type))
9706 	{
9707 	  error_at (location, "deduction guide %qD must be declared in the "
9708 			      "same scope as %qT", decl, type);
9709 	  inform (location_of (type), "  declared here");
9710 	  return NULL_TREE;
9711 	}
9712       if (funcdef_flag)
9713 	error_at (location,
9714 		  "deduction guide %qD must not have a function body", decl);
9715     }
9716   else if (IDENTIFIER_ANY_OP_P (DECL_NAME (decl))
9717 	   && !grok_op_properties (decl, /*complain=*/true))
9718     return NULL_TREE;
9719   else if (UDLIT_OPER_P (DECL_NAME (decl)))
9720     {
9721       bool long_long_unsigned_p;
9722       bool long_double_p;
9723       const char *suffix = NULL;
9724       /* [over.literal]/6: Literal operators shall not have C linkage. */
9725       if (DECL_LANGUAGE (decl) == lang_c)
9726 	{
9727 	  error_at (location, "literal operator with C linkage");
9728 	  maybe_show_extern_c_location ();
9729 	  return NULL_TREE;
9730 	}
9731 
9732       if (DECL_NAMESPACE_SCOPE_P (decl))
9733 	{
9734 	  if (!check_literal_operator_args (decl, &long_long_unsigned_p,
9735 					    &long_double_p))
9736 	    {
9737 	      error_at (location, "%qD has invalid argument list", decl);
9738 	      return NULL_TREE;
9739 	    }
9740 
9741 	  suffix = UDLIT_OP_SUFFIX (DECL_NAME (decl));
9742 	  if (long_long_unsigned_p)
9743 	    {
9744 	      if (cpp_interpret_int_suffix (parse_in, suffix, strlen (suffix)))
9745 		warning_at (location, 0, "integer suffix %qs"
9746 			    " shadowed by implementation", suffix);
9747 	    }
9748 	  else if (long_double_p)
9749 	    {
9750 	      if (cpp_interpret_float_suffix (parse_in, suffix, strlen (suffix)))
9751 		warning_at (location, 0, "floating-point suffix %qs"
9752 			    " shadowed by implementation", suffix);
9753 	    }
9754 	  /* 17.6.3.3.5  */
9755 	  if (suffix[0] != '_'
9756 	      && !current_function_decl && !(friendp && !funcdef_flag))
9757 	    warning_at (location, OPT_Wliteral_suffix,
9758 			"literal operator suffixes not preceded by %<_%>"
9759 			" are reserved for future standardization");
9760 	}
9761       else
9762 	{
9763 	  error_at (location, "%qD must be a non-member function", decl);
9764 	  return NULL_TREE;
9765 	}
9766     }
9767 
9768   if (funcdef_flag)
9769     /* Make the init_value nonzero so pushdecl knows this is not
9770        tentative.  error_mark_node is replaced later with the BLOCK.  */
9771     DECL_INITIAL (decl) = error_mark_node;
9772 
9773   if (TYPE_NOTHROW_P (type) || nothrow_libfn_p (decl))
9774     TREE_NOTHROW (decl) = 1;
9775 
9776   if (flag_openmp || flag_openmp_simd)
9777     {
9778       /* Adjust "omp declare simd" attributes.  */
9779       tree ods = lookup_attribute ("omp declare simd", *attrlist);
9780       if (ods)
9781 	{
9782 	  tree attr;
9783 	  for (attr = ods; attr;
9784 	       attr = lookup_attribute ("omp declare simd", TREE_CHAIN (attr)))
9785 	    {
9786 	      if (TREE_CODE (type) == METHOD_TYPE)
9787 		walk_tree (&TREE_VALUE (attr), declare_simd_adjust_this,
9788 			   DECL_ARGUMENTS (decl), NULL);
9789 	      if (TREE_VALUE (attr) != NULL_TREE)
9790 		{
9791 		  tree cl = TREE_VALUE (TREE_VALUE (attr));
9792 		  cl = c_omp_declare_simd_clauses_to_numbers
9793 						(DECL_ARGUMENTS (decl), cl);
9794 		  if (cl)
9795 		    TREE_VALUE (TREE_VALUE (attr)) = cl;
9796 		  else
9797 		    TREE_VALUE (attr) = NULL_TREE;
9798 		}
9799 	    }
9800 	}
9801     }
9802 
9803   /* Caller will do the rest of this.  */
9804   if (check < 0)
9805     return decl;
9806 
9807   if (ctype != NULL_TREE)
9808     grokclassfn (ctype, decl, flags);
9809 
9810   /* 12.4/3  */
9811   if (cxx_dialect >= cxx11
9812       && DECL_DESTRUCTOR_P (decl)
9813       && !TYPE_BEING_DEFINED (DECL_CONTEXT (decl))
9814       && !processing_template_decl)
9815     deduce_noexcept_on_destructor (decl);
9816 
9817   decl = check_explicit_specialization (orig_declarator, decl,
9818 					template_count,
9819 					2 * funcdef_flag +
9820 					4 * (friendp != 0) +
9821 	                                8 * concept_p,
9822 					*attrlist);
9823   if (decl == error_mark_node)
9824     return NULL_TREE;
9825 
9826   if (DECL_STATIC_FUNCTION_P (decl))
9827     check_static_quals (decl, quals);
9828 
9829   if (attrlist)
9830     {
9831       cplus_decl_attributes (&decl, *attrlist, 0);
9832       *attrlist = NULL_TREE;
9833     }
9834 
9835   /* Check main's type after attributes have been applied.  */
9836   if (ctype == NULL_TREE && DECL_MAIN_P (decl))
9837     {
9838       if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
9839 			integer_type_node))
9840 	{
9841 	  tree oldtypeargs = TYPE_ARG_TYPES (TREE_TYPE (decl));
9842 	  tree newtype;
9843 	  error_at (declspecs->locations[ds_type_spec],
9844 		    "%<::main%> must return %<int%>");
9845 	  newtype = build_function_type (integer_type_node, oldtypeargs);
9846 	  TREE_TYPE (decl) = newtype;
9847 	}
9848       if (warn_main)
9849 	check_main_parameter_types (decl);
9850     }
9851 
9852   if (ctype != NULL_TREE && check)
9853     {
9854       tree old_decl = check_classfn (ctype, decl,
9855 				     (processing_template_decl
9856 				      > template_class_depth (ctype))
9857 				     ? current_template_parms
9858 				     : NULL_TREE);
9859 
9860       if (old_decl == error_mark_node)
9861 	return NULL_TREE;
9862 
9863       if (old_decl)
9864 	{
9865 	  tree ok;
9866 	  tree pushed_scope;
9867 
9868 	  if (TREE_CODE (old_decl) == TEMPLATE_DECL)
9869 	    /* Because grokfndecl is always supposed to return a
9870 	       FUNCTION_DECL, we pull out the DECL_TEMPLATE_RESULT
9871 	       here.  We depend on our callers to figure out that its
9872 	       really a template that's being returned.  */
9873 	    old_decl = DECL_TEMPLATE_RESULT (old_decl);
9874 
9875 	  if (DECL_STATIC_FUNCTION_P (old_decl)
9876 	      && TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE)
9877 	    {
9878 	      /* Remove the `this' parm added by grokclassfn.  */
9879 	      revert_static_member_fn (decl);
9880 	      check_static_quals (decl, quals);
9881 	    }
9882 	  if (DECL_ARTIFICIAL (old_decl))
9883 	    {
9884 	      error ("definition of implicitly-declared %qD", old_decl);
9885 	      return NULL_TREE;
9886 	    }
9887 	  else if (DECL_DEFAULTED_FN (old_decl))
9888 	    {
9889 	      error ("definition of explicitly-defaulted %q+D", decl);
9890 	      inform (DECL_SOURCE_LOCATION (old_decl),
9891 		      "%q#D explicitly defaulted here", old_decl);
9892 	      return NULL_TREE;
9893 	    }
9894 
9895 	  /* Since we've smashed OLD_DECL to its
9896 	     DECL_TEMPLATE_RESULT, we must do the same to DECL.  */
9897 	  if (TREE_CODE (decl) == TEMPLATE_DECL)
9898 	    decl = DECL_TEMPLATE_RESULT (decl);
9899 
9900 	  /* Attempt to merge the declarations.  This can fail, in
9901 	     the case of some invalid specialization declarations.  */
9902 	  pushed_scope = push_scope (ctype);
9903 	  ok = duplicate_decls (decl, old_decl, friendp);
9904 	  if (pushed_scope)
9905 	    pop_scope (pushed_scope);
9906 	  if (!ok)
9907 	    {
9908 	      error ("no %q#D member function declared in class %qT",
9909 		     decl, ctype);
9910 	      return NULL_TREE;
9911 	    }
9912 	  if (ok == error_mark_node)
9913 	    return NULL_TREE;
9914 	  return old_decl;
9915 	}
9916     }
9917 
9918   if (DECL_CONSTRUCTOR_P (decl) && !grok_ctor_properties (ctype, decl))
9919     return NULL_TREE;
9920 
9921   if (ctype == NULL_TREE || check)
9922     return decl;
9923 
9924   if (virtualp)
9925     DECL_VIRTUAL_P (decl) = 1;
9926 
9927   return decl;
9928 }
9929 
9930 /* decl is a FUNCTION_DECL.
9931    specifiers are the parsed virt-specifiers.
9932 
9933    Set flags to reflect the virt-specifiers.
9934 
9935    Returns decl.  */
9936 
9937 static tree
set_virt_specifiers(tree decl,cp_virt_specifiers specifiers)9938 set_virt_specifiers (tree decl, cp_virt_specifiers specifiers)
9939 {
9940   if (decl == NULL_TREE)
9941     return decl;
9942   if (specifiers & VIRT_SPEC_OVERRIDE)
9943     DECL_OVERRIDE_P (decl) = 1;
9944   if (specifiers & VIRT_SPEC_FINAL)
9945     DECL_FINAL_P (decl) = 1;
9946   return decl;
9947 }
9948 
9949 /* DECL is a VAR_DECL for a static data member.  Set flags to reflect
9950    the linkage that DECL will receive in the object file.  */
9951 
9952 static void
set_linkage_for_static_data_member(tree decl)9953 set_linkage_for_static_data_member (tree decl)
9954 {
9955   /* A static data member always has static storage duration and
9956      external linkage.  Note that static data members are forbidden in
9957      local classes -- the only situation in which a class has
9958      non-external linkage.  */
9959   TREE_PUBLIC (decl) = 1;
9960   TREE_STATIC (decl) = 1;
9961   /* For non-template classes, static data members are always put
9962      out in exactly those files where they are defined, just as
9963      with ordinary namespace-scope variables.  */
9964   if (!processing_template_decl)
9965     DECL_INTERFACE_KNOWN (decl) = 1;
9966 }
9967 
9968 /* Create a VAR_DECL named NAME with the indicated TYPE.
9969 
9970    If SCOPE is non-NULL, it is the class type or namespace containing
9971    the variable.  If SCOPE is NULL, the variable should is created in
9972    the innermost enclosing scope.  */
9973 
9974 static tree
grokvardecl(tree type,tree name,tree orig_declarator,const cp_decl_specifier_seq * declspecs,int initialized,int type_quals,int inlinep,bool conceptp,int template_count,tree scope,location_t location)9975 grokvardecl (tree type,
9976 	     tree name,
9977 	     tree orig_declarator,
9978 	     const cp_decl_specifier_seq *declspecs,
9979 	     int initialized,
9980 	     int type_quals,
9981 	     int inlinep,
9982 	     bool conceptp,
9983 	     int template_count,
9984 	     tree scope,
9985 	     location_t location)
9986 {
9987   tree decl;
9988   tree explicit_scope;
9989 
9990   gcc_assert (!name || identifier_p (name));
9991 
9992   bool constp = (type_quals & TYPE_QUAL_CONST) != 0;
9993   bool volatilep = (type_quals & TYPE_QUAL_VOLATILE) != 0;
9994 
9995   /* Compute the scope in which to place the variable, but remember
9996      whether or not that scope was explicitly specified by the user.   */
9997   explicit_scope = scope;
9998   if (!scope)
9999     {
10000       /* An explicit "extern" specifier indicates a namespace-scope
10001 	 variable.  */
10002       if (declspecs->storage_class == sc_extern)
10003 	scope = current_decl_namespace ();
10004       else if (!at_function_scope_p ())
10005 	scope = current_scope ();
10006     }
10007 
10008   if (scope
10009       && (/* If the variable is a namespace-scope variable declared in a
10010 	     template, we need DECL_LANG_SPECIFIC.  */
10011 	  (TREE_CODE (scope) == NAMESPACE_DECL && processing_template_decl)
10012 	  /* Similarly for namespace-scope variables with language linkage
10013 	     other than C++.  */
10014 	  || (TREE_CODE (scope) == NAMESPACE_DECL
10015 	      && current_lang_name != lang_name_cplusplus)
10016 	  /* Similarly for static data members.  */
10017 	  || TYPE_P (scope)
10018 	  /* Similarly for explicit specializations.  */
10019 	  || (orig_declarator
10020 	      && TREE_CODE (orig_declarator) == TEMPLATE_ID_EXPR)))
10021     decl = build_lang_decl_loc (location, VAR_DECL, name, type);
10022   else
10023     decl = build_decl (location, VAR_DECL, name, type);
10024 
10025   if (explicit_scope && TREE_CODE (explicit_scope) == NAMESPACE_DECL)
10026     set_decl_namespace (decl, explicit_scope, 0);
10027   else
10028     DECL_CONTEXT (decl) = FROB_CONTEXT (scope);
10029 
10030   if (declspecs->storage_class == sc_extern)
10031     {
10032       DECL_THIS_EXTERN (decl) = 1;
10033       DECL_EXTERNAL (decl) = !initialized;
10034     }
10035 
10036   if (DECL_CLASS_SCOPE_P (decl))
10037     {
10038       set_linkage_for_static_data_member (decl);
10039       /* This function is only called with out-of-class definitions.  */
10040       DECL_EXTERNAL (decl) = 0;
10041       check_class_member_definition_namespace (decl);
10042     }
10043   /* At top level, either `static' or no s.c. makes a definition
10044      (perhaps tentative), and absence of `static' makes it public.  */
10045   else if (toplevel_bindings_p ())
10046     {
10047       TREE_PUBLIC (decl) = (declspecs->storage_class != sc_static
10048 			    && (DECL_THIS_EXTERN (decl)
10049 				|| ! constp
10050 				|| volatilep
10051 				|| inlinep));
10052       TREE_STATIC (decl) = ! DECL_EXTERNAL (decl);
10053     }
10054   /* Not at top level, only `static' makes a static definition.  */
10055   else
10056     {
10057       TREE_STATIC (decl) = declspecs->storage_class == sc_static;
10058       TREE_PUBLIC (decl) = DECL_EXTERNAL (decl);
10059     }
10060 
10061   if (decl_spec_seq_has_spec_p (declspecs, ds_thread))
10062     {
10063       if (DECL_EXTERNAL (decl) || TREE_STATIC (decl))
10064 	{
10065 	  CP_DECL_THREAD_LOCAL_P (decl) = true;
10066 	  if (!processing_template_decl)
10067 	    set_decl_tls_model (decl, decl_default_tls_model (decl));
10068 	}
10069       if (declspecs->gnu_thread_keyword_p)
10070 	SET_DECL_GNU_TLS_P (decl);
10071     }
10072 
10073   /* If the type of the decl has no linkage, make sure that we'll
10074      notice that in mark_used.  */
10075   if (cxx_dialect > cxx98
10076       && decl_linkage (decl) != lk_none
10077       && DECL_LANG_SPECIFIC (decl) == NULL
10078       && !DECL_EXTERN_C_P (decl)
10079       && no_linkage_check (TREE_TYPE (decl), /*relaxed_p=*/false))
10080     retrofit_lang_decl (decl);
10081 
10082   if (TREE_PUBLIC (decl))
10083     {
10084       /* [basic.link]: A name with no linkage (notably, the name of a class
10085 	 or enumeration declared in a local scope) shall not be used to
10086 	 declare an entity with linkage.
10087 
10088 	 DR 757 relaxes this restriction for C++0x.  */
10089       if (cxx_dialect < cxx11)
10090 	no_linkage_error (decl);
10091     }
10092   else
10093     DECL_INTERFACE_KNOWN (decl) = 1;
10094 
10095   if (DECL_NAME (decl)
10096       && MAIN_NAME_P (DECL_NAME (decl))
10097       && scope == global_namespace)
10098     error_at (DECL_SOURCE_LOCATION (decl),
10099 	      "cannot declare %<::main%> to be a global variable");
10100 
10101   /* Check that the variable can be safely declared as a concept.
10102      Note that this also forbids explicit specializations.  */
10103   if (conceptp)
10104     {
10105       if (!processing_template_decl)
10106         {
10107           error_at (declspecs->locations[ds_concept],
10108 		    "a non-template variable cannot be %<concept%>");
10109           return NULL_TREE;
10110         }
10111       else
10112         DECL_DECLARED_CONCEPT_P (decl) = true;
10113       if (!same_type_ignoring_top_level_qualifiers_p (type, boolean_type_node))
10114 	error_at (declspecs->locations[ds_type_spec],
10115 		  "concept must have type %<bool%>");
10116       if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
10117         {
10118           error_at (location, "a variable concept cannot be constrained");
10119           TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
10120         }
10121     }
10122   else if (flag_concepts
10123 	   && processing_template_decl > template_class_depth (scope))
10124     {
10125       tree reqs = TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
10126       tree ci = build_constraints (reqs, NULL_TREE);
10127 
10128       set_constraints (decl, ci);
10129     }
10130 
10131   // Handle explicit specializations and instantiations of variable templates.
10132   if (orig_declarator)
10133     decl = check_explicit_specialization (orig_declarator, decl,
10134 					  template_count, conceptp * 8);
10135 
10136   return decl != error_mark_node ? decl : NULL_TREE;
10137 }
10138 
10139 /* Create and return a canonical pointer to member function type, for
10140    TYPE, which is a POINTER_TYPE to a METHOD_TYPE.  */
10141 
10142 tree
build_ptrmemfunc_type(tree type)10143 build_ptrmemfunc_type (tree type)
10144 {
10145   tree field, fields;
10146   tree t;
10147 
10148   if (type == error_mark_node)
10149     return type;
10150 
10151   /* Make sure that we always have the unqualified pointer-to-member
10152      type first.  */
10153   if (cp_cv_quals quals = cp_type_quals (type))
10154     {
10155       tree unqual = build_ptrmemfunc_type (TYPE_MAIN_VARIANT (type));
10156       return cp_build_qualified_type (unqual, quals);
10157     }
10158 
10159   /* If a canonical type already exists for this type, use it.  We use
10160      this method instead of type_hash_canon, because it only does a
10161      simple equality check on the list of field members.  */
10162 
10163   t = TYPE_PTRMEMFUNC_TYPE (type);
10164   if (t)
10165     return t;
10166 
10167   t = make_node (RECORD_TYPE);
10168 
10169   /* Let the front end know this is a pointer to member function.  */
10170   TYPE_PTRMEMFUNC_FLAG (t) = 1;
10171 
10172   field = build_decl (input_location, FIELD_DECL, pfn_identifier, type);
10173   DECL_NONADDRESSABLE_P (field) = 1;
10174   fields = field;
10175 
10176   field = build_decl (input_location, FIELD_DECL, delta_identifier,
10177 		      delta_type_node);
10178   DECL_NONADDRESSABLE_P (field) = 1;
10179   DECL_CHAIN (field) = fields;
10180   fields = field;
10181 
10182   finish_builtin_struct (t, "__ptrmemfunc_type", fields, ptr_type_node);
10183 
10184   /* Zap out the name so that the back end will give us the debugging
10185      information for this anonymous RECORD_TYPE.  */
10186   TYPE_NAME (t) = NULL_TREE;
10187 
10188   /* Cache this pointer-to-member type so that we can find it again
10189      later.  */
10190   TYPE_PTRMEMFUNC_TYPE (type) = t;
10191 
10192   if (TYPE_STRUCTURAL_EQUALITY_P (type))
10193     SET_TYPE_STRUCTURAL_EQUALITY (t);
10194   else if (TYPE_CANONICAL (type) != type)
10195     TYPE_CANONICAL (t) = build_ptrmemfunc_type (TYPE_CANONICAL (type));
10196 
10197   return t;
10198 }
10199 
10200 /* Create and return a pointer to data member type.  */
10201 
10202 tree
build_ptrmem_type(tree class_type,tree member_type)10203 build_ptrmem_type (tree class_type, tree member_type)
10204 {
10205   if (TREE_CODE (member_type) == METHOD_TYPE)
10206     {
10207       cp_cv_quals quals = type_memfn_quals (member_type);
10208       cp_ref_qualifier rqual = type_memfn_rqual (member_type);
10209       member_type = build_memfn_type (member_type, class_type, quals, rqual);
10210       return build_ptrmemfunc_type (build_pointer_type (member_type));
10211     }
10212   else
10213     {
10214       gcc_assert (TREE_CODE (member_type) != FUNCTION_TYPE);
10215       return build_offset_type (class_type, member_type);
10216     }
10217 }
10218 
10219 /* DECL is a VAR_DECL defined in-class, whose TYPE is also given.
10220    Check to see that the definition is valid.  Issue appropriate error
10221    messages.  */
10222 
10223 static void
check_static_variable_definition(tree decl,tree type)10224 check_static_variable_definition (tree decl, tree type)
10225 {
10226   /* Avoid redundant diagnostics on out-of-class definitions.  */
10227   if (!current_class_type || !TYPE_BEING_DEFINED (current_class_type))
10228     ;
10229   /* Can't check yet if we don't know the type.  */
10230   else if (dependent_type_p (type))
10231     ;
10232   /* If DECL is declared constexpr, we'll do the appropriate checks
10233      in check_initializer.  Similarly for inline static data members.  */
10234   else if (DECL_P (decl)
10235       && (DECL_DECLARED_CONSTEXPR_P (decl)
10236 	  || undeduced_auto_decl (decl)
10237 	  || DECL_VAR_DECLARED_INLINE_P (decl)))
10238     ;
10239   else if (cxx_dialect >= cxx11 && !INTEGRAL_OR_ENUMERATION_TYPE_P (type))
10240     {
10241       if (!COMPLETE_TYPE_P (type))
10242 	error_at (DECL_SOURCE_LOCATION (decl),
10243 		  "in-class initialization of static data member %q#D of "
10244 		  "incomplete type", decl);
10245       else if (literal_type_p (type))
10246 	permerror (DECL_SOURCE_LOCATION (decl),
10247 		   "%<constexpr%> needed for in-class initialization of "
10248 		   "static data member %q#D of non-integral type", decl);
10249       else
10250 	error_at (DECL_SOURCE_LOCATION (decl),
10251 		  "in-class initialization of static data member %q#D of "
10252 		  "non-literal type", decl);
10253     }
10254   /* Motion 10 at San Diego: If a static const integral data member is
10255      initialized with an integral constant expression, the initializer
10256      may appear either in the declaration (within the class), or in
10257      the definition, but not both.  If it appears in the class, the
10258      member is a member constant.  The file-scope definition is always
10259      required.  */
10260   else if (!ARITHMETIC_TYPE_P (type) && TREE_CODE (type) != ENUMERAL_TYPE)
10261     error_at (DECL_SOURCE_LOCATION (decl),
10262 	      "invalid in-class initialization of static data member "
10263 	      "of non-integral type %qT",
10264 	      type);
10265   else if (!CP_TYPE_CONST_P (type))
10266     error_at (DECL_SOURCE_LOCATION (decl),
10267 	      "ISO C++ forbids in-class initialization of non-const "
10268 	      "static member %qD",
10269 	      decl);
10270   else if (!INTEGRAL_OR_ENUMERATION_TYPE_P (type))
10271     pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wpedantic,
10272 	     "ISO C++ forbids initialization of member constant "
10273 	     "%qD of non-integral type %qT", decl, type);
10274 }
10275 
10276 /* *expr_p is part of the TYPE_SIZE of a variably-sized array.  If any
10277    SAVE_EXPRs in *expr_p wrap expressions with side-effects, break those
10278    expressions out into temporary variables so that walk_tree doesn't
10279    step into them (c++/15764).  */
10280 
10281 static tree
stabilize_save_expr_r(tree * expr_p,int * walk_subtrees,void * data)10282 stabilize_save_expr_r (tree *expr_p, int *walk_subtrees, void *data)
10283 {
10284   hash_set<tree> *pset = (hash_set<tree> *)data;
10285   tree expr = *expr_p;
10286   if (TREE_CODE (expr) == SAVE_EXPR)
10287     {
10288       tree op = TREE_OPERAND (expr, 0);
10289       cp_walk_tree (&op, stabilize_save_expr_r, data, pset);
10290       if (TREE_SIDE_EFFECTS (op))
10291 	TREE_OPERAND (expr, 0) = get_temp_regvar (TREE_TYPE (op), op);
10292       *walk_subtrees = 0;
10293     }
10294   else if (!EXPR_P (expr) || !TREE_SIDE_EFFECTS (expr))
10295     *walk_subtrees = 0;
10296   return NULL;
10297 }
10298 
10299 /* Entry point for the above.  */
10300 
10301 static void
stabilize_vla_size(tree size)10302 stabilize_vla_size (tree size)
10303 {
10304   hash_set<tree> pset;
10305   /* Break out any function calls into temporary variables.  */
10306   cp_walk_tree (&size, stabilize_save_expr_r, &pset, &pset);
10307 }
10308 
10309 /* Reduce a SIZEOF_EXPR to its value.  */
10310 
10311 tree
fold_sizeof_expr(tree t)10312 fold_sizeof_expr (tree t)
10313 {
10314   tree r;
10315   if (SIZEOF_EXPR_TYPE_P (t))
10316     r = cxx_sizeof_or_alignof_type (EXPR_LOCATION (t),
10317 				    TREE_TYPE (TREE_OPERAND (t, 0)),
10318 				    SIZEOF_EXPR, false, false);
10319   else if (TYPE_P (TREE_OPERAND (t, 0)))
10320     r = cxx_sizeof_or_alignof_type (EXPR_LOCATION (t),
10321 				    TREE_OPERAND (t, 0), SIZEOF_EXPR,
10322 				    false, false);
10323   else
10324     r = cxx_sizeof_or_alignof_expr (EXPR_LOCATION (t),
10325 				    TREE_OPERAND (t, 0), SIZEOF_EXPR,
10326 				    false);
10327   if (r == error_mark_node)
10328     r = size_one_node;
10329   return r;
10330 }
10331 
10332 /* Given the SIZE (i.e., number of elements) in an array, compute
10333    an appropriate index type for the array.  If non-NULL, NAME is
10334    the name of the entity being declared.  */
10335 
10336 static tree
compute_array_index_type_loc(location_t name_loc,tree name,tree size,tsubst_flags_t complain)10337 compute_array_index_type_loc (location_t name_loc, tree name, tree size,
10338 			      tsubst_flags_t complain)
10339 {
10340   if (error_operand_p (size))
10341     return error_mark_node;
10342 
10343   /* The type of the index being computed.  */
10344   tree itype;
10345 
10346   /* The original numeric size as seen in the source code before
10347      conversion to size_t.  */
10348   tree origsize = size;
10349 
10350   location_t loc = cp_expr_loc_or_loc (size, name ? name_loc : input_location);
10351 
10352   if (!type_dependent_expression_p (size))
10353     {
10354       origsize = size = mark_rvalue_use (size);
10355 
10356       if (cxx_dialect < cxx11 && TREE_CODE (size) == NOP_EXPR
10357 	  && TREE_SIDE_EFFECTS (size))
10358 	/* In C++98, we mark a non-constant array bound with a magic
10359 	   NOP_EXPR with TREE_SIDE_EFFECTS; don't fold in that case.  */;
10360       else
10361 	{
10362 	  size = build_converted_constant_expr (size_type_node, size, complain);
10363 	  /* Pedantically a constant expression is required here and so
10364 	     __builtin_is_constant_evaluated () should fold to true if it
10365 	     is successfully folded into a constant.  */
10366 	  size = fold_non_dependent_expr (size, complain,
10367 					  /*manifestly_const_eval=*/true);
10368 
10369 	  if (!TREE_CONSTANT (size))
10370 	    size = origsize;
10371 	}
10372 
10373       if (error_operand_p (size))
10374 	return error_mark_node;
10375 
10376       /* The array bound must be an integer type.  */
10377       tree type = TREE_TYPE (size);
10378       if (!INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P (type))
10379 	{
10380 	  if (!(complain & tf_error))
10381 	    return error_mark_node;
10382 	  if (name)
10383 	    error_at (loc, "size of array %qD has non-integral type %qT",
10384 		      name, type);
10385 	  else
10386 	    error_at (loc, "size of array has non-integral type %qT", type);
10387 	  size = integer_one_node;
10388 	}
10389     }
10390 
10391   /* A type is dependent if it is...an array type constructed from any
10392      dependent type or whose size is specified by a constant expression
10393      that is value-dependent.  */
10394   /* We can only call value_dependent_expression_p on integral constant
10395      expressions; treat non-constant expressions as dependent, too.  */
10396   if (processing_template_decl
10397       && (!TREE_CONSTANT (size) || value_dependent_expression_p (size)))
10398     {
10399       /* We cannot do any checking for a SIZE that isn't known to be
10400 	 constant. Just build the index type and mark that it requires
10401 	 structural equality checks.  */
10402       itype = build_index_type (build_min (MINUS_EXPR, sizetype,
10403 					   size, size_one_node));
10404       TYPE_DEPENDENT_P (itype) = 1;
10405       TYPE_DEPENDENT_P_VALID (itype) = 1;
10406       SET_TYPE_STRUCTURAL_EQUALITY (itype);
10407       return itype;
10408     }
10409 
10410   if (TREE_CODE (size) != INTEGER_CST)
10411     {
10412       tree folded = cp_fully_fold (size);
10413       if (TREE_CODE (folded) == INTEGER_CST)
10414 	{
10415 	  if (name)
10416 	    pedwarn (loc, OPT_Wpedantic, "size of array %qD is not an "
10417 		     "integral constant-expression", name);
10418 	  else
10419 	    pedwarn (loc, OPT_Wpedantic,
10420 		     "size of array is not an integral constant-expression");
10421 	}
10422       if (TREE_CONSTANT (size) && !TREE_CONSTANT (folded))
10423 	/* We might have lost the TREE_CONSTANT flag e.g. when we are
10424 	   folding a conversion from a pointer to integral type.  In that
10425 	   case issue an error below and don't treat this as a VLA.  */;
10426       else
10427 	/* Use the folded result for VLAs, too; it will have resolved
10428 	   SIZEOF_EXPR.  */
10429 	size = folded;
10430     }
10431 
10432   /* Normally, the array-bound will be a constant.  */
10433   if (TREE_CODE (size) == INTEGER_CST)
10434     {
10435       /* The size to use in diagnostics that reflects the constant
10436 	 size used in the source, rather than SIZE massaged above.  */
10437       tree diagsize = size;
10438 
10439       /* If the original size before conversion to size_t was signed
10440 	 and negative, convert it to ssizetype to restore the sign.  */
10441       if (!TYPE_UNSIGNED (TREE_TYPE (origsize))
10442 	  && TREE_CODE (size) == INTEGER_CST
10443 	  && tree_int_cst_sign_bit (size))
10444 	{
10445 	  diagsize = fold_convert (ssizetype, size);
10446 
10447 	  /* Clear the overflow bit that may have been set as a result
10448 	     of the conversion from the sizetype of the new size to
10449 	     ssizetype.  */
10450 	  TREE_OVERFLOW (diagsize) = false;
10451 	}
10452 
10453       /* Verify that the array has a positive number of elements
10454 	 and issue the appropriate diagnostic if it doesn't.  */
10455       if (!valid_array_size_p (loc, diagsize, name, (complain & tf_error)))
10456 	{
10457 	  if (!(complain & tf_error))
10458 	    return error_mark_node;
10459 	  size = integer_one_node;
10460 	}
10461       /* As an extension we allow zero-sized arrays.  */
10462       else if (integer_zerop (size))
10463 	{
10464 	  if (!(complain & tf_error))
10465 	    /* We must fail if performing argument deduction (as
10466 	       indicated by the state of complain), so that
10467 	       another substitution can be found.  */
10468 	    return error_mark_node;
10469 	  else if (name)
10470 	    pedwarn (loc, OPT_Wpedantic,
10471 		     "ISO C++ forbids zero-size array %qD", name);
10472 	  else
10473 	    pedwarn (loc, OPT_Wpedantic,
10474 		     "ISO C++ forbids zero-size array");
10475 	}
10476     }
10477   else if (TREE_CONSTANT (size)
10478 	   /* We don't allow VLAs at non-function scopes, or during
10479 	      tentative template substitution.  */
10480 	   || !at_function_scope_p ()
10481 	   || !(complain & tf_error))
10482     {
10483       if (!(complain & tf_error))
10484 	return error_mark_node;
10485       /* `(int) &fn' is not a valid array bound.  */
10486       if (name)
10487 	error_at (loc,
10488 		  "size of array %qD is not an integral constant-expression",
10489 		  name);
10490       else
10491 	error_at (loc, "size of array is not an integral constant-expression");
10492       size = integer_one_node;
10493     }
10494   else if (pedantic && warn_vla != 0)
10495     {
10496       if (name)
10497 	pedwarn (name_loc, OPT_Wvla,
10498 		 "ISO C++ forbids variable length array %qD", name);
10499       else
10500 	pedwarn (input_location, OPT_Wvla,
10501 		 "ISO C++ forbids variable length array");
10502     }
10503   else if (warn_vla > 0)
10504     {
10505       if (name)
10506 	warning_at (name_loc, OPT_Wvla,
10507 		    "variable length array %qD is used", name);
10508       else
10509 	warning (OPT_Wvla,
10510                  "variable length array is used");
10511     }
10512 
10513   if (processing_template_decl && !TREE_CONSTANT (size))
10514     /* A variable sized array.  */
10515     itype = build_min (MINUS_EXPR, sizetype, size, integer_one_node);
10516   else
10517     {
10518       /* Compute the index of the largest element in the array.  It is
10519 	 one less than the number of elements in the array.  We save
10520 	 and restore PROCESSING_TEMPLATE_DECL so that computations in
10521 	 cp_build_binary_op will be appropriately folded.  */
10522       {
10523 	processing_template_decl_sentinel s;
10524 	itype = cp_build_binary_op (input_location,
10525 				    MINUS_EXPR,
10526 				    cp_convert (ssizetype, size, complain),
10527 				    cp_convert (ssizetype, integer_one_node,
10528 						complain),
10529 				    complain);
10530 	itype = maybe_constant_value (itype);
10531       }
10532 
10533       if (!TREE_CONSTANT (itype))
10534 	{
10535 	  /* A variable sized array.  */
10536 	  itype = variable_size (itype);
10537 
10538 	  stabilize_vla_size (itype);
10539 
10540 	  if (sanitize_flags_p (SANITIZE_VLA)
10541 	      && current_function_decl != NULL_TREE)
10542 	    {
10543 	      /* We have to add 1 -- in the ubsan routine we generate
10544 		 LE_EXPR rather than LT_EXPR.  */
10545 	      tree t = fold_build2 (PLUS_EXPR, TREE_TYPE (itype), itype,
10546 				    build_one_cst (TREE_TYPE (itype)));
10547 	      t = ubsan_instrument_vla (input_location, t);
10548 	      finish_expr_stmt (t);
10549 	    }
10550 	}
10551       /* Make sure that there was no overflow when creating to a signed
10552 	 index type.  (For example, on a 32-bit machine, an array with
10553 	 size 2^32 - 1 is too big.)  */
10554       else if (TREE_CODE (itype) == INTEGER_CST
10555 	       && TREE_OVERFLOW (itype))
10556 	{
10557 	  if (!(complain & tf_error))
10558 	    return error_mark_node;
10559 	  error ("overflow in array dimension");
10560 	  TREE_OVERFLOW (itype) = 0;
10561 	}
10562     }
10563 
10564   /* Create and return the appropriate index type.  */
10565   itype = build_index_type (itype);
10566 
10567   /* If the index type were dependent, we would have returned early, so
10568      remember that it isn't.  */
10569   TYPE_DEPENDENT_P (itype) = 0;
10570   TYPE_DEPENDENT_P_VALID (itype) = 1;
10571   return itype;
10572 }
10573 
10574 tree
compute_array_index_type(tree name,tree size,tsubst_flags_t complain)10575 compute_array_index_type (tree name, tree size, tsubst_flags_t complain)
10576 {
10577   return compute_array_index_type_loc (input_location, name, size, complain);
10578 }
10579 
10580 /* Returns the scope (if any) in which the entity declared by
10581    DECLARATOR will be located.  If the entity was declared with an
10582    unqualified name, NULL_TREE is returned.  */
10583 
10584 tree
get_scope_of_declarator(const cp_declarator * declarator)10585 get_scope_of_declarator (const cp_declarator *declarator)
10586 {
10587   while (declarator && declarator->kind != cdk_id)
10588     declarator = declarator->declarator;
10589 
10590   /* If the declarator-id is a SCOPE_REF, the scope in which the
10591      declaration occurs is the first operand.  */
10592   if (declarator
10593       && declarator->u.id.qualifying_scope)
10594     return declarator->u.id.qualifying_scope;
10595 
10596   /* Otherwise, the declarator is not a qualified name; the entity will
10597      be declared in the current scope.  */
10598   return NULL_TREE;
10599 }
10600 
10601 /* Returns an ARRAY_TYPE for an array with SIZE elements of the
10602    indicated TYPE.  If non-NULL, NAME is the NAME of the declaration
10603    with this type.  */
10604 
10605 static tree
create_array_type_for_decl(tree name,tree type,tree size,location_t loc)10606 create_array_type_for_decl (tree name, tree type, tree size, location_t loc)
10607 {
10608   tree itype = NULL_TREE;
10609 
10610   /* If things have already gone awry, bail now.  */
10611   if (type == error_mark_node || size == error_mark_node)
10612     return error_mark_node;
10613 
10614   /* 8.3.4/1: If the type of the identifier of D contains the auto
10615      type-specifier, the program is ill-formed.  */
10616   if (type_uses_auto (type))
10617     {
10618       if (name)
10619 	error_at (loc, "%qD declared as array of %qT", name, type);
10620       else
10621 	error ("creating array of %qT", type);
10622       return error_mark_node;
10623     }
10624 
10625   /* If there are some types which cannot be array elements,
10626      issue an error-message and return.  */
10627   switch (TREE_CODE (type))
10628     {
10629     case VOID_TYPE:
10630       if (name)
10631 	error_at (loc, "declaration of %qD as array of void", name);
10632       else
10633         error ("creating array of void");
10634       return error_mark_node;
10635 
10636     case FUNCTION_TYPE:
10637       if (name)
10638 	error_at (loc, "declaration of %qD as array of functions", name);
10639       else
10640         error ("creating array of functions");
10641       return error_mark_node;
10642 
10643     case REFERENCE_TYPE:
10644       if (name)
10645 	error_at (loc, "declaration of %qD as array of references", name);
10646       else
10647         error ("creating array of references");
10648       return error_mark_node;
10649 
10650     case METHOD_TYPE:
10651       if (name)
10652 	error_at (loc, "declaration of %qD as array of function members",
10653 		  name);
10654       else
10655         error ("creating array of function members");
10656       return error_mark_node;
10657 
10658     default:
10659       break;
10660     }
10661 
10662   if (!verify_type_context (name ? loc : input_location,
10663 			    TCTX_ARRAY_ELEMENT, type))
10664     return error_mark_node;
10665 
10666   /* [dcl.array]
10667 
10668      The constant expressions that specify the bounds of the arrays
10669      can be omitted only for the first member of the sequence.  */
10670   if (TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type))
10671     {
10672       if (name)
10673 	error_at (loc, "declaration of %qD as multidimensional array must "
10674 		  "have bounds for all dimensions except the first",
10675 		  name);
10676       else
10677 	error ("multidimensional array must have bounds for all "
10678 	       "dimensions except the first");
10679 
10680       return error_mark_node;
10681     }
10682 
10683   /* Figure out the index type for the array.  */
10684   if (size)
10685     itype = compute_array_index_type_loc (loc, name, size,
10686 					  tf_warning_or_error);
10687 
10688   /* [dcl.array]
10689      T is called the array element type; this type shall not be [...] an
10690      abstract class type.  */
10691   abstract_virtuals_error (name, type);
10692 
10693   return build_cplus_array_type (type, itype);
10694 }
10695 
10696 /* Returns the smallest location that is not UNKNOWN_LOCATION.  */
10697 
10698 static location_t
min_location(location_t loca,location_t locb)10699 min_location (location_t loca, location_t locb)
10700 {
10701   if (loca == UNKNOWN_LOCATION
10702       || (locb != UNKNOWN_LOCATION
10703 	  && linemap_location_before_p (line_table, locb, loca)))
10704     return locb;
10705   return loca;
10706 }
10707 
10708 /* Returns the smallest location != UNKNOWN_LOCATION among the
10709    three stored in LOCATIONS[ds_const], LOCATIONS[ds_volatile],
10710    and LOCATIONS[ds_restrict].  */
10711 
10712 static location_t
smallest_type_quals_location(int type_quals,const location_t * locations)10713 smallest_type_quals_location (int type_quals, const location_t* locations)
10714 {
10715   location_t loc = UNKNOWN_LOCATION;
10716 
10717   if (type_quals & TYPE_QUAL_CONST)
10718     loc = locations[ds_const];
10719 
10720   if (type_quals & TYPE_QUAL_VOLATILE)
10721     loc = min_location (loc, locations[ds_volatile]);
10722 
10723   if (type_quals & TYPE_QUAL_RESTRICT)
10724     loc = min_location (loc, locations[ds_restrict]);
10725 
10726   return loc;
10727 }
10728 
10729 /* Returns the smallest among the latter and locations[ds_type_spec].  */
10730 
10731 static location_t
smallest_type_location(int type_quals,const location_t * locations)10732 smallest_type_location (int type_quals, const location_t* locations)
10733 {
10734   location_t loc = smallest_type_quals_location (type_quals, locations);
10735   return min_location (loc, locations[ds_type_spec]);
10736 }
10737 
10738 static location_t
smallest_type_location(const cp_decl_specifier_seq * declspecs)10739 smallest_type_location (const cp_decl_specifier_seq *declspecs)
10740 {
10741   int type_quals = get_type_quals (declspecs);
10742   return smallest_type_location (type_quals, declspecs->locations);
10743 }
10744 
10745 /* Check that it's OK to declare a function with the indicated TYPE
10746    and TYPE_QUALS.  SFK indicates the kind of special function (if any)
10747    that this function is.  OPTYPE is the type given in a conversion
10748    operator declaration, or the class type for a constructor/destructor.
10749    Returns the actual return type of the function; that may be different
10750    than TYPE if an error occurs, or for certain special functions.  */
10751 
10752 static tree
check_special_function_return_type(special_function_kind sfk,tree type,tree optype,int type_quals,const location_t * locations)10753 check_special_function_return_type (special_function_kind sfk,
10754 				    tree type,
10755 				    tree optype,
10756 				    int type_quals,
10757 				    const location_t* locations)
10758 {
10759   switch (sfk)
10760     {
10761     case sfk_constructor:
10762       if (type)
10763 	error_at (smallest_type_location (type_quals, locations),
10764 		  "return type specification for constructor invalid");
10765       else if (type_quals != TYPE_UNQUALIFIED)
10766 	error_at (smallest_type_quals_location (type_quals, locations),
10767 		  "qualifiers are not allowed on constructor declaration");
10768 
10769       if (targetm.cxx.cdtor_returns_this ())
10770 	type = build_pointer_type (optype);
10771       else
10772 	type = void_type_node;
10773       break;
10774 
10775     case sfk_destructor:
10776       if (type)
10777 	error_at (smallest_type_location (type_quals, locations),
10778 		  "return type specification for destructor invalid");
10779       else if (type_quals != TYPE_UNQUALIFIED)
10780 	error_at (smallest_type_quals_location (type_quals, locations),
10781 		  "qualifiers are not allowed on destructor declaration");
10782 
10783       /* We can't use the proper return type here because we run into
10784 	 problems with ambiguous bases and covariant returns.  */
10785       if (targetm.cxx.cdtor_returns_this ())
10786 	type = build_pointer_type (void_type_node);
10787       else
10788 	type = void_type_node;
10789       break;
10790 
10791     case sfk_conversion:
10792       if (type)
10793 	error_at (smallest_type_location (type_quals, locations),
10794 		  "return type specified for %<operator %T%>", optype);
10795       else if (type_quals != TYPE_UNQUALIFIED)
10796 	error_at (smallest_type_quals_location (type_quals, locations),
10797 		  "qualifiers are not allowed on declaration of "
10798 		  "%<operator %T%>", optype);
10799 
10800       type = optype;
10801       break;
10802 
10803     case sfk_deduction_guide:
10804       if (type)
10805 	error_at (smallest_type_location (type_quals, locations),
10806 		  "return type specified for deduction guide");
10807       else if (type_quals != TYPE_UNQUALIFIED)
10808 	error_at (smallest_type_quals_location (type_quals, locations),
10809 		  "qualifiers are not allowed on declaration of "
10810 		  "deduction guide");
10811       if (TREE_CODE (optype) == TEMPLATE_TEMPLATE_PARM)
10812 	{
10813 	  error ("template template parameter %qT in declaration of "
10814 		 "deduction guide", optype);
10815 	  type = error_mark_node;
10816 	}
10817       else
10818 	type = make_template_placeholder (CLASSTYPE_TI_TEMPLATE (optype));
10819       for (int i = 0; i < ds_last; ++i)
10820 	if (i != ds_explicit && locations[i])
10821 	  error_at (locations[i],
10822 		    "%<decl-specifier%> in declaration of deduction guide");
10823       break;
10824 
10825     default:
10826       gcc_unreachable ();
10827     }
10828 
10829   return type;
10830 }
10831 
10832 /* A variable or data member (whose unqualified name is IDENTIFIER)
10833    has been declared with the indicated TYPE.  If the TYPE is not
10834    acceptable, issue an error message and return a type to use for
10835    error-recovery purposes.  */
10836 
10837 tree
check_var_type(tree identifier,tree type,location_t loc)10838 check_var_type (tree identifier, tree type, location_t loc)
10839 {
10840   if (VOID_TYPE_P (type))
10841     {
10842       if (!identifier)
10843 	error_at (loc, "unnamed variable or field declared void");
10844       else if (identifier_p (identifier))
10845 	{
10846 	  gcc_assert (!IDENTIFIER_ANY_OP_P (identifier));
10847 	  error_at (loc, "variable or field %qE declared void",
10848 		    identifier);
10849 	}
10850       else
10851 	error_at (loc, "variable or field declared void");
10852       type = error_mark_node;
10853     }
10854 
10855   return type;
10856 }
10857 
10858 /* Handle declaring DECL as an inline variable.  */
10859 
10860 static void
mark_inline_variable(tree decl,location_t loc)10861 mark_inline_variable (tree decl, location_t loc)
10862 {
10863   bool inlinep = true;
10864   if (! toplevel_bindings_p ())
10865     {
10866       error_at (loc, "%<inline%> specifier invalid for variable "
10867 		"%qD declared at block scope", decl);
10868       inlinep = false;
10869     }
10870   else if (cxx_dialect < cxx17)
10871     pedwarn (loc, 0, "inline variables are only available "
10872 	     "with %<-std=c++17%> or %<-std=gnu++17%>");
10873   if (inlinep)
10874     {
10875       retrofit_lang_decl (decl);
10876       SET_DECL_VAR_DECLARED_INLINE_P (decl);
10877     }
10878 }
10879 
10880 
10881 /* Assign a typedef-given name to a class or enumeration type declared
10882    as anonymous at first.  This was split out of grokdeclarator
10883    because it is also used in libcc1.  */
10884 
10885 void
name_unnamed_type(tree type,tree decl)10886 name_unnamed_type (tree type, tree decl)
10887 {
10888   gcc_assert (TYPE_UNNAMED_P (type));
10889 
10890   /* Replace the anonymous name with the real name everywhere.  */
10891   for (tree t = TYPE_MAIN_VARIANT (type); t; t = TYPE_NEXT_VARIANT (t))
10892     if (IDENTIFIER_ANON_P (TYPE_IDENTIFIER (t)))
10893       /* We do not rename the debug info representing the unnamed
10894 	 tagged type because the standard says in [dcl.typedef] that
10895 	 the naming applies only for linkage purposes.  */
10896       /*debug_hooks->set_name (t, decl);*/
10897       TYPE_NAME (t) = decl;
10898 
10899   /* If this is a typedef within a template class, the nested
10900      type is a (non-primary) template.  The name for the
10901      template needs updating as well.  */
10902   if (TYPE_LANG_SPECIFIC (type) && CLASSTYPE_TEMPLATE_INFO (type))
10903     DECL_NAME (CLASSTYPE_TI_TEMPLATE (type))
10904       = TYPE_IDENTIFIER (type);
10905 
10906   /* Adjust linkage now that we aren't unnamed anymore.  */
10907   reset_type_linkage (type);
10908 
10909   /* FIXME remangle member functions; member functions of a
10910      type with external linkage have external linkage.  */
10911 
10912   /* Check that our job is done, and that it would fail if we
10913      attempted to do it again.  */
10914   gcc_assert (!TYPE_UNNAMED_P (type));
10915 }
10916 
10917 /* Given declspecs and a declarator (abstract or otherwise), determine
10918    the name and type of the object declared and construct a DECL node
10919    for it.
10920 
10921    DECLSPECS points to the representation of declaration-specifier
10922    sequence that precedes declarator.
10923 
10924    DECL_CONTEXT says which syntactic context this declaration is in:
10925      NORMAL for most contexts.  Make a VAR_DECL or FUNCTION_DECL or TYPE_DECL.
10926      FUNCDEF for a function definition.  Like NORMAL but a few different
10927       error messages in each case.  Return value may be zero meaning
10928       this definition is too screwy to try to parse.
10929      MEMFUNCDEF for a function definition.  Like FUNCDEF but prepares to
10930       handle member functions (which have FIELD context).
10931       Return value may be zero meaning this definition is too screwy to
10932       try to parse.
10933      PARM for a parameter declaration (either within a function prototype
10934       or before a function body).  Make a PARM_DECL, or return void_type_node.
10935      TPARM for a template parameter declaration.
10936      CATCHPARM for a parameter declaration before a catch clause.
10937      TYPENAME if for a typename (in a cast or sizeof).
10938       Don't make a DECL node; just return the ..._TYPE node.
10939      FIELD for a struct or union field; make a FIELD_DECL.
10940      BITFIELD for a field with specified width.
10941 
10942    INITIALIZED is as for start_decl.
10943 
10944    ATTRLIST is a pointer to the list of attributes, which may be NULL
10945    if there are none; *ATTRLIST may be modified if attributes from inside
10946    the declarator should be applied to the declaration.
10947 
10948    When this function is called, scoping variables (such as
10949    CURRENT_CLASS_TYPE) should reflect the scope in which the
10950    declaration occurs, not the scope in which the new declaration will
10951    be placed.  For example, on:
10952 
10953      void S::f() { ... }
10954 
10955    when grokdeclarator is called for `S::f', the CURRENT_CLASS_TYPE
10956    should not be `S'.
10957 
10958    Returns a DECL (if a declarator is present), a TYPE (if there is no
10959    declarator, in cases like "struct S;"), or the ERROR_MARK_NODE if an
10960    error occurs. */
10961 
10962 tree
grokdeclarator(const cp_declarator * declarator,cp_decl_specifier_seq * declspecs,enum decl_context decl_context,int initialized,tree * attrlist)10963 grokdeclarator (const cp_declarator *declarator,
10964 		cp_decl_specifier_seq *declspecs,
10965 		enum decl_context decl_context,
10966 		int initialized,
10967 		tree* attrlist)
10968 {
10969   tree type = NULL_TREE;
10970   int longlong = 0;
10971   int explicit_intN = 0;
10972   int int_n_alt = 0;
10973   int virtualp, explicitp, friendp, inlinep, staticp;
10974   int explicit_int = 0;
10975   int explicit_char = 0;
10976   int defaulted_int = 0;
10977 
10978   tree typedef_decl = NULL_TREE;
10979   const char *name = NULL;
10980   tree typedef_type = NULL_TREE;
10981   /* True if this declarator is a function definition.  */
10982   bool funcdef_flag = false;
10983   cp_declarator_kind innermost_code = cdk_error;
10984   int bitfield = 0;
10985 #if 0
10986   /* See the code below that used this.  */
10987   tree decl_attr = NULL_TREE;
10988 #endif
10989 
10990   /* Keep track of what sort of function is being processed
10991      so that we can warn about default return values, or explicit
10992      return values which do not match prescribed defaults.  */
10993   special_function_kind sfk = sfk_none;
10994 
10995   tree dname = NULL_TREE;
10996   tree ctor_return_type = NULL_TREE;
10997   enum overload_flags flags = NO_SPECIAL;
10998   /* cv-qualifiers that apply to the declarator, for a declaration of
10999      a member function.  */
11000   cp_cv_quals memfn_quals = TYPE_UNQUALIFIED;
11001   /* virt-specifiers that apply to the declarator, for a declaration of
11002      a member function.  */
11003   cp_virt_specifiers virt_specifiers = VIRT_SPEC_UNSPECIFIED;
11004   /* ref-qualifier that applies to the declarator, for a declaration of
11005      a member function.  */
11006   cp_ref_qualifier rqual = REF_QUAL_NONE;
11007   /* cv-qualifiers that apply to the type specified by the DECLSPECS.  */
11008   int type_quals = get_type_quals (declspecs);
11009   tree raises = NULL_TREE;
11010   int template_count = 0;
11011   tree returned_attrs = NULL_TREE;
11012   tree parms = NULL_TREE;
11013   const cp_declarator *id_declarator;
11014   /* The unqualified name of the declarator; either an
11015      IDENTIFIER_NODE, BIT_NOT_EXPR, or TEMPLATE_ID_EXPR.  */
11016   tree unqualified_id;
11017   /* The class type, if any, in which this entity is located,
11018      or NULL_TREE if none.  Note that this value may be different from
11019      the current class type; for example if an attempt is made to declare
11020      "A::f" inside "B", this value will be "A".  */
11021   tree ctype = current_class_type;
11022   /* The NAMESPACE_DECL for the namespace in which this entity is
11023      located.  If an unqualified name is used to declare the entity,
11024      this value will be NULL_TREE, even if the entity is located at
11025      namespace scope.  */
11026   tree in_namespace = NULL_TREE;
11027   cp_storage_class storage_class;
11028   bool unsigned_p, signed_p, short_p, long_p, thread_p;
11029   bool type_was_error_mark_node = false;
11030   bool parameter_pack_p = declarator ? declarator->parameter_pack_p : false;
11031   bool template_type_arg = false;
11032   bool template_parm_flag = false;
11033   bool typedef_p = decl_spec_seq_has_spec_p (declspecs, ds_typedef);
11034   bool constexpr_p = decl_spec_seq_has_spec_p (declspecs, ds_constexpr);
11035   bool constinit_p = decl_spec_seq_has_spec_p (declspecs, ds_constinit);
11036   bool consteval_p = decl_spec_seq_has_spec_p (declspecs, ds_consteval);
11037   bool late_return_type_p = false;
11038   bool array_parameter_p = false;
11039   tree reqs = NULL_TREE;
11040 
11041   signed_p = decl_spec_seq_has_spec_p (declspecs, ds_signed);
11042   unsigned_p = decl_spec_seq_has_spec_p (declspecs, ds_unsigned);
11043   short_p = decl_spec_seq_has_spec_p (declspecs, ds_short);
11044   long_p = decl_spec_seq_has_spec_p (declspecs, ds_long);
11045   longlong = decl_spec_seq_has_spec_p (declspecs, ds_long_long);
11046   explicit_intN = declspecs->explicit_intN_p;
11047   int_n_alt = declspecs->int_n_alt;
11048   thread_p = decl_spec_seq_has_spec_p (declspecs, ds_thread);
11049 
11050   // Was concept_p specified? Note that ds_concept
11051   // implies ds_constexpr!
11052   bool concept_p = decl_spec_seq_has_spec_p (declspecs, ds_concept);
11053   if (concept_p)
11054     constexpr_p = true;
11055 
11056   if (decl_context == FUNCDEF)
11057     funcdef_flag = true, decl_context = NORMAL;
11058   else if (decl_context == MEMFUNCDEF)
11059     funcdef_flag = true, decl_context = FIELD;
11060   else if (decl_context == BITFIELD)
11061     bitfield = 1, decl_context = FIELD;
11062   else if (decl_context == TEMPLATE_TYPE_ARG)
11063     template_type_arg = true, decl_context = TYPENAME;
11064   else if (decl_context == TPARM)
11065     template_parm_flag = true, decl_context = PARM;
11066 
11067   if (initialized > 1)
11068     funcdef_flag = true;
11069 
11070   location_t typespec_loc = smallest_type_location (type_quals,
11071 						    declspecs->locations);
11072   if (typespec_loc == UNKNOWN_LOCATION)
11073     typespec_loc = input_location;
11074 
11075   location_t id_loc = declarator ? declarator->id_loc : input_location;
11076   if (id_loc == UNKNOWN_LOCATION)
11077     id_loc = input_location;
11078 
11079   /* Look inside a declarator for the name being declared
11080      and get it as a string, for an error message.  */
11081   for (id_declarator = declarator;
11082        id_declarator;
11083        id_declarator = id_declarator->declarator)
11084     {
11085       if (id_declarator->kind != cdk_id)
11086 	innermost_code = id_declarator->kind;
11087 
11088       switch (id_declarator->kind)
11089 	{
11090 	case cdk_function:
11091 	  if (id_declarator->declarator
11092 	      && id_declarator->declarator->kind == cdk_id)
11093 	    {
11094 	      sfk = id_declarator->declarator->u.id.sfk;
11095 	      if (sfk == sfk_destructor)
11096 		flags = DTOR_FLAG;
11097 	    }
11098 	  break;
11099 
11100 	case cdk_id:
11101 	  {
11102 	    tree qualifying_scope = id_declarator->u.id.qualifying_scope;
11103 	    tree decl = id_declarator->u.id.unqualified_name;
11104 	    if (!decl)
11105 	      break;
11106 	    if (qualifying_scope)
11107 	      {
11108 		if (check_for_bare_parameter_packs (qualifying_scope,
11109 						    id_declarator->id_loc))
11110 		  return error_mark_node;
11111 		if (at_function_scope_p ())
11112 		  {
11113 		    /* [dcl.meaning]
11114 
11115 		       A declarator-id shall not be qualified except
11116 		       for ...
11117 
11118 		       None of the cases are permitted in block
11119 		       scope.  */
11120 		    if (qualifying_scope == global_namespace)
11121 		      error ("invalid use of qualified-name %<::%D%>",
11122 			     decl);
11123 		    else if (TYPE_P (qualifying_scope))
11124 		      error ("invalid use of qualified-name %<%T::%D%>",
11125 			     qualifying_scope, decl);
11126 		    else
11127 		      error ("invalid use of qualified-name %<%D::%D%>",
11128 			     qualifying_scope, decl);
11129 		    return error_mark_node;
11130 		  }
11131 		else if (TYPE_P (qualifying_scope))
11132 		  {
11133 		    ctype = qualifying_scope;
11134 		    if (!MAYBE_CLASS_TYPE_P (ctype))
11135 		      {
11136 			error_at (id_declarator->id_loc,
11137 				  "%q#T is not a class or namespace", ctype);
11138 			ctype = NULL_TREE;
11139 		      }
11140 		    else if (innermost_code != cdk_function
11141 			     && current_class_type
11142 			     && !uniquely_derived_from_p (ctype,
11143 							  current_class_type))
11144 		      {
11145 			error_at (id_declarator->id_loc,
11146 				  "invalid use of qualified-name %<%T::%D%>",
11147 				  qualifying_scope, decl);
11148 			return error_mark_node;
11149 		      }
11150 		  }
11151 		else if (TREE_CODE (qualifying_scope) == NAMESPACE_DECL)
11152 		  in_namespace = qualifying_scope;
11153 	      }
11154 	    switch (TREE_CODE (decl))
11155 	      {
11156 	      case BIT_NOT_EXPR:
11157 		{
11158 		  if (innermost_code != cdk_function)
11159 		    {
11160 		      error_at (EXPR_LOCATION (decl),
11161 				"declaration of %qE as non-function", decl);
11162 		      return error_mark_node;
11163 		    }
11164 		  else if (!qualifying_scope
11165 			   && !(current_class_type && at_class_scope_p ()))
11166 		    {
11167 		      error_at (EXPR_LOCATION (decl),
11168 				"declaration of %qE as non-member", decl);
11169 		      return error_mark_node;
11170 		    }
11171 
11172 		  tree type = TREE_OPERAND (decl, 0);
11173 		  if (TYPE_P (type))
11174 		    type = constructor_name (type);
11175 		  name = identifier_to_locale (IDENTIFIER_POINTER (type));
11176 		  dname = decl;
11177 		}
11178 		break;
11179 
11180 	      case TEMPLATE_ID_EXPR:
11181 		{
11182 		  tree fns = TREE_OPERAND (decl, 0);
11183 
11184 		  dname = fns;
11185 		  if (!identifier_p (dname))
11186 		    dname = OVL_NAME (dname);
11187 		}
11188 		/* Fall through.  */
11189 
11190 	      case IDENTIFIER_NODE:
11191 		if (identifier_p (decl))
11192 		  dname = decl;
11193 
11194 		if (IDENTIFIER_KEYWORD_P (dname))
11195 		  {
11196 		    error ("declarator-id missing; using reserved word %qD",
11197 			   dname);
11198 		    name = identifier_to_locale (IDENTIFIER_POINTER (dname));
11199 		  }
11200 		else if (!IDENTIFIER_CONV_OP_P (dname))
11201 		  name = identifier_to_locale (IDENTIFIER_POINTER (dname));
11202 		else
11203 		  {
11204 		    gcc_assert (flags == NO_SPECIAL);
11205 		    flags = TYPENAME_FLAG;
11206 		    sfk = sfk_conversion;
11207 		    tree glob = get_global_binding (dname);
11208 		    if (glob && TREE_CODE (glob) == TYPE_DECL)
11209 		      name = identifier_to_locale (IDENTIFIER_POINTER (dname));
11210 		    else
11211 		      name = "<invalid operator>";
11212 		  }
11213 		break;
11214 
11215 	      default:
11216 		gcc_unreachable ();
11217 	      }
11218 	    break;
11219 	  }
11220 
11221 	case cdk_array:
11222 	case cdk_pointer:
11223 	case cdk_reference:
11224 	case cdk_ptrmem:
11225 	  break;
11226 
11227 	case cdk_decomp:
11228 	  name = "structured binding";
11229 	  break;
11230 
11231 	case cdk_error:
11232 	  return error_mark_node;
11233 
11234 	default:
11235 	  gcc_unreachable ();
11236 	}
11237       if (id_declarator->kind == cdk_id)
11238 	break;
11239     }
11240 
11241   /* [dcl.fct.edf]
11242 
11243      The declarator in a function-definition shall have the form
11244      D1 ( parameter-declaration-clause) ...  */
11245   if (funcdef_flag && innermost_code != cdk_function)
11246     {
11247       error_at (id_loc, "function definition does not declare parameters");
11248       return error_mark_node;
11249     }
11250 
11251   if (flags == TYPENAME_FLAG
11252       && innermost_code != cdk_function
11253       && ! (ctype && !declspecs->any_specifiers_p))
11254     {
11255       error_at (id_loc, "declaration of %qD as non-function", dname);
11256       return error_mark_node;
11257     }
11258 
11259   if (dname && identifier_p (dname))
11260     {
11261       if (UDLIT_OPER_P (dname)
11262 	  && innermost_code != cdk_function)
11263 	{
11264 	  error_at (id_loc, "declaration of %qD as non-function", dname);
11265 	  return error_mark_node;
11266 	}
11267 
11268       if (IDENTIFIER_ANY_OP_P (dname))
11269 	{
11270 	  if (typedef_p)
11271 	    {
11272 	      error_at (id_loc, "declaration of %qD as %<typedef%>", dname);
11273 	      return error_mark_node;
11274 	    }
11275 	  else if (decl_context == PARM || decl_context == CATCHPARM)
11276 	    {
11277 	      error_at (id_loc, "declaration of %qD as parameter", dname);
11278 	      return error_mark_node;
11279 	    }
11280 	}
11281     }
11282 
11283   /* Anything declared one level down from the top level
11284      must be one of the parameters of a function
11285      (because the body is at least two levels down).  */
11286 
11287   /* This heuristic cannot be applied to C++ nodes! Fixed, however,
11288      by not allowing C++ class definitions to specify their parameters
11289      with xdecls (must be spec.d in the parmlist).
11290 
11291      Since we now wait to push a class scope until we are sure that
11292      we are in a legitimate method context, we must set oldcname
11293      explicitly (since current_class_name is not yet alive).
11294 
11295      We also want to avoid calling this a PARM if it is in a namespace.  */
11296 
11297   if (decl_context == NORMAL && !toplevel_bindings_p ())
11298     {
11299       cp_binding_level *b = current_binding_level;
11300       current_binding_level = b->level_chain;
11301       if (current_binding_level != 0 && toplevel_bindings_p ())
11302 	decl_context = PARM;
11303       current_binding_level = b;
11304     }
11305 
11306   if (name == NULL)
11307     name = decl_context == PARM ? "parameter" : "type name";
11308 
11309   if (consteval_p && constexpr_p)
11310     {
11311       error_at (declspecs->locations[ds_consteval],
11312 		"both %qs and %qs specified", "constexpr", "consteval");
11313       return error_mark_node;
11314     }
11315 
11316   if (concept_p && typedef_p)
11317     {
11318       error_at (declspecs->locations[ds_concept],
11319 		"%qs cannot appear in a typedef declaration", "concept");
11320       return error_mark_node;
11321     }
11322 
11323   if (constexpr_p && typedef_p)
11324     {
11325       error_at (declspecs->locations[ds_constexpr],
11326 		"%qs cannot appear in a typedef declaration", "constexpr");
11327       return error_mark_node;
11328     }
11329 
11330   if (consteval_p && typedef_p)
11331     {
11332       error_at (declspecs->locations[ds_consteval],
11333 		"%qs cannot appear in a typedef declaration", "consteval");
11334       return error_mark_node;
11335     }
11336 
11337   if (constinit_p && typedef_p)
11338     {
11339       error_at (declspecs->locations[ds_constinit],
11340 		"%qs cannot appear in a typedef declaration", "constinit");
11341       return error_mark_node;
11342     }
11343 
11344   /* [dcl.spec]/2 "At most one of the constexpr, consteval, and constinit
11345      keywords shall appear in a decl-specifier-seq."  */
11346   if (constinit_p && constexpr_p)
11347     {
11348       gcc_rich_location richloc (declspecs->locations[ds_constinit]);
11349       richloc.add_range (declspecs->locations[ds_constexpr]);
11350       error_at (&richloc,
11351 		"can use at most one of the %<constinit%> and %<constexpr%> "
11352 		"specifiers");
11353       return error_mark_node;
11354     }
11355 
11356   /* If there were multiple types specified in the decl-specifier-seq,
11357      issue an error message.  */
11358   if (declspecs->multiple_types_p)
11359     {
11360       error_at (typespec_loc,
11361 		"two or more data types in declaration of %qs", name);
11362       return error_mark_node;
11363     }
11364 
11365   if (declspecs->conflicting_specifiers_p)
11366     {
11367       error_at (min_location (declspecs->locations[ds_typedef],
11368 			      declspecs->locations[ds_storage_class]),
11369 		"conflicting specifiers in declaration of %qs", name);
11370       return error_mark_node;
11371     }
11372 
11373   /* Extract the basic type from the decl-specifier-seq.  */
11374   type = declspecs->type;
11375   if (type == error_mark_node)
11376     {
11377       type = NULL_TREE;
11378       type_was_error_mark_node = true;
11379     }
11380   cp_warn_deprecated_use (type);
11381   if (type && TREE_CODE (type) == TYPE_DECL)
11382     {
11383       cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (type));
11384       typedef_decl = type;
11385       type = TREE_TYPE (typedef_decl);
11386       if (DECL_ARTIFICIAL (typedef_decl))
11387 	cp_warn_deprecated_use (type);
11388     }
11389   /* No type at all: default to `int', and set DEFAULTED_INT
11390      because it was not a user-defined typedef.  */
11391   if (type == NULL_TREE)
11392     {
11393       if (signed_p || unsigned_p || long_p || short_p)
11394 	{
11395 	  /* These imply 'int'.  */
11396 	  type = integer_type_node;
11397 	  defaulted_int = 1;
11398 	}
11399       /* If we just have "complex", it is equivalent to "complex double".  */
11400       else if (!longlong && !explicit_intN
11401 	       && decl_spec_seq_has_spec_p (declspecs, ds_complex))
11402 	{
11403 	  type = double_type_node;
11404 	  pedwarn (declspecs->locations[ds_complex], OPT_Wpedantic,
11405 		   "ISO C++ does not support plain %<complex%> meaning "
11406 		   "%<double complex%>");
11407 	}
11408     }
11409   /* Gather flags.  */
11410   explicit_int = declspecs->explicit_int_p;
11411   explicit_char = declspecs->explicit_char_p;
11412 
11413 #if 0
11414   /* See the code below that used this.  */
11415   if (typedef_decl)
11416     decl_attr = DECL_ATTRIBUTES (typedef_decl);
11417 #endif
11418   typedef_type = type;
11419 
11420   if (sfk == sfk_conversion || sfk == sfk_deduction_guide)
11421     ctor_return_type = TREE_TYPE (dname);
11422   else
11423     ctor_return_type = ctype;
11424 
11425   if (sfk != sfk_none)
11426     {
11427       type = check_special_function_return_type (sfk, type,
11428 						 ctor_return_type,
11429 						 type_quals,
11430 						 declspecs->locations);
11431       type_quals = TYPE_UNQUALIFIED;
11432     }
11433   else if (type == NULL_TREE)
11434     {
11435       int is_main;
11436 
11437       explicit_int = -1;
11438 
11439       /* We handle `main' specially here, because 'main () { }' is so
11440 	 common.  With no options, it is allowed.  With -Wreturn-type,
11441 	 it is a warning.  It is only an error with -pedantic-errors.  */
11442       is_main = (funcdef_flag
11443 		 && dname && identifier_p (dname)
11444 		 && MAIN_NAME_P (dname)
11445 		 && ctype == NULL_TREE
11446 		 && in_namespace == NULL_TREE
11447 		 && current_namespace == global_namespace);
11448 
11449       if (type_was_error_mark_node)
11450 	/* We've already issued an error, don't complain more.  */;
11451       else if (in_system_header_at (id_loc) || flag_ms_extensions)
11452 	/* Allow it, sigh.  */;
11453       else if (! is_main)
11454 	permerror (id_loc, "ISO C++ forbids declaration of %qs with no type",
11455 		   name);
11456       else if (pedantic)
11457 	pedwarn (id_loc, OPT_Wpedantic,
11458 		 "ISO C++ forbids declaration of %qs with no type", name);
11459       else
11460 	warning_at (id_loc, OPT_Wreturn_type,
11461 		    "ISO C++ forbids declaration of %qs with no type", name);
11462 
11463       if (type_was_error_mark_node && template_parm_flag)
11464 	/* FIXME we should be able to propagate the error_mark_node as is
11465 	   for other contexts too.  */
11466 	type = error_mark_node;
11467       else
11468 	type = integer_type_node;
11469     }
11470 
11471   ctype = NULL_TREE;
11472 
11473   if (explicit_intN)
11474     {
11475       if (! int_n_enabled_p[declspecs->int_n_idx])
11476 	{
11477 	  error_at (declspecs->locations[ds_type_spec],
11478 		    "%<__int%d%> is not supported by this target",
11479 		    int_n_data[declspecs->int_n_idx].bitsize);
11480 	  explicit_intN = false;
11481 	}
11482       /* Don't pedwarn if the alternate "__intN__" form has been used instead
11483 	 of "__intN".  */
11484       else if (!int_n_alt && pedantic)
11485 	pedwarn (declspecs->locations[ds_type_spec], OPT_Wpedantic,
11486 		 "ISO C++ does not support %<__int%d%> for %qs",
11487 		 int_n_data[declspecs->int_n_idx].bitsize, name);
11488     }
11489 
11490   /* Now process the modifiers that were specified
11491      and check for invalid combinations.  */
11492 
11493   /* Long double is a special combination.  */
11494   if (long_p && !longlong && TYPE_MAIN_VARIANT (type) == double_type_node)
11495     {
11496       long_p = false;
11497       type = cp_build_qualified_type (long_double_type_node,
11498 				      cp_type_quals (type));
11499     }
11500 
11501   /* Check all other uses of type modifiers.  */
11502 
11503   if (unsigned_p || signed_p || long_p || short_p)
11504     {
11505       location_t loc;
11506       const char *key;
11507       if (unsigned_p)
11508 	{
11509 	  key = "unsigned";
11510 	  loc = declspecs->locations[ds_unsigned];
11511 	}
11512       else if (signed_p)
11513 	{
11514 	  key = "signed";
11515 	  loc = declspecs->locations[ds_signed];
11516 	}
11517       else if (longlong)
11518 	{
11519 	  key = "long long";
11520 	  loc = declspecs->locations[ds_long_long];
11521 	}
11522       else if (long_p)
11523 	{
11524 	  key = "long";
11525 	  loc = declspecs->locations[ds_long];
11526 	}
11527       else /* if (short_p) */
11528 	{
11529 	  key = "short";
11530 	  loc = declspecs->locations[ds_short];
11531 	}
11532 
11533       int ok = 0;
11534 
11535       if (signed_p && unsigned_p)
11536 	{
11537 	  gcc_rich_location richloc (declspecs->locations[ds_signed]);
11538 	  richloc.add_range (declspecs->locations[ds_unsigned]);
11539 	  error_at (&richloc,
11540 		    "%<signed%> and %<unsigned%> specified together");
11541 	}
11542       else if (long_p && short_p)
11543 	{
11544 	  gcc_rich_location richloc (declspecs->locations[ds_long]);
11545 	  richloc.add_range (declspecs->locations[ds_short]);
11546 	  error_at (&richloc, "%<long%> and %<short%> specified together");
11547 	}
11548       else if (TREE_CODE (type) != INTEGER_TYPE
11549 	       || type == char8_type_node
11550 	       || type == char16_type_node
11551 	       || type == char32_type_node
11552 	       || ((long_p || short_p)
11553 		   && (explicit_char || explicit_intN)))
11554 	error_at (loc, "%qs specified with %qT", key, type);
11555       else if (!explicit_int && !defaulted_int
11556 	       && !explicit_char && !explicit_intN)
11557 	{
11558 	  if (typedef_decl)
11559 	    {
11560 	      pedwarn (loc, OPT_Wpedantic, "%qs specified with %qT",
11561 		       key, type);
11562 	      ok = !flag_pedantic_errors;
11563 	    }
11564 	  else if (declspecs->decltype_p)
11565 	    error_at (loc, "%qs specified with %<decltype%>", key);
11566 	  else
11567 	    error_at (loc, "%qs specified with %<typeof%>", key);
11568 	}
11569       else
11570 	ok = 1;
11571 
11572       /* Discard the type modifiers if they are invalid.  */
11573       if (! ok)
11574 	{
11575 	  unsigned_p = false;
11576 	  signed_p = false;
11577 	  long_p = false;
11578 	  short_p = false;
11579 	  longlong = 0;
11580 	}
11581     }
11582 
11583   /* Decide whether an integer type is signed or not.
11584      Optionally treat bitfields as signed by default.  */
11585   if (unsigned_p
11586       /* [class.bit]
11587 
11588 	 It is implementation-defined whether a plain (neither
11589 	 explicitly signed or unsigned) char, short, int, or long
11590 	 bit-field is signed or unsigned.
11591 
11592 	 Naturally, we extend this to long long as well.  Note that
11593 	 this does not include wchar_t.  */
11594       || (bitfield && !flag_signed_bitfields
11595 	  && !signed_p
11596 	  /* A typedef for plain `int' without `signed' can be
11597 	     controlled just like plain `int', but a typedef for
11598 	     `signed int' cannot be so controlled.  */
11599 	  && !(typedef_decl
11600 	       && C_TYPEDEF_EXPLICITLY_SIGNED (typedef_decl))
11601 	  && TREE_CODE (type) == INTEGER_TYPE
11602 	  && !same_type_p (TYPE_MAIN_VARIANT (type), wchar_type_node)))
11603     {
11604       if (explicit_intN)
11605 	type = int_n_trees[declspecs->int_n_idx].unsigned_type;
11606       else if (longlong)
11607 	type = long_long_unsigned_type_node;
11608       else if (long_p)
11609 	type = long_unsigned_type_node;
11610       else if (short_p)
11611 	type = short_unsigned_type_node;
11612       else if (type == char_type_node)
11613 	type = unsigned_char_type_node;
11614       else if (typedef_decl)
11615 	type = unsigned_type_for (type);
11616       else
11617 	type = unsigned_type_node;
11618     }
11619   else if (signed_p && type == char_type_node)
11620     type = signed_char_type_node;
11621   else if (explicit_intN)
11622     type = int_n_trees[declspecs->int_n_idx].signed_type;
11623   else if (longlong)
11624     type = long_long_integer_type_node;
11625   else if (long_p)
11626     type = long_integer_type_node;
11627   else if (short_p)
11628     type = short_integer_type_node;
11629 
11630   if (decl_spec_seq_has_spec_p (declspecs, ds_complex))
11631     {
11632       if (TREE_CODE (type) != INTEGER_TYPE && TREE_CODE (type) != REAL_TYPE)
11633 	error_at (declspecs->locations[ds_complex],
11634 		  "complex invalid for %qs", name);
11635       /* If a modifier is specified, the resulting complex is the complex
11636 	 form of TYPE.  E.g, "complex short" is "complex short int".  */
11637       else if (type == integer_type_node)
11638 	type = complex_integer_type_node;
11639       else if (type == float_type_node)
11640 	type = complex_float_type_node;
11641       else if (type == double_type_node)
11642 	type = complex_double_type_node;
11643       else if (type == long_double_type_node)
11644 	type = complex_long_double_type_node;
11645       else
11646 	type = build_complex_type (type);
11647     }
11648 
11649   /* If we're using the injected-class-name to form a compound type or a
11650      declaration, replace it with the underlying class so we don't get
11651      redundant typedefs in the debug output.  But if we are returning the
11652      type unchanged, leave it alone so that it's available to
11653      maybe_get_template_decl_from_type_decl.  */
11654   if (CLASS_TYPE_P (type)
11655       && DECL_SELF_REFERENCE_P (TYPE_NAME (type))
11656       && type == TREE_TYPE (TYPE_NAME (type))
11657       && (declarator || type_quals))
11658     type = DECL_ORIGINAL_TYPE (TYPE_NAME (type));
11659 
11660   type_quals |= cp_type_quals (type);
11661   type = cp_build_qualified_type_real
11662     (type, type_quals, ((((typedef_decl && !DECL_ARTIFICIAL (typedef_decl))
11663 			  || declspecs->decltype_p)
11664 			 ? tf_ignore_bad_quals : 0) | tf_warning_or_error));
11665   /* We might have ignored or rejected some of the qualifiers.  */
11666   type_quals = cp_type_quals (type);
11667 
11668   if (cxx_dialect >= cxx17 && type && is_auto (type)
11669       && innermost_code != cdk_function
11670       && id_declarator && declarator != id_declarator)
11671     if (tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (type))
11672     {
11673       error_at (typespec_loc, "template placeholder type %qT must be followed "
11674 		"by a simple declarator-id", type);
11675       inform (DECL_SOURCE_LOCATION (tmpl), "%qD declared here", tmpl);
11676       type = error_mark_node;
11677     }
11678 
11679   staticp = 0;
11680   inlinep = decl_spec_seq_has_spec_p (declspecs, ds_inline);
11681   virtualp =  decl_spec_seq_has_spec_p (declspecs, ds_virtual);
11682   explicitp = decl_spec_seq_has_spec_p (declspecs, ds_explicit);
11683 
11684   storage_class = declspecs->storage_class;
11685   if (storage_class == sc_static)
11686     staticp = 1 + (decl_context == FIELD);
11687 
11688   if (virtualp)
11689     {
11690       if (staticp == 2)
11691 	{
11692 	  gcc_rich_location richloc (declspecs->locations[ds_virtual]);
11693 	  richloc.add_range (declspecs->locations[ds_storage_class]);
11694 	  error_at (&richloc, "member %qD cannot be declared both %<virtual%> "
11695 		    "and %<static%>", dname);
11696 	  storage_class = sc_none;
11697 	  staticp = 0;
11698 	}
11699       if (constexpr_p && cxx_dialect < cxx2a)
11700 	{
11701 	  gcc_rich_location richloc (declspecs->locations[ds_virtual]);
11702 	  richloc.add_range (declspecs->locations[ds_constexpr]);
11703 	  pedwarn (&richloc, OPT_Wpedantic, "member %qD can be declared both "
11704 		   "%<virtual%> and %<constexpr%> only in %<-std=c++2a%> or "
11705 		   "%<-std=gnu++2a%>", dname);
11706 	}
11707     }
11708   friendp = decl_spec_seq_has_spec_p (declspecs, ds_friend);
11709 
11710   /* Issue errors about use of storage classes for parameters.  */
11711   if (decl_context == PARM)
11712     {
11713       if (typedef_p)
11714 	{
11715 	  error_at (declspecs->locations[ds_typedef],
11716 		    "typedef declaration invalid in parameter declaration");
11717 	  return error_mark_node;
11718 	}
11719       else if (template_parm_flag && storage_class != sc_none)
11720 	{
11721 	  error_at (min_location (declspecs->locations[ds_thread],
11722 				  declspecs->locations[ds_storage_class]),
11723 		    "storage class specified for template parameter %qs",
11724 		    name);
11725 	  return error_mark_node;
11726 	}
11727       else if (storage_class == sc_static
11728 	       || storage_class == sc_extern
11729 	       || thread_p)
11730 	{
11731 	  error_at (min_location (declspecs->locations[ds_thread],
11732 				  declspecs->locations[ds_storage_class]),
11733 		    "storage class specified for parameter %qs", name);
11734 	  return error_mark_node;
11735 	}
11736 
11737       /* Function parameters cannot be concept. */
11738       if (concept_p)
11739 	{
11740 	  error_at (declspecs->locations[ds_concept],
11741 		    "a parameter cannot be declared %qs", "concept");
11742 	  concept_p = 0;
11743 	  constexpr_p = 0;
11744 	}
11745       /* Function parameters cannot be constexpr.  If we saw one, moan
11746          and pretend it wasn't there.  */
11747       else if (constexpr_p)
11748         {
11749           error_at (declspecs->locations[ds_constexpr],
11750 		    "a parameter cannot be declared %qs", "constexpr");
11751           constexpr_p = 0;
11752         }
11753       if (constinit_p)
11754 	{
11755 	  error_at (declspecs->locations[ds_constinit],
11756 		    "a parameter cannot be declared %qs", "constinit");
11757 	  constinit_p = 0;
11758 	}
11759       if (consteval_p)
11760 	{
11761 	  error_at (declspecs->locations[ds_consteval],
11762 		    "a parameter cannot be declared %qs", "consteval");
11763 	  consteval_p = 0;
11764 	}
11765     }
11766 
11767   /* Give error if `virtual' is used outside of class declaration.  */
11768   if (virtualp
11769       && (current_class_name == NULL_TREE || decl_context != FIELD))
11770     {
11771       error_at (declspecs->locations[ds_virtual],
11772 		"%<virtual%> outside class declaration");
11773       virtualp = 0;
11774     }
11775 
11776   if (innermost_code == cdk_decomp)
11777     {
11778       location_t loc = (declarator->kind == cdk_reference
11779 			? declarator->declarator->id_loc : declarator->id_loc);
11780       if (inlinep)
11781 	error_at (declspecs->locations[ds_inline],
11782 		  "structured binding declaration cannot be %qs", "inline");
11783       if (typedef_p)
11784 	error_at (declspecs->locations[ds_typedef],
11785 		  "structured binding declaration cannot be %qs", "typedef");
11786       if (constexpr_p && !concept_p)
11787 	error_at (declspecs->locations[ds_constexpr], "structured "
11788 		  "binding declaration cannot be %qs", "constexpr");
11789       if (consteval_p)
11790 	error_at (declspecs->locations[ds_consteval], "structured "
11791 		  "binding declaration cannot be %qs", "consteval");
11792       if (thread_p && cxx_dialect < cxx2a)
11793 	pedwarn (declspecs->locations[ds_thread], 0,
11794 		 "structured binding declaration can be %qs only in "
11795 		 "%<-std=c++2a%> or %<-std=gnu++2a%>",
11796 		 declspecs->gnu_thread_keyword_p
11797 		 ? "__thread" : "thread_local");
11798       if (concept_p)
11799 	error_at (declspecs->locations[ds_concept],
11800 		  "structured binding declaration cannot be %qs", "concept");
11801       /* [dcl.struct.bind] "A cv that includes volatile is deprecated."  */
11802       if (type_quals & TYPE_QUAL_VOLATILE)
11803 	warning_at (declspecs->locations[ds_volatile], OPT_Wvolatile,
11804 		    "%<volatile%>-qualified structured binding is deprecated");
11805       switch (storage_class)
11806 	{
11807 	case sc_none:
11808 	  break;
11809 	case sc_register:
11810 	  error_at (loc, "structured binding declaration cannot be %qs",
11811 		    "register");
11812 	  break;
11813 	case sc_static:
11814 	  if (cxx_dialect < cxx2a)
11815 	    pedwarn (loc, 0,
11816 		     "structured binding declaration can be %qs only in "
11817 		     "%<-std=c++2a%> or %<-std=gnu++2a%>", "static");
11818 	  break;
11819 	case sc_extern:
11820 	  error_at (loc, "structured binding declaration cannot be %qs",
11821 		    "extern");
11822 	  break;
11823 	case sc_mutable:
11824 	  error_at (loc, "structured binding declaration cannot be %qs",
11825 		    "mutable");
11826 	  break;
11827 	case sc_auto:
11828 	  error_at (loc, "structured binding declaration cannot be "
11829 		    "C++98 %<auto%>");
11830 	  break;
11831 	default:
11832 	  gcc_unreachable ();
11833 	}
11834       if (TREE_CODE (type) != TEMPLATE_TYPE_PARM
11835 	  || TYPE_IDENTIFIER (type) != auto_identifier)
11836 	{
11837 	  if (type != error_mark_node)
11838 	    {
11839 	      error_at (loc, "structured binding declaration cannot have "
11840 			"type %qT", type);
11841 	      inform (loc,
11842 		      "type must be cv-qualified %<auto%> or reference to "
11843 		      "cv-qualified %<auto%>");
11844 	    }
11845 	  type = build_qualified_type (make_auto (), type_quals);
11846 	  declspecs->type = type;
11847 	}
11848       inlinep = 0;
11849       typedef_p = 0;
11850       constexpr_p = 0;
11851       consteval_p = 0;
11852       concept_p = 0;
11853       if (storage_class != sc_static)
11854 	{
11855 	  storage_class = sc_none;
11856 	  declspecs->storage_class = sc_none;
11857 	}
11858     }
11859 
11860   /* Static anonymous unions are dealt with here.  */
11861   if (staticp && decl_context == TYPENAME
11862       && declspecs->type
11863       && ANON_AGGR_TYPE_P (declspecs->type))
11864     decl_context = FIELD;
11865 
11866   /* Warn about storage classes that are invalid for certain
11867      kinds of declarations (parameters, typenames, etc.).  */
11868   if (thread_p
11869       && ((storage_class
11870 	   && storage_class != sc_extern
11871 	   && storage_class != sc_static)
11872 	  || typedef_p))
11873     {
11874       location_t loc
11875 	= min_location (declspecs->locations[ds_thread],
11876 			declspecs->locations[ds_storage_class]);
11877       error_at (loc, "multiple storage classes in declaration of %qs", name);
11878       thread_p = false;
11879     }
11880   if (decl_context != NORMAL
11881       && ((storage_class != sc_none
11882 	   && storage_class != sc_mutable)
11883 	  || thread_p))
11884     {
11885       if ((decl_context == PARM || decl_context == CATCHPARM)
11886 	  && (storage_class == sc_register
11887 	      || storage_class == sc_auto))
11888 	;
11889       else if (typedef_p)
11890 	;
11891       else if (decl_context == FIELD
11892 	       /* C++ allows static class elements.  */
11893 	       && storage_class == sc_static)
11894 	/* C++ also allows inlines and signed and unsigned elements,
11895 	   but in those cases we don't come in here.  */
11896 	;
11897       else
11898 	{
11899 	  location_t loc
11900 	    = min_location (declspecs->locations[ds_thread],
11901 			    declspecs->locations[ds_storage_class]);
11902 	  if (decl_context == FIELD)
11903 	    error_at (loc, "storage class specified for %qs", name);
11904 	  else if (decl_context == PARM || decl_context == CATCHPARM)
11905 	    error_at (loc, "storage class specified for parameter %qs", name);
11906 	  else
11907 	    error_at (loc, "storage class specified for typename");
11908 	  if (storage_class == sc_register
11909 	      || storage_class == sc_auto
11910 	      || storage_class == sc_extern
11911 	      || thread_p)
11912 	    storage_class = sc_none;
11913 	}
11914     }
11915   else if (storage_class == sc_extern && funcdef_flag
11916 	   && ! toplevel_bindings_p ())
11917     error ("nested function %qs declared %<extern%>", name);
11918   else if (toplevel_bindings_p ())
11919     {
11920       if (storage_class == sc_auto)
11921 	error_at (declspecs->locations[ds_storage_class],
11922 		  "top-level declaration of %qs specifies %<auto%>", name);
11923     }
11924   else if (thread_p
11925 	   && storage_class != sc_extern
11926 	   && storage_class != sc_static)
11927     {
11928       if (declspecs->gnu_thread_keyword_p)
11929 	pedwarn (declspecs->locations[ds_thread],
11930 		 0, "function-scope %qs implicitly auto and "
11931 		 "declared %<__thread%>", name);
11932 
11933       /* When thread_local is applied to a variable of block scope the
11934 	 storage-class-specifier static is implied if it does not appear
11935 	 explicitly.  */
11936       storage_class = declspecs->storage_class = sc_static;
11937       staticp = 1;
11938     }
11939 
11940   if (storage_class && friendp)
11941     {
11942       error_at (min_location (declspecs->locations[ds_thread],
11943 			      declspecs->locations[ds_storage_class]),
11944 		"storage class specifiers invalid in friend function "
11945 		"declarations");
11946       storage_class = sc_none;
11947       staticp = 0;
11948     }
11949 
11950   if (!id_declarator)
11951     unqualified_id = NULL_TREE;
11952   else
11953     {
11954       unqualified_id = id_declarator->u.id.unqualified_name;
11955       switch (TREE_CODE (unqualified_id))
11956 	{
11957 	case BIT_NOT_EXPR:
11958 	  unqualified_id = TREE_OPERAND (unqualified_id, 0);
11959 	  if (TYPE_P (unqualified_id))
11960 	    unqualified_id = constructor_name (unqualified_id);
11961 	  break;
11962 
11963 	case IDENTIFIER_NODE:
11964 	case TEMPLATE_ID_EXPR:
11965 	  break;
11966 
11967 	default:
11968 	  gcc_unreachable ();
11969 	}
11970     }
11971 
11972   if (declspecs->std_attributes)
11973     {
11974       location_t attr_loc = declspecs->locations[ds_std_attribute];
11975       if (warning_at (attr_loc, OPT_Wattributes, "attribute ignored"))
11976 	inform (attr_loc, "an attribute that appertains to a type-specifier "
11977 		"is ignored");
11978     }
11979 
11980   /* Determine the type of the entity declared by recurring on the
11981      declarator.  */
11982   for (; declarator; declarator = declarator->declarator)
11983     {
11984       const cp_declarator *inner_declarator;
11985       tree attrs;
11986 
11987       if (type == error_mark_node)
11988 	return error_mark_node;
11989 
11990       attrs = declarator->attributes;
11991       if (attrs)
11992 	{
11993 	  int attr_flags;
11994 
11995 	  attr_flags = 0;
11996 	  if (declarator == NULL || declarator->kind == cdk_id)
11997 	    attr_flags |= (int) ATTR_FLAG_DECL_NEXT;
11998 	  if (declarator->kind == cdk_function)
11999 	    attr_flags |= (int) ATTR_FLAG_FUNCTION_NEXT;
12000 	  if (declarator->kind == cdk_array)
12001 	    attr_flags |= (int) ATTR_FLAG_ARRAY_NEXT;
12002 	  tree late_attrs = NULL_TREE;
12003 	  if (decl_context != PARM && decl_context != TYPENAME)
12004 	    /* Assume that any attributes that get applied late to
12005 	       templates will DTRT when applied to the declaration
12006 	       as a whole.  */
12007 	    late_attrs = splice_template_attributes (&attrs, type);
12008 	  returned_attrs = decl_attributes (&type,
12009 					    chainon (returned_attrs, attrs),
12010 					    attr_flags);
12011 	  returned_attrs = chainon (late_attrs, returned_attrs);
12012 	}
12013 
12014       inner_declarator = declarator->declarator;
12015 
12016       /* We don't want to warn in parameter context because we don't
12017 	 yet know if the parse will succeed, and this might turn out
12018 	 to be a constructor call.  */
12019       if (decl_context != PARM
12020 	  && decl_context != TYPENAME
12021 	  && !typedef_p
12022 	  && declarator->parenthesized != UNKNOWN_LOCATION
12023 	  /* If the type is class-like and the inner name used a
12024 	     global namespace qualifier, we need the parens.
12025 	     Unfortunately all we can tell is whether a qualified name
12026 	     was used or not.  */
12027 	  && !(inner_declarator
12028 	       && inner_declarator->kind == cdk_id
12029 	       && inner_declarator->u.id.qualifying_scope
12030 	       && (MAYBE_CLASS_TYPE_P (type)
12031 		   || TREE_CODE (type) == ENUMERAL_TYPE)))
12032 	warning_at (declarator->parenthesized, OPT_Wparentheses,
12033 		    "unnecessary parentheses in declaration of %qs", name);
12034       if (declarator->kind == cdk_id || declarator->kind == cdk_decomp)
12035 	break;
12036 
12037       switch (declarator->kind)
12038 	{
12039 	case cdk_array:
12040 	  type = create_array_type_for_decl (dname, type,
12041 					     declarator->u.array.bounds,
12042 					     declarator->id_loc);
12043 	  if (!valid_array_size_p (dname
12044 				   ? declarator->id_loc : input_location,
12045 				   type, dname))
12046 	    type = error_mark_node;
12047 
12048 	  if (declarator->std_attributes)
12049 	    /* [dcl.array]/1:
12050 
12051 	       The optional attribute-specifier-seq appertains to the
12052 	       array.  */
12053 	    returned_attrs = chainon (returned_attrs,
12054 				      declarator->std_attributes);
12055 	  break;
12056 
12057 	case cdk_function:
12058 	  {
12059 	    tree arg_types;
12060 	    int funcdecl_p;
12061 
12062 	    /* Declaring a function type.  */
12063 
12064 	    {
12065 	      iloc_sentinel ils (declspecs->locations[ds_type_spec]);
12066 	      abstract_virtuals_error (ACU_RETURN, type);
12067 	    }
12068 
12069 	    /* Pick up type qualifiers which should be applied to `this'.  */
12070 	    memfn_quals = declarator->u.function.qualifiers;
12071 	    /* Pick up virt-specifiers.  */
12072             virt_specifiers = declarator->u.function.virt_specifiers;
12073 	    /* And ref-qualifier, too */
12074 	    rqual = declarator->u.function.ref_qualifier;
12075 	    /* And tx-qualifier.  */
12076 	    tree tx_qual = declarator->u.function.tx_qualifier;
12077 	    /* Pick up the exception specifications.  */
12078 	    raises = declarator->u.function.exception_specification;
12079 	    /* If the exception-specification is ill-formed, let's pretend
12080 	       there wasn't one.  */
12081 	    if (raises == error_mark_node)
12082 	      raises = NULL_TREE;
12083 
12084 	    if (reqs)
12085 	      error_at (location_of (reqs), "requires-clause on return type");
12086 	    reqs = declarator->u.function.requires_clause;
12087 
12088 	    /* Say it's a definition only for the CALL_EXPR
12089 	       closest to the identifier.  */
12090 	    funcdecl_p = inner_declarator && inner_declarator->kind == cdk_id;
12091 
12092 	    /* Handle a late-specified return type.  */
12093 	    tree late_return_type = declarator->u.function.late_return_type;
12094 	    if (funcdecl_p
12095 		/* This is the case e.g. for
12096 		   using T = auto () -> int.  */
12097 		|| inner_declarator == NULL)
12098 	      {
12099 		if (tree auto_node = type_uses_auto (type))
12100 		  {
12101 		    if (!late_return_type)
12102 		      {
12103 			if (current_class_type
12104 			    && LAMBDA_TYPE_P (current_class_type))
12105 			  /* OK for C++11 lambdas.  */;
12106 			else if (cxx_dialect < cxx14)
12107 			  {
12108 			    error_at (typespec_loc, "%qs function uses "
12109 				      "%<auto%> type specifier without "
12110 				      "trailing return type", name);
12111 			    inform (typespec_loc,
12112 				    "deduced return type only available "
12113 				    "with %<-std=c++14%> or %<-std=gnu++14%>");
12114 			  }
12115 			else if (virtualp)
12116 			  {
12117 			    error_at (typespec_loc, "virtual function "
12118 				      "cannot have deduced return type");
12119 			    virtualp = false;
12120 			  }
12121 		      }
12122 		    else if (!is_auto (type) && sfk != sfk_conversion)
12123 		      {
12124 			error_at (typespec_loc, "%qs function with trailing "
12125 				  "return type has %qT as its type rather "
12126 				  "than plain %<auto%>", name, type);
12127 			return error_mark_node;
12128 		      }
12129 		    else if (is_auto (type) && AUTO_IS_DECLTYPE (type))
12130 		      {
12131 			if (funcdecl_p)
12132 			  error_at (typespec_loc,
12133 				    "%qs function with trailing return type "
12134 				    "has %<decltype(auto)%> as its type "
12135 				    "rather than plain %<auto%>", name);
12136 			else
12137 			  error_at (typespec_loc,
12138 				    "invalid use of %<decltype(auto)%>");
12139 			return error_mark_node;
12140 		      }
12141 		    tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node);
12142 		    if (!tmpl)
12143 		      if (tree late_auto = type_uses_auto (late_return_type))
12144 			tmpl = CLASS_PLACEHOLDER_TEMPLATE (late_auto);
12145 		    if (tmpl && funcdecl_p)
12146 		      {
12147 			if (!dguide_name_p (unqualified_id))
12148 			  {
12149 			    error_at (declarator->id_loc, "deduced class "
12150 				      "type %qD in function return type",
12151 				      DECL_NAME (tmpl));
12152 			    inform (DECL_SOURCE_LOCATION (tmpl),
12153 				    "%qD declared here", tmpl);
12154 			    return error_mark_node;
12155 			  }
12156 			else if (!late_return_type)
12157 			  {
12158 			    error_at (declarator->id_loc, "deduction guide "
12159 				      "for %qT must have trailing return "
12160 				      "type", TREE_TYPE (tmpl));
12161 			    inform (DECL_SOURCE_LOCATION (tmpl),
12162 				    "%qD declared here", tmpl);
12163 			    return error_mark_node;
12164 			  }
12165 			else if (CLASS_TYPE_P (late_return_type)
12166 				 && CLASSTYPE_TEMPLATE_INFO (late_return_type)
12167 				 && (CLASSTYPE_TI_TEMPLATE (late_return_type)
12168 				     == tmpl))
12169 			  /* OK */;
12170 			else
12171 			  error ("trailing return type %qT of deduction guide "
12172 				 "is not a specialization of %qT",
12173 				 late_return_type, TREE_TYPE (tmpl));
12174 		      }
12175 		  }
12176 		else if (late_return_type
12177 			 && sfk != sfk_conversion)
12178 		  {
12179 		    if (late_return_type == error_mark_node)
12180 		      return error_mark_node;
12181 		    if (cxx_dialect < cxx11)
12182 		      /* Not using maybe_warn_cpp0x because this should
12183 			 always be an error.  */
12184 		      error_at (typespec_loc,
12185 				"trailing return type only available "
12186 				"with %<-std=c++11%> or %<-std=gnu++11%>");
12187 		    else
12188 		      error_at (typespec_loc, "%qs function with trailing "
12189 				"return type not declared with %<auto%> "
12190 				"type specifier", name);
12191 		    return error_mark_node;
12192 		  }
12193 	      }
12194 	    type = splice_late_return_type (type, late_return_type);
12195 	    if (type == error_mark_node)
12196 	      return error_mark_node;
12197 
12198 	    if (late_return_type)
12199 	      {
12200 		late_return_type_p = true;
12201 		type_quals = cp_type_quals (type);
12202 	      }
12203 
12204 	    if (type_quals != TYPE_UNQUALIFIED)
12205 	      {
12206 		if (SCALAR_TYPE_P (type) || VOID_TYPE_P (type))
12207 		  warning_at (typespec_loc, OPT_Wignored_qualifiers, "type "
12208 			      "qualifiers ignored on function return type");
12209 		/* [dcl.fct] "A volatile-qualified return type is
12210 		   deprecated."  */
12211 		if (type_quals & TYPE_QUAL_VOLATILE)
12212 		  warning_at (typespec_loc, OPT_Wvolatile,
12213 			      "%<volatile%>-qualified return type is "
12214 			      "deprecated");
12215 
12216 		/* We now know that the TYPE_QUALS don't apply to the
12217 		   decl, but to its return type.  */
12218 		type_quals = TYPE_UNQUALIFIED;
12219 	      }
12220 
12221 	    /* Error about some types functions can't return.  */
12222 
12223 	    if (TREE_CODE (type) == FUNCTION_TYPE)
12224 	      {
12225 		error_at (typespec_loc, "%qs declared as function returning "
12226 			  "a function", name);
12227 		return error_mark_node;
12228 	      }
12229 	    if (TREE_CODE (type) == ARRAY_TYPE)
12230 	      {
12231 		error_at (typespec_loc, "%qs declared as function returning "
12232 			  "an array", name);
12233 		return error_mark_node;
12234 	      }
12235 	    if (constinit_p)
12236 	      {
12237 		error_at (declspecs->locations[ds_constinit],
12238 			  "%<constinit%> on function return type is not "
12239 			  "allowed");
12240 		return error_mark_node;
12241 	      }
12242 	    /* Only plain decltype(auto) is allowed.  */
12243 	    if (tree a = type_uses_auto (type))
12244 	      {
12245 		if (AUTO_IS_DECLTYPE (a) && a != type)
12246 		  {
12247 		    error_at (typespec_loc, "%qT as type rather than "
12248 			      "plain %<decltype(auto)%>", type);
12249 		    return error_mark_node;
12250 		  }
12251 	      }
12252 
12253 	    if (ctype == NULL_TREE
12254 		&& decl_context == FIELD
12255 		&& funcdecl_p
12256 		&& friendp == 0)
12257 	      ctype = current_class_type;
12258 
12259 	    if (ctype && (sfk == sfk_constructor
12260 			  || sfk == sfk_destructor))
12261 	      {
12262 		/* We are within a class's scope. If our declarator name
12263 		   is the same as the class name, and we are defining
12264 		   a function, then it is a constructor/destructor, and
12265 		   therefore returns a void type.  */
12266 
12267 		/* ISO C++ 12.4/2.  A destructor may not be declared
12268 		   const or volatile.  A destructor may not be static.
12269 		   A destructor may not be declared with ref-qualifier.
12270 
12271 		   ISO C++ 12.1.  A constructor may not be declared
12272 		   const or volatile.  A constructor may not be
12273 		   virtual.  A constructor may not be static.
12274 		   A constructor may not be declared with ref-qualifier. */
12275 		if (staticp == 2)
12276 		  error_at (declspecs->locations[ds_storage_class],
12277 			    (flags == DTOR_FLAG)
12278 			    ? G_("destructor cannot be static member "
12279 				 "function")
12280 			    : G_("constructor cannot be static member "
12281 				 "function"));
12282 		if (memfn_quals)
12283 		  {
12284 		    error ((flags == DTOR_FLAG)
12285 			   ? G_("destructors may not be cv-qualified")
12286 			   : G_("constructors may not be cv-qualified"));
12287 		    memfn_quals = TYPE_UNQUALIFIED;
12288 		  }
12289 
12290 		if (rqual)
12291 		  {
12292 		    maybe_warn_cpp0x (CPP0X_REF_QUALIFIER);
12293 		    error ((flags == DTOR_FLAG)
12294 			   ? G_("destructors may not be ref-qualified")
12295 			   : G_("constructors may not be ref-qualified"));
12296 		    rqual = REF_QUAL_NONE;
12297 		  }
12298 
12299 		if (decl_context == FIELD
12300 		    && !member_function_or_else (ctype,
12301 						 current_class_type,
12302 						 flags))
12303 		  return error_mark_node;
12304 
12305 		if (flags != DTOR_FLAG)
12306 		  {
12307 		    /* It's a constructor.  */
12308 		    if (explicitp == 1)
12309 		      explicitp = 2;
12310 		    if (virtualp)
12311 		      {
12312 			permerror (declspecs->locations[ds_virtual],
12313 				   "constructors cannot be declared %<virtual%>");
12314 			virtualp = 0;
12315 		      }
12316 		    if (decl_context == FIELD
12317 			&& sfk != sfk_constructor)
12318 		      return error_mark_node;
12319 		  }
12320 		if (decl_context == FIELD)
12321 		  staticp = 0;
12322 	      }
12323 	    else if (friendp)
12324 	      {
12325 		if (virtualp)
12326 		  {
12327 		    /* Cannot be both friend and virtual.  */
12328 		    gcc_rich_location richloc (declspecs->locations[ds_virtual]);
12329 		    richloc.add_range (declspecs->locations[ds_friend]);
12330 		    error_at (&richloc, "virtual functions cannot be friends");
12331 		    friendp = 0;
12332 		  }
12333 		if (decl_context == NORMAL)
12334 		  error_at (declarator->id_loc,
12335 			    "friend declaration not in class definition");
12336 		if (current_function_decl && funcdef_flag)
12337 		  {
12338 		    error_at (declarator->id_loc,
12339 			      "cannot define friend function %qs in a local "
12340 			      "class definition", name);
12341 		    friendp = 0;
12342 		  }
12343 		/* [class.friend]/6: A function can be defined in a friend
12344 		   declaration if the function name is unqualified.  */
12345 		if (funcdef_flag && in_namespace)
12346 		  {
12347 		    if (in_namespace == global_namespace)
12348 		      error_at (declarator->id_loc,
12349 				"friend function definition %qs cannot have "
12350 				"a name qualified with %<::%>", name);
12351 		    else
12352 		      error_at (declarator->id_loc,
12353 				"friend function definition %qs cannot have "
12354 				"a name qualified with %<%D::%>", name,
12355 				in_namespace);
12356 		  }
12357 	      }
12358 	    else if (ctype && sfk == sfk_conversion)
12359 	      {
12360 		if (explicitp == 1)
12361 		  {
12362 		    maybe_warn_cpp0x (CPP0X_EXPLICIT_CONVERSION);
12363 		    explicitp = 2;
12364 		  }
12365 		if (late_return_type_p)
12366 		  error ("a conversion function cannot have a trailing return type");
12367 	      }
12368 	    else if (sfk == sfk_deduction_guide)
12369 	      {
12370 		if (explicitp == 1)
12371 		  explicitp = 2;
12372 	      }
12373 
12374 	    tree pushed_scope = NULL_TREE;
12375 	    if (funcdecl_p
12376 		&& decl_context != FIELD
12377 		&& inner_declarator->u.id.qualifying_scope
12378 		&& CLASS_TYPE_P (inner_declarator->u.id.qualifying_scope))
12379 	      pushed_scope
12380 		= push_scope (inner_declarator->u.id.qualifying_scope);
12381 
12382 	    arg_types = grokparms (declarator->u.function.parameters, &parms);
12383 
12384 	    if (pushed_scope)
12385 	      pop_scope (pushed_scope);
12386 
12387 	    if (inner_declarator
12388 		&& inner_declarator->kind == cdk_id
12389 		&& inner_declarator->u.id.sfk == sfk_destructor
12390 		&& arg_types != void_list_node)
12391 	      {
12392 		error_at (declarator->id_loc,
12393 			  "destructors may not have parameters");
12394 		arg_types = void_list_node;
12395 		parms = NULL_TREE;
12396 	      }
12397 
12398 	    type = build_function_type (type, arg_types);
12399 
12400 	    tree attrs = declarator->std_attributes;
12401 	    if (tx_qual)
12402 	      {
12403 		tree att = build_tree_list (tx_qual, NULL_TREE);
12404 		/* transaction_safe applies to the type, but
12405 		   transaction_safe_dynamic applies to the function.  */
12406 		if (is_attribute_p ("transaction_safe", tx_qual))
12407 		  attrs = chainon (attrs, att);
12408 		else
12409 		  returned_attrs = chainon (returned_attrs, att);
12410 	      }
12411 	    if (attrs)
12412 	      /* [dcl.fct]/2:
12413 
12414 		 The optional attribute-specifier-seq appertains to
12415 		 the function type.  */
12416 	      cplus_decl_attributes (&type, attrs, 0);
12417 
12418 	    if (raises)
12419 	      type = build_exception_variant (type, raises);
12420 	  }
12421 	  break;
12422 
12423 	case cdk_pointer:
12424 	case cdk_reference:
12425 	case cdk_ptrmem:
12426 	  /* Filter out pointers-to-references and references-to-references.
12427 	     We can get these if a TYPE_DECL is used.  */
12428 
12429 	  if (TYPE_REF_P (type))
12430 	    {
12431 	      if (declarator->kind != cdk_reference)
12432 		{
12433 		  error ("cannot declare pointer to %q#T", type);
12434 		  type = TREE_TYPE (type);
12435 		}
12436 
12437 	      /* In C++0x, we allow reference to reference declarations
12438 		 that occur indirectly through typedefs [7.1.3/8 dcl.typedef]
12439 		 and template type arguments [14.3.1/4 temp.arg.type]. The
12440 		 check for direct reference to reference declarations, which
12441 		 are still forbidden, occurs below. Reasoning behind the change
12442 		 can be found in DR106, DR540, and the rvalue reference
12443 		 proposals. */
12444 	      else if (cxx_dialect == cxx98)
12445 		{
12446 		  error ("cannot declare reference to %q#T", type);
12447 		  type = TREE_TYPE (type);
12448 		}
12449 	    }
12450 	  else if (VOID_TYPE_P (type))
12451 	    {
12452 	      if (declarator->kind == cdk_reference)
12453 		error ("cannot declare reference to %q#T", type);
12454 	      else if (declarator->kind == cdk_ptrmem)
12455 		error ("cannot declare pointer to %q#T member", type);
12456 	    }
12457 
12458 	  /* We now know that the TYPE_QUALS don't apply to the decl,
12459 	     but to the target of the pointer.  */
12460 	  type_quals = TYPE_UNQUALIFIED;
12461 
12462 	  /* This code used to handle METHOD_TYPE, but I don't think it's
12463 	     possible to get it here anymore.  */
12464 	  gcc_assert (TREE_CODE (type) != METHOD_TYPE);
12465 	  if (declarator->kind == cdk_ptrmem
12466 	      && TREE_CODE (type) == FUNCTION_TYPE)
12467 	    {
12468 	      memfn_quals |= type_memfn_quals (type);
12469 	      type = build_memfn_type (type,
12470 				       declarator->u.pointer.class_type,
12471 				       memfn_quals,
12472 				       rqual);
12473 	      if (type == error_mark_node)
12474 		return error_mark_node;
12475 
12476 	      rqual = REF_QUAL_NONE;
12477 	      memfn_quals = TYPE_UNQUALIFIED;
12478 	    }
12479 
12480 	  if (TREE_CODE (type) == FUNCTION_TYPE
12481 	      && (type_memfn_quals (type) != TYPE_UNQUALIFIED
12482 		  || type_memfn_rqual (type) != REF_QUAL_NONE))
12483             error (declarator->kind == cdk_reference
12484                    ? G_("cannot declare reference to qualified function type %qT")
12485                    : G_("cannot declare pointer to qualified function type %qT"),
12486 		   type);
12487 
12488 	  /* When the pointed-to type involves components of variable size,
12489 	     care must be taken to ensure that the size evaluation code is
12490 	     emitted early enough to dominate all the possible later uses
12491 	     and late enough for the variables on which it depends to have
12492 	     been assigned.
12493 
12494 	     This is expected to happen automatically when the pointed-to
12495 	     type has a name/declaration of it's own, but special attention
12496 	     is required if the type is anonymous.
12497 
12498 	     We handle the NORMAL and FIELD contexts here by inserting a
12499 	     dummy statement that just evaluates the size at a safe point
12500 	     and ensures it is not deferred until e.g. within a deeper
12501 	     conditional context (c++/43555).
12502 
12503 	     We expect nothing to be needed here for PARM or TYPENAME.
12504 	     Evaluating the size at this point for TYPENAME would
12505 	     actually be incorrect, as we might be in the middle of an
12506 	     expression with side effects on the pointed-to type size
12507 	     "arguments" prior to the pointer declaration point and the
12508 	     size evaluation could end up prior to the side effects.  */
12509 
12510 	  if (!TYPE_NAME (type)
12511 	      && (decl_context == NORMAL || decl_context == FIELD)
12512 	      && at_function_scope_p ()
12513 	      && variably_modified_type_p (type, NULL_TREE))
12514 	    {
12515 	      TYPE_NAME (type) = build_decl (UNKNOWN_LOCATION, TYPE_DECL,
12516 					     NULL_TREE, type);
12517 	      add_decl_expr (TYPE_NAME (type));
12518 	    }
12519 
12520 	  if (declarator->kind == cdk_reference)
12521 	    {
12522 	      /* In C++0x, the type we are creating a reference to might be
12523 		 a typedef which is itself a reference type. In that case,
12524 		 we follow the reference collapsing rules in
12525 		 [7.1.3/8 dcl.typedef] to create the final reference type:
12526 
12527 		 "If a typedef TD names a type that is a reference to a type
12528 		 T, an attempt to create the type 'lvalue reference to cv TD'
12529 		 creates the type 'lvalue reference to T,' while an attempt
12530 		 to create the type "rvalue reference to cv TD' creates the
12531 		 type TD."
12532               */
12533 	      if (VOID_TYPE_P (type))
12534 		/* We already gave an error.  */;
12535 	      else if (TYPE_REF_P (type))
12536 		{
12537 		  if (declarator->u.reference.rvalue_ref)
12538 		    /* Leave type alone.  */;
12539 		  else
12540 		    type = cp_build_reference_type (TREE_TYPE (type), false);
12541 		}
12542 	      else
12543 		type = cp_build_reference_type
12544 		  (type, declarator->u.reference.rvalue_ref);
12545 
12546 	      /* In C++0x, we need this check for direct reference to
12547 		 reference declarations, which are forbidden by
12548 		 [8.3.2/5 dcl.ref]. Reference to reference declarations
12549 		 are only allowed indirectly through typedefs and template
12550 		 type arguments. Example:
12551 
12552 		   void foo(int & &);      // invalid ref-to-ref decl
12553 
12554 		   typedef int & int_ref;
12555 		   void foo(int_ref &);    // valid ref-to-ref decl
12556 	      */
12557 	      if (inner_declarator && inner_declarator->kind == cdk_reference)
12558 		error ("cannot declare reference to %q#T, which is not "
12559 		       "a typedef or a template type argument", type);
12560 	    }
12561 	  else if (TREE_CODE (type) == METHOD_TYPE)
12562 	    type = build_ptrmemfunc_type (build_pointer_type (type));
12563 	  else if (declarator->kind == cdk_ptrmem)
12564 	    {
12565 	      gcc_assert (TREE_CODE (declarator->u.pointer.class_type)
12566 			  != NAMESPACE_DECL);
12567 	      if (declarator->u.pointer.class_type == error_mark_node)
12568 		/* We will already have complained.  */
12569 		type = error_mark_node;
12570 	      else
12571 		type = build_ptrmem_type (declarator->u.pointer.class_type,
12572 					  type);
12573 	    }
12574 	  else
12575 	    type = build_pointer_type (type);
12576 
12577 	  /* Process a list of type modifier keywords (such as
12578 	     const or volatile) that were given inside the `*' or `&'.  */
12579 
12580 	  if (declarator->u.pointer.qualifiers)
12581 	    {
12582 	      type
12583 		= cp_build_qualified_type (type,
12584 					   declarator->u.pointer.qualifiers);
12585 	      type_quals = cp_type_quals (type);
12586 	    }
12587 
12588 	  /* Apply C++11 attributes to the pointer, and not to the
12589 	     type pointed to.  This is unlike what is done for GNU
12590 	     attributes above.  It is to comply with [dcl.ptr]/1:
12591 
12592 		 [the optional attribute-specifier-seq (7.6.1) appertains
12593 		  to the pointer and not to the object pointed to].  */
12594 	  if (declarator->std_attributes)
12595 	    decl_attributes (&type, declarator->std_attributes,
12596 			     0);
12597 
12598 	  ctype = NULL_TREE;
12599 	  break;
12600 
12601 	case cdk_error:
12602 	  break;
12603 
12604 	default:
12605 	  gcc_unreachable ();
12606 	}
12607     }
12608 
12609   id_loc = declarator ? declarator->id_loc : input_location;
12610 
12611   /* A `constexpr' specifier used in an object declaration declares
12612      the object as `const'.  */
12613   if (constexpr_p && innermost_code != cdk_function)
12614     {
12615       /* DR1688 says that a `constexpr' specifier in combination with
12616 	 `volatile' is valid.  */
12617 
12618       if (!TYPE_REF_P (type))
12619 	{
12620 	  type_quals |= TYPE_QUAL_CONST;
12621 	  type = cp_build_qualified_type (type, type_quals);
12622 	}
12623     }
12624 
12625   if (unqualified_id && TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR
12626       && !FUNC_OR_METHOD_TYPE_P (type)
12627       && !variable_template_p (TREE_OPERAND (unqualified_id, 0)))
12628     {
12629       error ("template-id %qD used as a declarator",
12630 	     unqualified_id);
12631       unqualified_id = dname;
12632     }
12633 
12634   /* If TYPE is a FUNCTION_TYPE, but the function name was explicitly
12635      qualified with a class-name, turn it into a METHOD_TYPE, unless
12636      we know that the function is static.  We take advantage of this
12637      opportunity to do other processing that pertains to entities
12638      explicitly declared to be class members.  Note that if DECLARATOR
12639      is non-NULL, we know it is a cdk_id declarator; otherwise, we
12640      would not have exited the loop above.  */
12641   if (declarator
12642       && declarator->kind == cdk_id
12643       && declarator->u.id.qualifying_scope
12644       && MAYBE_CLASS_TYPE_P (declarator->u.id.qualifying_scope))
12645     {
12646       ctype = declarator->u.id.qualifying_scope;
12647       ctype = TYPE_MAIN_VARIANT (ctype);
12648       template_count = num_template_headers_for_class (ctype);
12649 
12650       if (ctype == current_class_type)
12651 	{
12652 	  if (friendp)
12653 	    {
12654 	      permerror (declspecs->locations[ds_friend],
12655 			 "member functions are implicitly "
12656 			 "friends of their class");
12657 	      friendp = 0;
12658 	    }
12659 	  else
12660 	    permerror (id_loc, "extra qualification %<%T::%> on member %qs",
12661 		       ctype, name);
12662 	}
12663       else if (/* If the qualifying type is already complete, then we
12664 		  can skip the following checks.  */
12665 	       !COMPLETE_TYPE_P (ctype)
12666 	       && (/* If the function is being defined, then
12667 		      qualifying type must certainly be complete.  */
12668 		   funcdef_flag
12669 		   /* A friend declaration of "T::f" is OK, even if
12670 		      "T" is a template parameter.  But, if this
12671 		      function is not a friend, the qualifying type
12672 		      must be a class.  */
12673 		   || (!friendp && !CLASS_TYPE_P (ctype))
12674 		   /* For a declaration, the type need not be
12675 		      complete, if either it is dependent (since there
12676 		      is no meaningful definition of complete in that
12677 		      case) or the qualifying class is currently being
12678 		      defined.  */
12679 		   || !(dependent_type_p (ctype)
12680 			|| currently_open_class (ctype)))
12681 	       /* Check that the qualifying type is complete.  */
12682 	       && !complete_type_or_else (ctype, NULL_TREE))
12683 	return error_mark_node;
12684       else if (TREE_CODE (type) == FUNCTION_TYPE)
12685 	{
12686 	  if (current_class_type
12687 	      && (!friendp || funcdef_flag || initialized))
12688 	    {
12689 	      error_at (id_loc, funcdef_flag || initialized
12690 			? G_("cannot define member function %<%T::%s%> "
12691 			     "within %qT")
12692 			: G_("cannot declare member function %<%T::%s%> "
12693 			     "within %qT"),
12694 			ctype, name, current_class_type);
12695 	      return error_mark_node;
12696 	    }
12697 	}
12698       else if (typedef_p && current_class_type)
12699 	{
12700 	  error_at (id_loc, "cannot declare member %<%T::%s%> within %qT",
12701 		    ctype, name, current_class_type);
12702 	  return error_mark_node;
12703 	}
12704     }
12705 
12706   if (ctype == NULL_TREE && decl_context == FIELD && friendp == 0)
12707     ctype = current_class_type;
12708 
12709   /* Now TYPE has the actual type.  */
12710 
12711   if (returned_attrs)
12712     {
12713       if (attrlist)
12714 	*attrlist = chainon (returned_attrs, *attrlist);
12715       else
12716 	attrlist = &returned_attrs;
12717     }
12718 
12719   if (declarator
12720       && declarator->kind == cdk_id
12721       && declarator->std_attributes
12722       && attrlist != NULL)
12723     {
12724       /* [dcl.meaning]/1: The optional attribute-specifier-seq following
12725 	 a declarator-id appertains to the entity that is declared.  */
12726       if (declarator->std_attributes != error_mark_node)
12727 	*attrlist = chainon (*attrlist, declarator->std_attributes);
12728       else
12729 	/* We should have already diagnosed the issue (c++/78344).  */
12730 	gcc_assert (seen_error ());
12731     }
12732 
12733   /* Handle parameter packs. */
12734   if (parameter_pack_p)
12735     {
12736       if (decl_context == PARM)
12737         /* Turn the type into a pack expansion.*/
12738         type = make_pack_expansion (type);
12739       else
12740         error ("non-parameter %qs cannot be a parameter pack", name);
12741     }
12742 
12743   if ((decl_context == FIELD || decl_context == PARM)
12744       && !processing_template_decl
12745       && variably_modified_type_p (type, NULL_TREE))
12746     {
12747       if (decl_context == FIELD)
12748 	error_at (id_loc,
12749 		  "data member may not have variably modified type %qT", type);
12750       else
12751 	error_at (id_loc,
12752 		  "parameter may not have variably modified type %qT", type);
12753       type = error_mark_node;
12754     }
12755 
12756   if (explicitp == 1 || (explicitp && friendp))
12757     {
12758       /* [dcl.fct.spec] (C++11) The explicit specifier shall be used only
12759 	 in the declaration of a constructor or conversion function within
12760 	 a class definition.  */
12761       if (!current_class_type)
12762 	error_at (declspecs->locations[ds_explicit],
12763 		  "%<explicit%> outside class declaration");
12764       else if (friendp)
12765 	error_at (declspecs->locations[ds_explicit],
12766 		  "%<explicit%> in friend declaration");
12767       else
12768 	error_at (declspecs->locations[ds_explicit],
12769 		  "only declarations of constructors and conversion operators "
12770 		  "can be %<explicit%>");
12771       explicitp = 0;
12772     }
12773 
12774   if (storage_class == sc_mutable)
12775     {
12776       location_t sloc = declspecs->locations[ds_storage_class];
12777       if (decl_context != FIELD || friendp)
12778 	{
12779 	  error_at (sloc, "non-member %qs cannot be declared %<mutable%>",
12780 		    name);
12781 	  storage_class = sc_none;
12782 	}
12783       else if (decl_context == TYPENAME || typedef_p)
12784 	{
12785 	  error_at (sloc,
12786 		    "non-object member %qs cannot be declared %<mutable%>",
12787 		    name);
12788 	  storage_class = sc_none;
12789 	}
12790       else if (FUNC_OR_METHOD_TYPE_P (type))
12791 	{
12792 	  error_at (sloc, "function %qs cannot be declared %<mutable%>",
12793 		    name);
12794 	  storage_class = sc_none;
12795 	}
12796       else if (staticp)
12797 	{
12798 	  error_at (sloc, "%<static%> %qs cannot be declared %<mutable%>",
12799 		    name);
12800 	  storage_class = sc_none;
12801 	}
12802       else if (type_quals & TYPE_QUAL_CONST)
12803 	{
12804 	  error_at (sloc, "%<const%> %qs cannot be declared %<mutable%>",
12805 		    name);
12806 	  storage_class = sc_none;
12807 	}
12808       else if (TYPE_REF_P (type))
12809 	{
12810 	  permerror (sloc, "reference %qs cannot be declared %<mutable%>",
12811 		     name);
12812 	  storage_class = sc_none;
12813 	}
12814     }
12815 
12816   /* If this is declaring a typedef name, return a TYPE_DECL.  */
12817   if (typedef_p && decl_context != TYPENAME)
12818     {
12819       bool alias_p = decl_spec_seq_has_spec_p (declspecs, ds_alias);
12820       tree decl;
12821 
12822       if (funcdef_flag)
12823 	{
12824 	  if (decl_context == NORMAL)
12825 	    error_at (id_loc,
12826 		      "typedef may not be a function definition");
12827 	  else
12828 	    error_at (id_loc,
12829 		      "typedef may not be a member function definition");
12830 	  return error_mark_node;
12831 	}
12832 
12833       /* This declaration:
12834 
12835 	   typedef void f(int) const;
12836 
12837 	 declares a function type which is not a member of any
12838 	 particular class, but which is cv-qualified; for
12839 	 example "f S::*" declares a pointer to a const-qualified
12840 	 member function of S.  We record the cv-qualification in the
12841 	 function type.  */
12842       if ((rqual || memfn_quals) && TREE_CODE (type) == FUNCTION_TYPE)
12843         {
12844           type = apply_memfn_quals (type, memfn_quals, rqual);
12845 
12846           /* We have now dealt with these qualifiers.  */
12847           memfn_quals = TYPE_UNQUALIFIED;
12848 	  rqual = REF_QUAL_NONE;
12849         }
12850 
12851       if (type_uses_auto (type))
12852 	{
12853 	  if (alias_p)
12854 	    error_at (declspecs->locations[ds_type_spec],
12855 		      "%<auto%> not allowed in alias declaration");
12856 	  else
12857 	    error_at (declspecs->locations[ds_type_spec],
12858 		      "typedef declared %<auto%>");
12859 	  type = error_mark_node;
12860 	}
12861 
12862       if (reqs)
12863 	error_at (location_of (reqs), "requires-clause on typedef");
12864 
12865       if (id_declarator && declarator->u.id.qualifying_scope)
12866 	{
12867 	  error_at (id_loc, "typedef name may not be a nested-name-specifier");
12868 	  type = error_mark_node;
12869 	}
12870 
12871       if (decl_context == FIELD)
12872 	decl = build_lang_decl_loc (id_loc, TYPE_DECL, unqualified_id, type);
12873       else
12874 	decl = build_decl (id_loc, TYPE_DECL, unqualified_id, type);
12875 
12876       if (decl_context != FIELD)
12877 	{
12878 	  if (!current_function_decl)
12879 	    DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
12880 	  else if (DECL_MAYBE_IN_CHARGE_CDTOR_P (current_function_decl))
12881 	    /* The TYPE_DECL is "abstract" because there will be
12882 	       clones of this constructor/destructor, and there will
12883 	       be copies of this TYPE_DECL generated in those
12884 	       clones.  The decloning optimization (for space) may
12885                revert this subsequently if it determines that
12886                the clones should share a common implementation.  */
12887 	    DECL_ABSTRACT_P (decl) = true;
12888 	}
12889       else if (current_class_type
12890 	       && constructor_name_p (unqualified_id, current_class_type))
12891 	permerror (id_loc, "ISO C++ forbids nested type %qD with same name "
12892 		   "as enclosing class",
12893 		   unqualified_id);
12894 
12895       /* If the user declares "typedef struct {...} foo" then the
12896 	 struct will have an anonymous name.  Fill that name in now.
12897 	 Nothing can refer to it, so nothing needs know about the name
12898 	 change.  */
12899       if (type != error_mark_node
12900 	  && unqualified_id
12901 	  && TYPE_NAME (type)
12902 	  && TREE_CODE (TYPE_NAME (type)) == TYPE_DECL
12903 	  && TYPE_UNNAMED_P (type)
12904 	  && declspecs->type_definition_p
12905 	  && attributes_naming_typedef_ok (*attrlist)
12906 	  && cp_type_quals (type) == TYPE_UNQUALIFIED)
12907 	name_unnamed_type (type, decl);
12908 
12909       if (signed_p
12910 	  || (typedef_decl && C_TYPEDEF_EXPLICITLY_SIGNED (typedef_decl)))
12911 	C_TYPEDEF_EXPLICITLY_SIGNED (decl) = 1;
12912 
12913       bad_specifiers (decl, BSP_TYPE, virtualp,
12914 		      memfn_quals != TYPE_UNQUALIFIED,
12915 		      inlinep, friendp, raises != NULL_TREE,
12916 		      declspecs->locations);
12917 
12918       if (alias_p)
12919 	/* Acknowledge that this was written:
12920 	     `using analias = atype;'.  */
12921 	TYPE_DECL_ALIAS_P (decl) = 1;
12922 
12923       return decl;
12924     }
12925 
12926   /* Detect the case of an array type of unspecified size
12927      which came, as such, direct from a typedef name.
12928      We must copy the type, so that the array's domain can be
12929      individually set by the object's initializer.  */
12930 
12931   if (type && typedef_type
12932       && TREE_CODE (type) == ARRAY_TYPE && !TYPE_DOMAIN (type)
12933       && TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (typedef_type))
12934     type = build_cplus_array_type (TREE_TYPE (type), NULL_TREE);
12935 
12936   /* Detect where we're using a typedef of function type to declare a
12937      function. PARMS will not be set, so we must create it now.  */
12938 
12939   if (type == typedef_type && TREE_CODE (type) == FUNCTION_TYPE)
12940     {
12941       tree decls = NULL_TREE;
12942       tree args;
12943 
12944       for (args = TYPE_ARG_TYPES (type);
12945 	   args && args != void_list_node;
12946 	   args = TREE_CHAIN (args))
12947 	{
12948 	  tree decl = cp_build_parm_decl (NULL_TREE, NULL_TREE,
12949 					  TREE_VALUE (args));
12950 
12951 	  DECL_CHAIN (decl) = decls;
12952 	  decls = decl;
12953 	}
12954 
12955       parms = nreverse (decls);
12956 
12957       if (decl_context != TYPENAME)
12958 	{
12959 	  /* The qualifiers on the function type become the qualifiers on
12960 	     the non-static member function. */
12961 	  memfn_quals |= type_memfn_quals (type);
12962 	  rqual = type_memfn_rqual (type);
12963 	  type_quals = TYPE_UNQUALIFIED;
12964 	  raises = TYPE_RAISES_EXCEPTIONS (type);
12965 	}
12966     }
12967 
12968   /* If this is a type name (such as, in a cast or sizeof),
12969      compute the type and return it now.  */
12970 
12971   if (decl_context == TYPENAME)
12972     {
12973       /* Note that here we don't care about type_quals.  */
12974 
12975       /* Special case: "friend class foo" looks like a TYPENAME context.  */
12976       if (friendp)
12977 	{
12978 	  if (inlinep)
12979 	    {
12980 	      error ("%<inline%> specified for friend class declaration");
12981 	      inlinep = 0;
12982 	    }
12983 
12984 	  if (!current_aggr)
12985 	    {
12986 	      /* Don't allow friend declaration without a class-key.  */
12987 	      if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
12988 		permerror (input_location, "template parameters cannot be friends");
12989 	      else if (TREE_CODE (type) == TYPENAME_TYPE)
12990 		permerror (input_location, "friend declaration requires class-key, "
12991 			   "i.e. %<friend class %T::%D%>",
12992 			   TYPE_CONTEXT (type), TYPENAME_TYPE_FULLNAME (type));
12993 	      else
12994 		permerror (input_location, "friend declaration requires class-key, "
12995 			   "i.e. %<friend %#T%>",
12996 			   type);
12997 	    }
12998 
12999 	  /* Only try to do this stuff if we didn't already give up.  */
13000 	  if (type != integer_type_node)
13001 	    {
13002 	      /* A friendly class?  */
13003 	      if (current_class_type)
13004 		make_friend_class (current_class_type, TYPE_MAIN_VARIANT (type),
13005 				   /*complain=*/true);
13006 	      else
13007 		error ("trying to make class %qT a friend of global scope",
13008 		       type);
13009 
13010 	      type = void_type_node;
13011 	    }
13012 	}
13013       else if (memfn_quals || rqual)
13014 	{
13015 	  if (ctype == NULL_TREE
13016 	      && TREE_CODE (type) == METHOD_TYPE)
13017 	    ctype = TYPE_METHOD_BASETYPE (type);
13018 
13019 	  if (ctype)
13020 	    type = build_memfn_type (type, ctype, memfn_quals, rqual);
13021 	  /* Core issue #547: need to allow this in template type args.
13022 	     Allow it in general in C++11 for alias-declarations.  */
13023 	  else if ((template_type_arg || cxx_dialect >= cxx11)
13024 		   && TREE_CODE (type) == FUNCTION_TYPE)
13025 	    type = apply_memfn_quals (type, memfn_quals, rqual);
13026 	  else
13027 	    error ("invalid qualifiers on non-member function type");
13028 	}
13029 
13030       if (reqs)
13031 	error_at (location_of (reqs), "requires-clause on type-id");
13032 
13033       return type;
13034     }
13035   else if (unqualified_id == NULL_TREE && decl_context != PARM
13036 	   && decl_context != CATCHPARM
13037 	   && TREE_CODE (type) != UNION_TYPE
13038 	   && ! bitfield
13039 	   && innermost_code != cdk_decomp)
13040     {
13041       error ("abstract declarator %qT used as declaration", type);
13042       return error_mark_node;
13043     }
13044 
13045   if (!FUNC_OR_METHOD_TYPE_P (type))
13046     {
13047       /* Only functions may be declared using an operator-function-id.  */
13048       if (dname && IDENTIFIER_ANY_OP_P (dname))
13049 	{
13050 	  error_at (id_loc, "declaration of %qD as non-function", dname);
13051 	  return error_mark_node;
13052 	}
13053 
13054       if (reqs)
13055 	error_at (location_of (reqs),
13056 		  "requires-clause on declaration of non-function type %qT",
13057 		  type);
13058     }
13059 
13060   /* We don't check parameter types here because we can emit a better
13061      error message later.  */
13062   if (decl_context != PARM)
13063     {
13064       type = check_var_type (unqualified_id, type, id_loc);
13065       if (type == error_mark_node)
13066         return error_mark_node;
13067     }
13068 
13069   /* Now create the decl, which may be a VAR_DECL, a PARM_DECL
13070      or a FUNCTION_DECL, depending on DECL_CONTEXT and TYPE.  */
13071 
13072   if (decl_context == PARM || decl_context == CATCHPARM)
13073     {
13074       if (ctype || in_namespace)
13075 	error ("cannot use %<::%> in parameter declaration");
13076 
13077       tree auto_node = type_uses_auto (type);
13078       if (auto_node && !(cxx_dialect >= cxx17 && template_parm_flag))
13079 	{
13080 	  if (cxx_dialect >= cxx14)
13081 	    {
13082 	      if (decl_context == PARM && AUTO_IS_DECLTYPE (auto_node))
13083 		error_at (typespec_loc,
13084 			  "cannot declare a parameter with %<decltype(auto)%>");
13085 	      else
13086 		error_at (typespec_loc,
13087 			  "%<auto%> parameter not permitted in this context");
13088 	    }
13089 	  else
13090 	    error_at (typespec_loc, "parameter declared %<auto%>");
13091 	  type = error_mark_node;
13092 	}
13093 
13094       /* A parameter declared as an array of T is really a pointer to T.
13095 	 One declared as a function is really a pointer to a function.
13096 	 One declared as a member is really a pointer to member.  */
13097 
13098       if (TREE_CODE (type) == ARRAY_TYPE)
13099 	{
13100 	  /* Transfer const-ness of array into that of type pointed to.  */
13101 	  type = build_pointer_type (TREE_TYPE (type));
13102 	  type_quals = TYPE_UNQUALIFIED;
13103 	  array_parameter_p = true;
13104 	}
13105       else if (TREE_CODE (type) == FUNCTION_TYPE)
13106 	type = build_pointer_type (type);
13107     }
13108 
13109   if (ctype && TREE_CODE (type) == FUNCTION_TYPE && staticp < 2
13110       && !(unqualified_id
13111 	   && identifier_p (unqualified_id)
13112 	   && IDENTIFIER_NEWDEL_OP_P (unqualified_id)))
13113     {
13114       cp_cv_quals real_quals = memfn_quals;
13115       if (cxx_dialect < cxx14 && constexpr_p
13116 	  && sfk != sfk_constructor && sfk != sfk_destructor)
13117 	real_quals |= TYPE_QUAL_CONST;
13118       type = build_memfn_type (type, ctype, real_quals, rqual);
13119     }
13120 
13121   {
13122     tree decl = NULL_TREE;
13123 
13124     if (decl_context == PARM)
13125       {
13126 	decl = cp_build_parm_decl (NULL_TREE, unqualified_id, type);
13127 	DECL_ARRAY_PARAMETER_P (decl) = array_parameter_p;
13128 
13129 	bad_specifiers (decl, BSP_PARM, virtualp,
13130 			memfn_quals != TYPE_UNQUALIFIED,
13131 			inlinep, friendp, raises != NULL_TREE,
13132 			declspecs->locations);
13133       }
13134     else if (decl_context == FIELD)
13135       {
13136 	if (!staticp && !friendp && TREE_CODE (type) != METHOD_TYPE)
13137 	  if (tree auto_node = type_uses_auto (type))
13138 	    {
13139 	      location_t tloc = declspecs->locations[ds_type_spec];
13140 	      if (CLASS_PLACEHOLDER_TEMPLATE (auto_node))
13141 		error_at (tloc, "invalid use of template-name %qE without an "
13142 			  "argument list",
13143 			  CLASS_PLACEHOLDER_TEMPLATE (auto_node));
13144 	      else
13145 		error_at (tloc, "non-static data member declared with "
13146 			  "placeholder %qT", auto_node);
13147 	      type = error_mark_node;
13148 	    }
13149 
13150 	/* The C99 flexible array extension.  */
13151 	if (!staticp && TREE_CODE (type) == ARRAY_TYPE
13152 	    && TYPE_DOMAIN (type) == NULL_TREE)
13153 	  {
13154 	    if (ctype
13155 		&& (TREE_CODE (ctype) == UNION_TYPE
13156 		    || TREE_CODE (ctype) == QUAL_UNION_TYPE))
13157 	      {
13158 		error_at (id_loc, "flexible array member in union");
13159 		type = error_mark_node;
13160 	      }
13161 	    else
13162 	      {
13163 		/* Array is a flexible member.  */
13164 		if (name)
13165 		  pedwarn (id_loc, OPT_Wpedantic,
13166 			   "ISO C++ forbids flexible array member %qs", name);
13167 		else
13168 		  pedwarn (input_location, OPT_Wpedantic,
13169 			   "ISO C++ forbids flexible array members");
13170 
13171 		/* Flexible array member has a null domain.  */
13172 		type = build_cplus_array_type (TREE_TYPE (type), NULL_TREE);
13173 	      }
13174 	  }
13175 
13176 	if (type == error_mark_node)
13177 	  {
13178 	    /* Happens when declaring arrays of sizes which
13179 	       are error_mark_node, for example.  */
13180 	    decl = NULL_TREE;
13181 	  }
13182 	else if (in_namespace && !friendp)
13183 	  {
13184 	    /* Something like struct S { int N::j; };  */
13185 	    error_at (id_loc, "invalid use of %<::%>");
13186 	    return error_mark_node;
13187 	  }
13188 	else if (FUNC_OR_METHOD_TYPE_P (type) && unqualified_id)
13189 	  {
13190 	    int publicp = 0;
13191 	    tree function_context;
13192 
13193 	    if (friendp == 0)
13194 	      {
13195 		/* This should never happen in pure C++ (the check
13196 		   could be an assert).  It could happen in
13197 		   Objective-C++ if someone writes invalid code that
13198 		   uses a function declaration for an instance
13199 		   variable or property (instance variables and
13200 		   properties are parsed as FIELD_DECLs, but they are
13201 		   part of an Objective-C class, not a C++ class).
13202 		   That code is invalid and is caught by this
13203 		   check.  */
13204 		if (!ctype)
13205 		  {
13206 		    error ("declaration of function %qD in invalid context",
13207 			   unqualified_id);
13208 		    return error_mark_node;
13209 		  }
13210 
13211 		/* ``A union may [ ... ] not [ have ] virtual functions.''
13212 		   ARM 9.5 */
13213 		if (virtualp && TREE_CODE (ctype) == UNION_TYPE)
13214 		  {
13215 		    error_at (declspecs->locations[ds_virtual],
13216 			      "function %qD declared %<virtual%> inside a union",
13217 			      unqualified_id);
13218 		    return error_mark_node;
13219 		  }
13220 
13221 		if (virtualp
13222 		    && identifier_p (unqualified_id)
13223 		    && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
13224 		  {
13225 		    error_at (declspecs->locations[ds_virtual],
13226 			      "%qD cannot be declared %<virtual%>, since it "
13227 			      "is always static", unqualified_id);
13228 		    virtualp = 0;
13229 		  }
13230 	      }
13231 
13232 	    /* Check that the name used for a destructor makes sense.  */
13233 	    if (sfk == sfk_destructor)
13234 	      {
13235 		tree uqname = id_declarator->u.id.unqualified_name;
13236 
13237 		if (!ctype)
13238 		  {
13239 		    gcc_assert (friendp);
13240 		    error_at (id_loc, "expected qualified name in friend "
13241 			      "declaration for destructor %qD", uqname);
13242 		    return error_mark_node;
13243 		  }
13244 
13245 		if (!check_dtor_name (ctype, TREE_OPERAND (uqname, 0)))
13246 		  {
13247 		    error_at (id_loc, "declaration of %qD as member of %qT",
13248 			      uqname, ctype);
13249 		    return error_mark_node;
13250 		  }
13251                 if (concept_p)
13252                   {
13253                     error_at (declspecs->locations[ds_concept],
13254 			      "a destructor cannot be %qs", "concept");
13255                     return error_mark_node;
13256                   }
13257 		if (constexpr_p && cxx_dialect < cxx2a)
13258 		  {
13259 		    error_at (declspecs->locations[ds_constexpr],
13260 			      "%<constexpr%> destructors only available"
13261 			      " with %<-std=c++2a%> or %<-std=gnu++2a%>");
13262 		    return error_mark_node;
13263 		  }
13264 		if (consteval_p)
13265 		  {
13266 		    error_at (declspecs->locations[ds_consteval],
13267 			      "a destructor cannot be %qs", "consteval");
13268 		    return error_mark_node;
13269 		  }
13270 	      }
13271 	    else if (sfk == sfk_constructor && friendp && !ctype)
13272 	      {
13273 		error ("expected qualified name in friend declaration "
13274 		       "for constructor %qD",
13275 		       id_declarator->u.id.unqualified_name);
13276 		return error_mark_node;
13277 	      }
13278 	    if (sfk == sfk_constructor)
13279 	      if (concept_p)
13280 		{
13281 		  error_at (declspecs->locations[ds_concept],
13282 			    "a constructor cannot be %<concept%>");
13283 		  return error_mark_node;
13284 		}
13285 	    if (concept_p)
13286 	      {
13287 		error_at (declspecs->locations[ds_concept],
13288 			  "a concept cannot be a member function");
13289 		concept_p = false;
13290 	      }
13291 	    else if (consteval_p
13292 		     && identifier_p (unqualified_id)
13293 		     && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
13294 	      {
13295 		error_at (declspecs->locations[ds_consteval],
13296 			  "%qD cannot be %qs", unqualified_id, "consteval");
13297 		consteval_p = false;
13298 	      }
13299 
13300 	    if (TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
13301 	      {
13302 		tree tmpl = TREE_OPERAND (unqualified_id, 0);
13303 		if (variable_template_p (tmpl))
13304 		  {
13305 		    error_at (id_loc, "specialization of variable template "
13306 			      "%qD declared as function", tmpl);
13307 		    inform (DECL_SOURCE_LOCATION (tmpl),
13308 			    "variable template declared here");
13309 		    return error_mark_node;
13310 		  }
13311 	      }
13312 
13313 	    /* Tell grokfndecl if it needs to set TREE_PUBLIC on the node.  */
13314 	    function_context
13315 	      = (ctype != NULL_TREE
13316 		 ? decl_function_context (TYPE_MAIN_DECL (ctype)) : NULL_TREE);
13317 	    publicp = ((! friendp || ! staticp)
13318 		       && function_context == NULL_TREE);
13319 
13320 	    decl = grokfndecl (ctype, type,
13321 			       TREE_CODE (unqualified_id) != TEMPLATE_ID_EXPR
13322 			       ? unqualified_id : dname,
13323 			       parms,
13324 			       unqualified_id,
13325 			       declspecs,
13326 			       reqs,
13327 			       virtualp, flags, memfn_quals, rqual, raises,
13328 			       friendp ? -1 : 0, friendp, publicp,
13329 			       inlinep | (2 * constexpr_p) | (4 * concept_p)
13330 				       | (8 * consteval_p),
13331 			       initialized == SD_DELETED, sfk,
13332 			       funcdef_flag, late_return_type_p,
13333 			       initialized,
13334 			       template_count, in_namespace,
13335 			       attrlist, id_loc);
13336             decl = set_virt_specifiers (decl, virt_specifiers);
13337 	    if (decl == NULL_TREE)
13338 	      return error_mark_node;
13339 #if 0
13340 	    /* This clobbers the attrs stored in `decl' from `attrlist'.  */
13341 	    /* The decl and setting of decl_attr is also turned off.  */
13342 	    decl = build_decl_attribute_variant (decl, decl_attr);
13343 #endif
13344 
13345 	    /* [class.conv.ctor]
13346 
13347 	       A constructor declared without the function-specifier
13348 	       explicit that can be called with a single parameter
13349 	       specifies a conversion from the type of its first
13350 	       parameter to the type of its class.  Such a constructor
13351 	       is called a converting constructor.  */
13352 	    if (explicitp == 2)
13353 	      DECL_NONCONVERTING_P (decl) = 1;
13354 
13355 	    if (declspecs->explicit_specifier)
13356 	      store_explicit_specifier (decl, declspecs->explicit_specifier);
13357 	  }
13358 	else if (!staticp
13359 		 && ((current_class_type
13360 		      && same_type_p (type, current_class_type))
13361 		     || (!dependent_type_p (type)
13362 			 && !COMPLETE_TYPE_P (complete_type (type))
13363 			 && (!complete_or_array_type_p (type)
13364 			     || initialized == 0))))
13365 	  {
13366 	    if (TREE_CODE (type) != ARRAY_TYPE
13367 		|| !COMPLETE_TYPE_P (TREE_TYPE (type)))
13368 	      {
13369 		if (unqualified_id)
13370 		  {
13371 		    error_at (id_loc, "field %qD has incomplete type %qT",
13372 			      unqualified_id, type);
13373 		    cxx_incomplete_type_inform (strip_array_types (type));
13374 		  }
13375 		else
13376 		  error ("name %qT has incomplete type", type);
13377 
13378 		type = error_mark_node;
13379 		decl = NULL_TREE;
13380 	      }
13381 	  }
13382 	else if (!verify_type_context (input_location,
13383 				       staticp
13384 				       ? TCTX_STATIC_STORAGE
13385 				       : TCTX_FIELD, type))
13386 	  {
13387 	    type = error_mark_node;
13388 	    decl = NULL_TREE;
13389 	  }
13390 	else
13391 	  {
13392 	    if (friendp)
13393 	      {
13394 		if (unqualified_id)
13395 		  error_at (id_loc,
13396 			    "%qE is neither function nor member function; "
13397 			    "cannot be declared friend", unqualified_id);
13398 		else
13399 		  error ("unnamed field is neither function nor member "
13400 			 "function; cannot be declared friend");
13401 		return error_mark_node;
13402 	      }
13403 	    decl = NULL_TREE;
13404 	  }
13405 
13406 	if (friendp)
13407 	  {
13408 	    /* Friends are treated specially.  */
13409 	    if (ctype == current_class_type)
13410 	      ;  /* We already issued a permerror.  */
13411 	    else if (decl && DECL_NAME (decl))
13412 	      {
13413 		if (initialized)
13414 		  /* Kludge: We need funcdef_flag to be true in do_friend for
13415 		     in-class defaulted functions, but that breaks grokfndecl.
13416 		     So set it here.  */
13417 		  funcdef_flag = true;
13418 		if (template_class_depth (current_class_type) == 0)
13419 		  {
13420 		    decl = check_explicit_specialization
13421 		      (unqualified_id, decl, template_count,
13422 		       2 * funcdef_flag + 4);
13423 		    if (decl == error_mark_node)
13424 		      return error_mark_node;
13425 		  }
13426 
13427 		decl = do_friend (ctype, unqualified_id, decl,
13428 				  *attrlist, flags,
13429 				  funcdef_flag);
13430 		return decl;
13431 	      }
13432 	    else
13433 	      return error_mark_node;
13434 	  }
13435 
13436 	/* Structure field.  It may not be a function, except for C++.  */
13437 
13438 	if (decl == NULL_TREE)
13439 	  {
13440 	    if (staticp)
13441 	      {
13442 		/* C++ allows static class members.  All other work
13443 		   for this is done by grokfield.  */
13444 		decl = build_lang_decl_loc (id_loc, VAR_DECL,
13445 					    unqualified_id, type);
13446 		set_linkage_for_static_data_member (decl);
13447 		if (concept_p)
13448 		  error_at (declspecs->locations[ds_concept],
13449 			    "static data member %qE declared %qs",
13450 			    unqualified_id, "concept");
13451 		else if (constexpr_p && !initialized)
13452 		  {
13453 		    error_at (DECL_SOURCE_LOCATION (decl),
13454 			      "%<constexpr%> static data member %qD must "
13455 			      "have an initializer", decl);
13456 		    constexpr_p = false;
13457 		  }
13458 		if (consteval_p)
13459 		  error_at (declspecs->locations[ds_consteval],
13460 			    "static data member %qE declared %qs",
13461 			    unqualified_id, "consteval");
13462 
13463 		if (inlinep)
13464 		  mark_inline_variable (decl, declspecs->locations[ds_inline]);
13465 
13466 		if (!DECL_VAR_DECLARED_INLINE_P (decl)
13467 		    && !(cxx_dialect >= cxx17 && constexpr_p))
13468 		  /* Even if there is an in-class initialization, DECL
13469 		     is considered undefined until an out-of-class
13470 		     definition is provided, unless this is an inline
13471 		     variable.  */
13472 		  DECL_EXTERNAL (decl) = 1;
13473 
13474 		if (thread_p)
13475 		  {
13476 		    CP_DECL_THREAD_LOCAL_P (decl) = true;
13477 		    if (!processing_template_decl)
13478 		      set_decl_tls_model (decl, decl_default_tls_model (decl));
13479 		    if (declspecs->gnu_thread_keyword_p)
13480 		      SET_DECL_GNU_TLS_P (decl);
13481 		  }
13482 	      }
13483 	    else
13484 	      {
13485 		if (concept_p)
13486 		  {
13487 		    error_at (declspecs->locations[ds_concept],
13488 			      "non-static data member %qE declared %qs",
13489 			      unqualified_id, "concept");
13490 		    concept_p = false;
13491 		    constexpr_p = false;
13492 		  }
13493 		else if (constexpr_p)
13494 		  {
13495 		    error_at (declspecs->locations[ds_constexpr],
13496 			      "non-static data member %qE declared %qs",
13497 			      unqualified_id, "constexpr");
13498 		    constexpr_p = false;
13499 		  }
13500 		if (constinit_p)
13501 		  {
13502 		    error_at (declspecs->locations[ds_constinit],
13503 			      "non-static data member %qE declared %qs",
13504 			      unqualified_id, "constinit");
13505 		    constinit_p = false;
13506 		  }
13507 		if (consteval_p)
13508 		  {
13509 		    error_at (declspecs->locations[ds_consteval],
13510 			      "non-static data member %qE declared %qs",
13511 			      unqualified_id, "consteval");
13512 		    consteval_p = false;
13513 		  }
13514 		decl = build_decl (id_loc, FIELD_DECL, unqualified_id, type);
13515 		DECL_NONADDRESSABLE_P (decl) = bitfield;
13516 		if (bitfield && !unqualified_id)
13517 		  {
13518 		    TREE_NO_WARNING (decl) = 1;
13519 		    DECL_PADDING_P (decl) = 1;
13520 		  }
13521 
13522 		if (storage_class == sc_mutable)
13523 		  {
13524 		    DECL_MUTABLE_P (decl) = 1;
13525 		    storage_class = sc_none;
13526 		  }
13527 
13528 		if (initialized)
13529 		  {
13530 		    /* An attempt is being made to initialize a non-static
13531 		       member.  This is new in C++11.  */
13532 		    maybe_warn_cpp0x (CPP0X_NSDMI);
13533 
13534 		    /* If this has been parsed with static storage class, but
13535 		       errors forced staticp to be cleared, ensure NSDMI is
13536 		       not present.  */
13537 		    if (declspecs->storage_class == sc_static)
13538 		      DECL_INITIAL (decl) = error_mark_node;
13539 		  }
13540 	      }
13541 
13542 	    bad_specifiers (decl, BSP_FIELD, virtualp,
13543 			    memfn_quals != TYPE_UNQUALIFIED,
13544 			    staticp ? false : inlinep, friendp,
13545 			    raises != NULL_TREE,
13546 			    declspecs->locations);
13547 	  }
13548       }
13549     else if (FUNC_OR_METHOD_TYPE_P (type))
13550       {
13551 	tree original_name;
13552 	int publicp = 0;
13553 
13554 	if (!unqualified_id)
13555 	  return error_mark_node;
13556 
13557 	if (TREE_CODE (unqualified_id) == TEMPLATE_ID_EXPR)
13558 	  original_name = dname;
13559 	else
13560 	  original_name = unqualified_id;
13561 	// FIXME:gcc_assert (original_name == dname);
13562 
13563 	if (storage_class == sc_auto)
13564 	  error_at (declspecs->locations[ds_storage_class],
13565 		    "storage class %<auto%> invalid for function %qs", name);
13566 	else if (storage_class == sc_register)
13567 	  error_at (declspecs->locations[ds_storage_class],
13568 		    "storage class %<register%> invalid for function %qs",
13569 		    name);
13570 	else if (thread_p)
13571 	  {
13572 	    if (declspecs->gnu_thread_keyword_p)
13573 	      error_at (declspecs->locations[ds_thread],
13574 			"storage class %<__thread%> invalid for function %qs",
13575 			name);
13576 	    else
13577 	      error_at (declspecs->locations[ds_thread],
13578 			"storage class %<thread_local%> invalid for "
13579 			"function %qs", name);
13580 	  }
13581 
13582         if (virt_specifiers)
13583           error ("virt-specifiers in %qs not allowed outside a class "
13584 		 "definition", name);
13585 	/* Function declaration not at top level.
13586 	   Storage classes other than `extern' are not allowed
13587 	   and `extern' makes no difference.  */
13588 	if (! toplevel_bindings_p ()
13589 	    && (storage_class == sc_static
13590 		|| decl_spec_seq_has_spec_p (declspecs, ds_inline))
13591 	    && pedantic)
13592 	  {
13593 	    if (storage_class == sc_static)
13594 	      pedwarn (declspecs->locations[ds_storage_class], OPT_Wpedantic,
13595 		       "%<static%> specifier invalid for function %qs "
13596 		       "declared out of global scope", name);
13597 	    else
13598 	      pedwarn (declspecs->locations[ds_inline], OPT_Wpedantic,
13599 		       "%<inline%> specifier invalid for function %qs "
13600 		       "declared out of global scope", name);
13601 	  }
13602 
13603 	if (ctype == NULL_TREE)
13604 	  {
13605 	    if (virtualp)
13606 	      {
13607 		error ("virtual non-class function %qs", name);
13608 		virtualp = 0;
13609 	      }
13610 	    else if (sfk == sfk_constructor
13611 		     || sfk == sfk_destructor)
13612 	      {
13613 		error (funcdef_flag
13614 		       ? G_("%qs defined in a non-class scope")
13615 		       : G_("%qs declared in a non-class scope"), name);
13616 		sfk = sfk_none;
13617 	      }
13618 	  }
13619 	if (consteval_p
13620 	    && identifier_p (unqualified_id)
13621 	    && IDENTIFIER_NEWDEL_OP_P (unqualified_id))
13622 	  {
13623 	    error_at (declspecs->locations[ds_consteval],
13624 		      "%qD cannot be %qs", unqualified_id, "consteval");
13625 	    consteval_p = false;
13626 	  }
13627 
13628 	/* Record whether the function is public.  */
13629 	publicp = (ctype != NULL_TREE
13630 		   || storage_class != sc_static);
13631 
13632 	decl = grokfndecl (ctype, type, original_name, parms, unqualified_id,
13633 			   declspecs,
13634                            reqs, virtualp, flags, memfn_quals, rqual, raises,
13635 			   1, friendp,
13636 			   publicp,
13637 			   inlinep | (2 * constexpr_p) | (4 * concept_p)
13638 				   | (8 * consteval_p),
13639 			   initialized == SD_DELETED,
13640                            sfk,
13641                            funcdef_flag,
13642 			   late_return_type_p,
13643 			   initialized,
13644 			   template_count, in_namespace, attrlist,
13645 			   id_loc);
13646 	if (decl == NULL_TREE)
13647 	  return error_mark_node;
13648 
13649 	if (explicitp == 2)
13650 	  DECL_NONCONVERTING_P (decl) = 1;
13651 	if (staticp == 1)
13652 	  {
13653 	    int invalid_static = 0;
13654 
13655 	    /* Don't allow a static member function in a class, and forbid
13656 	       declaring main to be static.  */
13657 	    if (TREE_CODE (type) == METHOD_TYPE)
13658 	      {
13659 		permerror (input_location, "cannot declare member function %qD to have "
13660 			   "static linkage", decl);
13661 		invalid_static = 1;
13662 	      }
13663 	    else if (current_function_decl)
13664 	      {
13665 		/* 7.1.1: There can be no static function declarations within a
13666 		   block.  */
13667 		error_at (declspecs->locations[ds_storage_class],
13668 			  "cannot declare static function inside another function");
13669 		invalid_static = 1;
13670 	      }
13671 
13672 	    if (invalid_static)
13673 	      {
13674 		staticp = 0;
13675 		storage_class = sc_none;
13676 	      }
13677 	  }
13678       }
13679     else
13680       {
13681 	/* It's a variable.  */
13682 
13683 	/* An uninitialized decl with `extern' is a reference.  */
13684 	decl = grokvardecl (type, dname, unqualified_id,
13685 			    declspecs,
13686 			    initialized,
13687 			    type_quals,
13688 			    inlinep,
13689 			    concept_p,
13690 			    template_count,
13691 			    ctype ? ctype : in_namespace,
13692 			    id_loc);
13693 	if (decl == NULL_TREE)
13694 	  return error_mark_node;
13695 
13696 	bad_specifiers (decl, BSP_VAR, virtualp,
13697 			memfn_quals != TYPE_UNQUALIFIED,
13698 			inlinep, friendp, raises != NULL_TREE,
13699 			declspecs->locations);
13700 
13701 	if (ctype)
13702 	  {
13703 	    DECL_CONTEXT (decl) = ctype;
13704 	    if (staticp == 1)
13705 	      {
13706 		permerror (declspecs->locations[ds_storage_class],
13707 			   "%<static%> may not be used when defining "
13708 			   "(as opposed to declaring) a static data member");
13709 		staticp = 0;
13710 		storage_class = sc_none;
13711 	      }
13712 	    if (storage_class == sc_register && TREE_STATIC (decl))
13713 	      {
13714 		error ("static member %qD declared %<register%>", decl);
13715 		storage_class = sc_none;
13716 	      }
13717 	    if (storage_class == sc_extern && pedantic)
13718 	      {
13719 		pedwarn (input_location, OPT_Wpedantic,
13720 			 "cannot explicitly declare member %q#D to have "
13721 			 "extern linkage", decl);
13722 		storage_class = sc_none;
13723 	      }
13724 	  }
13725 	else if (constexpr_p && DECL_EXTERNAL (decl))
13726 	  {
13727 	    error_at (DECL_SOURCE_LOCATION (decl),
13728 		      "declaration of %<constexpr%> variable %qD "
13729 		      "is not a definition", decl);
13730 	    constexpr_p = false;
13731 	  }
13732 	if (consteval_p)
13733 	  {
13734 	    error_at (DECL_SOURCE_LOCATION (decl),
13735 		      "a variable cannot be declared %<consteval%>");
13736 	    consteval_p = false;
13737 	  }
13738 
13739 	if (inlinep)
13740 	  mark_inline_variable (decl, declspecs->locations[ds_inline]);
13741 	if (innermost_code == cdk_decomp)
13742 	  {
13743 	    gcc_assert (declarator && declarator->kind == cdk_decomp);
13744 	    DECL_SOURCE_LOCATION (decl) = id_loc;
13745 	    DECL_ARTIFICIAL (decl) = 1;
13746 	    fit_decomposition_lang_decl (decl, NULL_TREE);
13747 	  }
13748       }
13749 
13750     if (VAR_P (decl) && !initialized)
13751       if (tree auto_node = type_uses_auto (type))
13752 	if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
13753 	  {
13754 	    location_t loc = declspecs->locations[ds_type_spec];
13755 	    error_at (loc, "declaration of %q#D has no initializer", decl);
13756 	    TREE_TYPE (decl) = error_mark_node;
13757 	  }
13758 
13759     if (storage_class == sc_extern && initialized && !funcdef_flag)
13760       {
13761 	if (toplevel_bindings_p ())
13762 	  {
13763 	    /* It's common practice (and completely valid) to have a const
13764 	       be initialized and declared extern.  */
13765 	    if (!(type_quals & TYPE_QUAL_CONST))
13766 	      warning_at (DECL_SOURCE_LOCATION (decl), 0,
13767 			  "%qs initialized and declared %<extern%>", name);
13768 	  }
13769 	else
13770 	  {
13771 	    error_at (DECL_SOURCE_LOCATION (decl),
13772 		      "%qs has both %<extern%> and initializer", name);
13773 	    return error_mark_node;
13774 	  }
13775       }
13776 
13777     /* Record `register' declaration for warnings on &
13778        and in case doing stupid register allocation.  */
13779 
13780     if (storage_class == sc_register)
13781       {
13782 	DECL_REGISTER (decl) = 1;
13783 	/* Warn about register storage specifiers on PARM_DECLs.  */
13784 	if (TREE_CODE (decl) == PARM_DECL)
13785 	  {
13786 	    if (cxx_dialect >= cxx17)
13787 	      pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
13788 		       "ISO C++17 does not allow %<register%> storage "
13789 		       "class specifier");
13790 	    else
13791 	      warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wregister,
13792 			  "%<register%> storage class specifier used");
13793 	  }
13794       }
13795     else if (storage_class == sc_extern)
13796       DECL_THIS_EXTERN (decl) = 1;
13797     else if (storage_class == sc_static)
13798       DECL_THIS_STATIC (decl) = 1;
13799 
13800     /* Set constexpr flag on vars (functions got it in grokfndecl).  */
13801     if (constexpr_p && VAR_P (decl))
13802       DECL_DECLARED_CONSTEXPR_P (decl) = true;
13803 
13804     /* Record constancy and volatility on the DECL itself .  There's
13805        no need to do this when processing a template; we'll do this
13806        for the instantiated declaration based on the type of DECL.  */
13807     if (!processing_template_decl)
13808       cp_apply_type_quals_to_decl (type_quals, decl);
13809 
13810     return decl;
13811   }
13812 }
13813 
13814 /* Subroutine of start_function.  Ensure that each of the parameter
13815    types (as listed in PARMS) is complete, as is required for a
13816    function definition.  */
13817 
13818 static void
require_complete_types_for_parms(tree parms)13819 require_complete_types_for_parms (tree parms)
13820 {
13821   for (; parms; parms = DECL_CHAIN (parms))
13822     {
13823       if (dependent_type_p (TREE_TYPE (parms)))
13824 	continue;
13825       if (!VOID_TYPE_P (TREE_TYPE (parms))
13826 	  && complete_type_or_else (TREE_TYPE (parms), parms))
13827 	{
13828 	  relayout_decl (parms);
13829 	  DECL_ARG_TYPE (parms) = type_passed_as (TREE_TYPE (parms));
13830 
13831 	  maybe_warn_parm_abi (TREE_TYPE (parms),
13832 			       DECL_SOURCE_LOCATION (parms));
13833 	}
13834       else
13835 	/* grokparms or complete_type_or_else will have already issued
13836 	   an error.  */
13837 	TREE_TYPE (parms) = error_mark_node;
13838     }
13839 }
13840 
13841 /* Returns nonzero if T is a local variable.  */
13842 
13843 int
local_variable_p(const_tree t)13844 local_variable_p (const_tree t)
13845 {
13846   if ((VAR_P (t)
13847        /* A VAR_DECL with a context that is a _TYPE is a static data
13848 	  member.  */
13849        && !TYPE_P (CP_DECL_CONTEXT (t))
13850        /* Any other non-local variable must be at namespace scope.  */
13851        && !DECL_NAMESPACE_SCOPE_P (t))
13852       || (TREE_CODE (t) == PARM_DECL))
13853     return 1;
13854 
13855   return 0;
13856 }
13857 
13858 /* Like local_variable_p, but suitable for use as a tree-walking
13859    function.  */
13860 
13861 static tree
local_variable_p_walkfn(tree * tp,int * walk_subtrees,void *)13862 local_variable_p_walkfn (tree *tp, int *walk_subtrees,
13863 			 void * /*data*/)
13864 {
13865   if (local_variable_p (*tp)
13866       && (!DECL_ARTIFICIAL (*tp) || DECL_NAME (*tp) == this_identifier))
13867     return *tp;
13868   else if (TYPE_P (*tp))
13869     *walk_subtrees = 0;
13870 
13871   return NULL_TREE;
13872 }
13873 
13874 /* Check that ARG, which is a default-argument expression for a
13875    parameter DECL, is valid.  Returns ARG, or ERROR_MARK_NODE, if
13876    something goes wrong.  DECL may also be a _TYPE node, rather than a
13877    DECL, if there is no DECL available.  */
13878 
13879 tree
check_default_argument(tree decl,tree arg,tsubst_flags_t complain)13880 check_default_argument (tree decl, tree arg, tsubst_flags_t complain)
13881 {
13882   tree var;
13883   tree decl_type;
13884 
13885   if (TREE_CODE (arg) == DEFERRED_PARSE)
13886     /* We get a DEFERRED_PARSE when looking at an in-class declaration
13887        with a default argument.  Ignore the argument for now; we'll
13888        deal with it after the class is complete.  */
13889     return arg;
13890 
13891   if (TYPE_P (decl))
13892     {
13893       decl_type = decl;
13894       decl = NULL_TREE;
13895     }
13896   else
13897     decl_type = TREE_TYPE (decl);
13898 
13899   if (arg == error_mark_node
13900       || decl == error_mark_node
13901       || TREE_TYPE (arg) == error_mark_node
13902       || decl_type == error_mark_node)
13903     /* Something already went wrong.  There's no need to check
13904        further.  */
13905     return error_mark_node;
13906 
13907   /* [dcl.fct.default]
13908 
13909      A default argument expression is implicitly converted to the
13910      parameter type.  */
13911   ++cp_unevaluated_operand;
13912   /* Avoid digest_init clobbering the initializer.  */
13913   tree carg = BRACE_ENCLOSED_INITIALIZER_P (arg) ? unshare_expr (arg): arg;
13914   perform_implicit_conversion_flags (decl_type, carg, complain,
13915 				     LOOKUP_IMPLICIT);
13916   --cp_unevaluated_operand;
13917 
13918   /* Avoid redundant -Wzero-as-null-pointer-constant warnings at
13919      the call sites.  */
13920   if (TYPE_PTR_OR_PTRMEM_P (decl_type)
13921       && null_ptr_cst_p (arg)
13922       /* Don't lose side-effects as in PR90473.  */
13923       && !TREE_SIDE_EFFECTS (arg))
13924     return nullptr_node;
13925 
13926   /* [dcl.fct.default]
13927 
13928      Local variables shall not be used in default argument
13929      expressions.
13930 
13931      The keyword `this' shall not be used in a default argument of a
13932      member function.  */
13933   var = cp_walk_tree_without_duplicates (&arg, local_variable_p_walkfn, NULL);
13934   if (var)
13935     {
13936       if (complain & tf_warning_or_error)
13937 	{
13938 	  if (DECL_NAME (var) == this_identifier)
13939 	    permerror (input_location, "default argument %qE uses %qD",
13940 		       arg, var);
13941 	  else
13942 	    error ("default argument %qE uses local variable %qD", arg, var);
13943 	}
13944       return error_mark_node;
13945     }
13946 
13947   /* All is well.  */
13948   return arg;
13949 }
13950 
13951 /* Returns a deprecated type used within TYPE, or NULL_TREE if none.  */
13952 
13953 static tree
type_is_deprecated(tree type)13954 type_is_deprecated (tree type)
13955 {
13956   enum tree_code code;
13957   if (TREE_DEPRECATED (type))
13958     return type;
13959   if (TYPE_NAME (type))
13960     {
13961       if (TREE_DEPRECATED (TYPE_NAME (type)))
13962 	return type;
13963       else
13964 	{
13965 	  cp_warn_deprecated_use_scopes (CP_DECL_CONTEXT (TYPE_NAME (type)));
13966 	  return NULL_TREE;
13967 	}
13968     }
13969 
13970   /* Do warn about using typedefs to a deprecated class.  */
13971   if (OVERLOAD_TYPE_P (type) && type != TYPE_MAIN_VARIANT (type))
13972     return type_is_deprecated (TYPE_MAIN_VARIANT (type));
13973 
13974   code = TREE_CODE (type);
13975 
13976   if (code == POINTER_TYPE || code == REFERENCE_TYPE
13977       || code == OFFSET_TYPE || code == FUNCTION_TYPE
13978       || code == METHOD_TYPE || code == ARRAY_TYPE)
13979     return type_is_deprecated (TREE_TYPE (type));
13980 
13981   if (TYPE_PTRMEMFUNC_P (type))
13982     return type_is_deprecated
13983       (TREE_TYPE (TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (type))));
13984 
13985   return NULL_TREE;
13986 }
13987 
13988 /* Decode the list of parameter types for a function type.
13989    Given the list of things declared inside the parens,
13990    return a list of types.
13991 
13992    If this parameter does not end with an ellipsis, we append
13993    void_list_node.
13994 
13995    *PARMS is set to the chain of PARM_DECLs created.  */
13996 
13997 tree
grokparms(tree parmlist,tree * parms)13998 grokparms (tree parmlist, tree *parms)
13999 {
14000   tree result = NULL_TREE;
14001   tree decls = NULL_TREE;
14002   tree parm;
14003   int any_error = 0;
14004 
14005   for (parm = parmlist; parm != NULL_TREE; parm = TREE_CHAIN (parm))
14006     {
14007       tree type = NULL_TREE;
14008       tree init = TREE_PURPOSE (parm);
14009       tree decl = TREE_VALUE (parm);
14010 
14011       if (parm == void_list_node)
14012 	break;
14013 
14014       if (! decl || TREE_TYPE (decl) == error_mark_node)
14015 	continue;
14016 
14017       type = TREE_TYPE (decl);
14018       if (VOID_TYPE_P (type))
14019 	{
14020 	  if (same_type_p (type, void_type_node)
14021 	      && !init
14022 	      && !DECL_NAME (decl) && !result
14023 	      && TREE_CHAIN (parm) == void_list_node)
14024 	    /* DR 577: A parameter list consisting of a single
14025 	       unnamed parameter of non-dependent type 'void'.  */
14026 	    break;
14027 	  else if (cv_qualified_p (type))
14028 	    error_at (DECL_SOURCE_LOCATION (decl),
14029 		      "invalid use of cv-qualified type %qT in "
14030 		      "parameter declaration", type);
14031 	  else
14032 	    error_at (DECL_SOURCE_LOCATION (decl),
14033 		      "invalid use of type %<void%> in parameter "
14034 		      "declaration");
14035 	  /* It's not a good idea to actually create parameters of
14036 	     type `void'; other parts of the compiler assume that a
14037 	     void type terminates the parameter list.  */
14038 	  type = error_mark_node;
14039 	  TREE_TYPE (decl) = error_mark_node;
14040 	}
14041 
14042       if (type != error_mark_node)
14043 	{
14044 	  if (deprecated_state != DEPRECATED_SUPPRESS)
14045 	    {
14046 	      tree deptype = type_is_deprecated (type);
14047 	      if (deptype)
14048 		cp_warn_deprecated_use (deptype);
14049 	    }
14050 
14051 	  /* [dcl.fct] "A parameter with volatile-qualified type is
14052 	     deprecated."  */
14053 	  if (CP_TYPE_VOLATILE_P (type))
14054 	    warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wvolatile,
14055 			"%<volatile%>-qualified parameter is "
14056 			"deprecated");
14057 
14058 	  /* Top-level qualifiers on the parameters are
14059 	     ignored for function types.  */
14060 	  type = cp_build_qualified_type (type, 0);
14061 	  if (TREE_CODE (type) == METHOD_TYPE)
14062 	    {
14063 	      error ("parameter %qD invalidly declared method type", decl);
14064 	      type = build_pointer_type (type);
14065 	      TREE_TYPE (decl) = type;
14066 	    }
14067 	  else if (abstract_virtuals_error (decl, type))
14068 	    any_error = 1;  /* Seems like a good idea.  */
14069 	  else if (cxx_dialect < cxx17 && INDIRECT_TYPE_P (type))
14070 	    {
14071 	      /* Before C++17 DR 393:
14072 		 [dcl.fct]/6, parameter types cannot contain pointers
14073 		 (references) to arrays of unknown bound.  */
14074 	      tree t = TREE_TYPE (type);
14075 	      int ptr = TYPE_PTR_P (type);
14076 
14077 	      while (1)
14078 		{
14079 		  if (TYPE_PTR_P (t))
14080 		    ptr = 1;
14081 		  else if (TREE_CODE (t) != ARRAY_TYPE)
14082 		    break;
14083 		  else if (!TYPE_DOMAIN (t))
14084 		    break;
14085 		  t = TREE_TYPE (t);
14086 		}
14087 	      if (TREE_CODE (t) == ARRAY_TYPE)
14088 		pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wpedantic,
14089 			 ptr
14090 			 ? G_("parameter %qD includes pointer to array of "
14091 			      "unknown bound %qT")
14092 			 : G_("parameter %qD includes reference to array of "
14093 			      "unknown bound %qT"),
14094 			 decl, t);
14095 	    }
14096 
14097 	  if (any_error)
14098 	    init = NULL_TREE;
14099 	  else if (init && !processing_template_decl)
14100 	    init = check_default_argument (decl, init, tf_warning_or_error);
14101 	}
14102 
14103       DECL_CHAIN (decl) = decls;
14104       decls = decl;
14105       result = tree_cons (init, type, result);
14106     }
14107   decls = nreverse (decls);
14108   result = nreverse (result);
14109   if (parm)
14110     result = chainon (result, void_list_node);
14111   *parms = decls;
14112 
14113   return result;
14114 }
14115 
14116 
14117 /* D is a constructor or overloaded `operator='.
14118 
14119    Let T be the class in which D is declared. Then, this function
14120    returns:
14121 
14122    -1 if D's is an ill-formed constructor or copy assignment operator
14123       whose first parameter is of type `T'.
14124    0  if D is not a copy constructor or copy assignment
14125       operator.
14126    1  if D is a copy constructor or copy assignment operator whose
14127       first parameter is a reference to non-const qualified T.
14128    2  if D is a copy constructor or copy assignment operator whose
14129       first parameter is a reference to const qualified T.
14130 
14131    This function can be used as a predicate. Positive values indicate
14132    a copy constructor and nonzero values indicate a copy assignment
14133    operator.  */
14134 
14135 int
copy_fn_p(const_tree d)14136 copy_fn_p (const_tree d)
14137 {
14138   tree args;
14139   tree arg_type;
14140   int result = 1;
14141 
14142   gcc_assert (DECL_FUNCTION_MEMBER_P (d));
14143 
14144   if (TREE_CODE (d) == TEMPLATE_DECL
14145       || (DECL_TEMPLATE_INFO (d)
14146 	  && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (d))))
14147     /* Instantiations of template member functions are never copy
14148        functions.  Note that member functions of templated classes are
14149        represented as template functions internally, and we must
14150        accept those as copy functions.  */
14151     return 0;
14152 
14153   args = FUNCTION_FIRST_USER_PARMTYPE (d);
14154   if (!args)
14155     return 0;
14156 
14157   arg_type = TREE_VALUE (args);
14158   if (arg_type == error_mark_node)
14159     return 0;
14160 
14161   if (TYPE_MAIN_VARIANT (arg_type) == DECL_CONTEXT (d))
14162     {
14163       /* Pass by value copy assignment operator.  */
14164       result = -1;
14165     }
14166   else if (TYPE_REF_P (arg_type)
14167 	   && !TYPE_REF_IS_RVALUE (arg_type)
14168 	   && TYPE_MAIN_VARIANT (TREE_TYPE (arg_type)) == DECL_CONTEXT (d))
14169     {
14170       if (CP_TYPE_CONST_P (TREE_TYPE (arg_type)))
14171 	result = 2;
14172     }
14173   else
14174     return 0;
14175 
14176   args = TREE_CHAIN (args);
14177 
14178   if (args && args != void_list_node && !TREE_PURPOSE (args))
14179     /* There are more non-optional args.  */
14180     return 0;
14181 
14182   return result;
14183 }
14184 
14185 /* D is a constructor or overloaded `operator='.
14186 
14187    Let T be the class in which D is declared. Then, this function
14188    returns true when D is a move constructor or move assignment
14189    operator, false otherwise.  */
14190 
14191 bool
move_fn_p(const_tree d)14192 move_fn_p (const_tree d)
14193 {
14194   gcc_assert (DECL_FUNCTION_MEMBER_P (d));
14195 
14196   if (cxx_dialect == cxx98)
14197     /* There are no move constructors if we are in C++98 mode.  */
14198     return false;
14199 
14200   if (TREE_CODE (d) == TEMPLATE_DECL
14201       || (DECL_TEMPLATE_INFO (d)
14202          && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (d))))
14203     /* Instantiations of template member functions are never move
14204        functions.  Note that member functions of templated classes are
14205        represented as template functions internally, and we must
14206        accept those as move functions.  */
14207     return 0;
14208 
14209   return move_signature_fn_p (d);
14210 }
14211 
14212 /* D is a constructor or overloaded `operator='.
14213 
14214    Then, this function returns true when D has the same signature as a move
14215    constructor or move assignment operator (because either it is such a
14216    ctor/op= or it is a template specialization with the same signature),
14217    false otherwise.  */
14218 
14219 bool
move_signature_fn_p(const_tree d)14220 move_signature_fn_p (const_tree d)
14221 {
14222   tree args;
14223   tree arg_type;
14224   bool result = false;
14225 
14226   args = FUNCTION_FIRST_USER_PARMTYPE (d);
14227   if (!args)
14228     return 0;
14229 
14230   arg_type = TREE_VALUE (args);
14231   if (arg_type == error_mark_node)
14232     return 0;
14233 
14234   if (TYPE_REF_P (arg_type)
14235       && TYPE_REF_IS_RVALUE (arg_type)
14236       && same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (arg_type)),
14237                       DECL_CONTEXT (d)))
14238     result = true;
14239 
14240   args = TREE_CHAIN (args);
14241 
14242   if (args && args != void_list_node && !TREE_PURPOSE (args))
14243     /* There are more non-optional args.  */
14244     return false;
14245 
14246   return result;
14247 }
14248 
14249 /* Remember any special properties of member function DECL.  */
14250 
14251 void
grok_special_member_properties(tree decl)14252 grok_special_member_properties (tree decl)
14253 {
14254   tree class_type;
14255 
14256   if (TREE_CODE (decl) == USING_DECL
14257       || !DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
14258     return;
14259 
14260   class_type = DECL_CONTEXT (decl);
14261   if (IDENTIFIER_CTOR_P (DECL_NAME (decl)))
14262     {
14263       int ctor = copy_fn_p (decl);
14264 
14265       if (!DECL_ARTIFICIAL (decl))
14266 	TYPE_HAS_USER_CONSTRUCTOR (class_type) = 1;
14267 
14268       if (ctor > 0)
14269 	{
14270 	  /* [class.copy]
14271 
14272 	     A non-template constructor for class X is a copy
14273 	     constructor if its first parameter is of type X&, const
14274 	     X&, volatile X& or const volatile X&, and either there
14275 	     are no other parameters or else all other parameters have
14276 	     default arguments.  */
14277 	  TYPE_HAS_COPY_CTOR (class_type) = 1;
14278 	  if (ctor > 1)
14279 	    TYPE_HAS_CONST_COPY_CTOR (class_type) = 1;
14280 	}
14281       else if (sufficient_parms_p (FUNCTION_FIRST_USER_PARMTYPE (decl)))
14282 	TYPE_HAS_DEFAULT_CONSTRUCTOR (class_type) = 1;
14283       else if (is_list_ctor (decl))
14284 	TYPE_HAS_LIST_CTOR (class_type) = 1;
14285 
14286       if (DECL_DECLARED_CONSTEXPR_P (decl)
14287 	  && !ctor && !move_fn_p (decl))
14288 	TYPE_HAS_CONSTEXPR_CTOR (class_type) = 1;
14289     }
14290   else if (DECL_NAME (decl) == assign_op_identifier)
14291     {
14292       /* [class.copy]
14293 
14294 	 A non-template assignment operator for class X is a copy
14295 	 assignment operator if its parameter is of type X, X&, const
14296 	 X&, volatile X& or const volatile X&.  */
14297 
14298       int assop = copy_fn_p (decl);
14299 
14300       if (assop)
14301 	{
14302 	  TYPE_HAS_COPY_ASSIGN (class_type) = 1;
14303 	  if (assop != 1)
14304 	    TYPE_HAS_CONST_COPY_ASSIGN (class_type) = 1;
14305 	}
14306     }
14307   else if (IDENTIFIER_CONV_OP_P (DECL_NAME (decl)))
14308     TYPE_HAS_CONVERSION (class_type) = true;
14309 
14310   /* Destructors are handled in check_methods.  */
14311 }
14312 
14313 /* Check a constructor DECL has the correct form.  Complains
14314    if the class has a constructor of the form X(X).  */
14315 
14316 bool
grok_ctor_properties(const_tree ctype,const_tree decl)14317 grok_ctor_properties (const_tree ctype, const_tree decl)
14318 {
14319   int ctor_parm = copy_fn_p (decl);
14320 
14321   if (ctor_parm < 0)
14322     {
14323       /* [class.copy]
14324 
14325 	 A declaration of a constructor for a class X is ill-formed if
14326 	 its first parameter is of type (optionally cv-qualified) X
14327 	 and either there are no other parameters or else all other
14328 	 parameters have default arguments.
14329 
14330 	 We *don't* complain about member template instantiations that
14331 	 have this form, though; they can occur as we try to decide
14332 	 what constructor to use during overload resolution.  Since
14333 	 overload resolution will never prefer such a constructor to
14334 	 the non-template copy constructor (which is either explicitly
14335 	 or implicitly defined), there's no need to worry about their
14336 	 existence.  Theoretically, they should never even be
14337 	 instantiated, but that's hard to forestall.  */
14338       error_at (DECL_SOURCE_LOCATION (decl),
14339 		"invalid constructor; you probably meant %<%T (const %T&)%>",
14340 		ctype, ctype);
14341       return false;
14342     }
14343 
14344   return true;
14345 }
14346 
14347 /* DECL is a declaration for an overloaded or conversion operator.  If
14348    COMPLAIN is true, errors are issued for invalid declarations.  */
14349 
14350 bool
grok_op_properties(tree decl,bool complain)14351 grok_op_properties (tree decl, bool complain)
14352 {
14353   tree argtypes = TYPE_ARG_TYPES (TREE_TYPE (decl));
14354   bool methodp = TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE;
14355   tree name = DECL_NAME (decl);
14356   location_t loc = DECL_SOURCE_LOCATION (decl);
14357 
14358   tree class_type = DECL_CONTEXT (decl);
14359   if (class_type && !CLASS_TYPE_P (class_type))
14360     class_type = NULL_TREE;
14361 
14362   tree_code operator_code;
14363   unsigned op_flags;
14364   if (IDENTIFIER_CONV_OP_P (name))
14365     {
14366       /* Conversion operators are TYPE_EXPR for the purposes of this
14367 	 function.  */
14368       operator_code = TYPE_EXPR;
14369       op_flags = OVL_OP_FLAG_UNARY;
14370     }
14371   else
14372     {
14373       const ovl_op_info_t *ovl_op = IDENTIFIER_OVL_OP_INFO (name);
14374 
14375       operator_code = ovl_op->tree_code;
14376       op_flags = ovl_op->flags;
14377       gcc_checking_assert (operator_code != ERROR_MARK);
14378       DECL_OVERLOADED_OPERATOR_CODE_RAW (decl) = ovl_op->ovl_op_code;
14379     }
14380 
14381   if (op_flags & OVL_OP_FLAG_ALLOC)
14382     {
14383       /* operator new and operator delete are quite special.  */
14384       if (class_type)
14385 	switch (op_flags)
14386 	  {
14387 	  case OVL_OP_FLAG_ALLOC:
14388 	    TYPE_HAS_NEW_OPERATOR (class_type) = 1;
14389 	    break;
14390 
14391 	  case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_DELETE:
14392 	    TYPE_GETS_DELETE (class_type) |= 1;
14393 	    break;
14394 
14395 	  case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_VEC:
14396 	    TYPE_HAS_ARRAY_NEW_OPERATOR (class_type) = 1;
14397 	    break;
14398 
14399 	  case OVL_OP_FLAG_ALLOC | OVL_OP_FLAG_DELETE | OVL_OP_FLAG_VEC:
14400 	    TYPE_GETS_DELETE (class_type) |= 2;
14401 	    break;
14402 
14403 	  default:
14404 	    gcc_unreachable ();
14405 	  }
14406 
14407       /* [basic.std.dynamic.allocation]/1:
14408 
14409 	 A program is ill-formed if an allocation function is declared
14410 	 in a namespace scope other than global scope or declared
14411 	 static in global scope.
14412 
14413 	 The same also holds true for deallocation functions.  */
14414       if (DECL_NAMESPACE_SCOPE_P (decl))
14415 	{
14416 	  if (CP_DECL_CONTEXT (decl) != global_namespace)
14417 	    {
14418 	      error_at (loc, "%qD may not be declared within a namespace",
14419 			decl);
14420 	      return false;
14421 	    }
14422 
14423 	  if (!TREE_PUBLIC (decl))
14424 	    {
14425 	      error_at (loc, "%qD may not be declared as static", decl);
14426 	      return false;
14427 	    }
14428 	}
14429 
14430       if (op_flags & OVL_OP_FLAG_DELETE)
14431 	{
14432 	  DECL_SET_IS_OPERATOR_DELETE (decl, true);
14433 	  coerce_delete_type (decl, loc);
14434 	}
14435       else
14436 	{
14437 	  DECL_SET_IS_OPERATOR_NEW (decl, true);
14438 	  TREE_TYPE (decl) = coerce_new_type (TREE_TYPE (decl), loc);
14439 	}
14440 
14441       return true;
14442     }
14443 
14444   /* An operator function must either be a non-static member function
14445      or have at least one parameter of a class, a reference to a class,
14446      an enumeration, or a reference to an enumeration.  13.4.0.6 */
14447   if (! methodp || DECL_STATIC_FUNCTION_P (decl))
14448     {
14449       if (operator_code == TYPE_EXPR
14450 	  || operator_code == CALL_EXPR
14451 	  || operator_code == COMPONENT_REF
14452 	  || operator_code == ARRAY_REF
14453 	  || operator_code == NOP_EXPR)
14454 	{
14455 	  error_at (loc, "%qD must be a nonstatic member function", decl);
14456 	  return false;
14457 	}
14458 
14459       if (DECL_STATIC_FUNCTION_P (decl))
14460 	{
14461 	  error_at (loc, "%qD must be either a non-static member "
14462 		    "function or a non-member function", decl);
14463 	  return false;
14464 	}
14465 
14466       for (tree arg = argtypes; ; arg = TREE_CHAIN (arg))
14467 	{
14468 	  if (!arg || arg == void_list_node)
14469 	    {
14470 	      if (complain)
14471 		error_at(loc, "%qD must have an argument of class or "
14472 			 "enumerated type", decl);
14473 	      return false;
14474 	    }
14475 
14476 	  tree type = non_reference (TREE_VALUE (arg));
14477 	  if (type == error_mark_node)
14478 	    return false;
14479 
14480 	  /* MAYBE_CLASS_TYPE_P, rather than CLASS_TYPE_P, is used
14481 	     because these checks are performed even on template
14482 	     functions.  */
14483 	  if (MAYBE_CLASS_TYPE_P (type)
14484 	      || TREE_CODE (type) == ENUMERAL_TYPE)
14485 	    break;
14486 	}
14487     }
14488 
14489   if (operator_code == CALL_EXPR)
14490     /* There are no further restrictions on the arguments to an overloaded
14491        "operator ()".  */
14492     return true;
14493 
14494   if (operator_code == COND_EXPR)
14495     {
14496       /* 13.4.0.3 */
14497       error_at (loc, "ISO C++ prohibits overloading %<operator ?:%>");
14498       return false;
14499     }
14500 
14501   /* Count the number of arguments and check for ellipsis.  */
14502   int arity = 0;
14503   for (tree arg = argtypes; arg != void_list_node; arg = TREE_CHAIN (arg))
14504     {
14505       if (!arg)
14506 	{
14507 	  /* Variadic.  */
14508 	  error_at (loc, "%qD must not have variable number of arguments",
14509 		    decl);
14510 	  return false;
14511 	}
14512       ++arity;
14513     }
14514 
14515   /* Verify correct number of arguments.  */
14516   switch (op_flags)
14517     {
14518     case OVL_OP_FLAG_AMBIARY:
14519       if (arity == 1)
14520 	{
14521 	  /* We have a unary instance of an ambi-ary op.  Remap to the
14522 	     unary one.  */
14523 	  unsigned alt = ovl_op_alternate[ovl_op_mapping [operator_code]];
14524 	  const ovl_op_info_t *ovl_op = &ovl_op_info[false][alt];
14525 	  gcc_checking_assert (ovl_op->flags == OVL_OP_FLAG_UNARY);
14526 	  operator_code = ovl_op->tree_code;
14527 	  DECL_OVERLOADED_OPERATOR_CODE_RAW (decl) = ovl_op->ovl_op_code;
14528 	}
14529       else if (arity != 2)
14530 	{
14531 	  /* This was an ambiguous operator but is invalid. */
14532 	  error_at (loc,
14533 		    methodp
14534 		    ? G_("%qD must have either zero or one argument")
14535 		    : G_("%qD must have either one or two arguments"), decl);
14536 	  return false;
14537 	}
14538       else if ((operator_code == POSTINCREMENT_EXPR
14539 		|| operator_code == POSTDECREMENT_EXPR)
14540 	       && ! processing_template_decl
14541 	       /* x++ and x--'s second argument must be an int.  */
14542 	       && ! same_type_p (TREE_VALUE (TREE_CHAIN (argtypes)),
14543 				 integer_type_node))
14544 	{
14545 	  error_at (loc,
14546 		    methodp
14547 		    ? G_("postfix %qD must have %<int%> as its argument")
14548 		    : G_("postfix %qD must have %<int%> as its second argument"),
14549 		    decl);
14550 	  return false;
14551 	}
14552       break;
14553 
14554     case OVL_OP_FLAG_UNARY:
14555       if (arity != 1)
14556 	{
14557 	  error_at (loc,
14558 		    methodp
14559 		    ? G_("%qD must have no arguments")
14560 		    : G_("%qD must have exactly one argument"), decl);
14561 	  return false;
14562 	}
14563       break;
14564 
14565     case OVL_OP_FLAG_BINARY:
14566       if (arity != 2)
14567 	{
14568 	  error_at (loc,
14569 		    methodp
14570 		    ? G_("%qD must have exactly one argument")
14571 		    : G_("%qD must have exactly two arguments"), decl);
14572 	  return false;
14573 	}
14574       break;
14575 
14576     default:
14577       gcc_unreachable ();
14578     }
14579 
14580   /* There can be no default arguments.  */
14581   for (tree arg = argtypes; arg != void_list_node; arg = TREE_CHAIN (arg))
14582     if (TREE_PURPOSE (arg))
14583       {
14584 	TREE_PURPOSE (arg) = NULL_TREE;
14585 	error_at (loc, "%qD cannot have default arguments", decl);
14586 	return false;
14587       }
14588 
14589   /* At this point the declaration is well-formed.  It may not be
14590      sensible though.  */
14591 
14592   /* Check member function warnings only on the in-class declaration.
14593      There's no point warning on an out-of-class definition.  */
14594   if (class_type && class_type != current_class_type)
14595     return true;
14596 
14597   /* Warn about conversion operators that will never be used.  */
14598   if (IDENTIFIER_CONV_OP_P (name)
14599       && ! DECL_TEMPLATE_INFO (decl)
14600       && warn_class_conversion)
14601     {
14602       tree t = TREE_TYPE (name);
14603       int ref = TYPE_REF_P (t);
14604 
14605       if (ref)
14606 	t = TYPE_MAIN_VARIANT (TREE_TYPE (t));
14607 
14608       if (VOID_TYPE_P (t))
14609 	warning_at (loc, OPT_Wclass_conversion, "converting %qT to %<void%> "
14610 		    "will never use a type conversion operator", class_type);
14611       else if (class_type)
14612 	{
14613 	  if (same_type_ignoring_top_level_qualifiers_p (t, class_type))
14614 	    warning_at (loc, OPT_Wclass_conversion,
14615 			ref
14616 			? G_("converting %qT to a reference to the same type "
14617 			     "will never use a type conversion operator")
14618 			: G_("converting %qT to the same type "
14619 			     "will never use a type conversion operator"),
14620 			class_type);
14621 	  /* Don't force t to be complete here.  */
14622 	  else if (MAYBE_CLASS_TYPE_P (t)
14623 		   && COMPLETE_TYPE_P (t)
14624 		   && DERIVED_FROM_P (t, class_type))
14625 	    warning_at (loc, OPT_Wclass_conversion,
14626 			ref
14627 			? G_("converting %qT to a reference to a base class "
14628 			     "%qT will never use a type conversion operator")
14629 			: G_("converting %qT to a base class %qT "
14630 			     "will never use a type conversion operator"),
14631 			class_type, t);
14632 	}
14633     }
14634 
14635   if (!warn_ecpp)
14636     return true;
14637 
14638   /* Effective C++ rules below.  */
14639 
14640   /* More Effective C++ rule 7.  */
14641   if (operator_code == TRUTH_ANDIF_EXPR
14642       || operator_code == TRUTH_ORIF_EXPR
14643       || operator_code == COMPOUND_EXPR)
14644     warning_at (loc, OPT_Weffc__,
14645 		"user-defined %qD always evaluates both arguments", decl);
14646 
14647   /* More Effective C++ rule 6.  */
14648   if (operator_code == POSTINCREMENT_EXPR
14649       || operator_code == POSTDECREMENT_EXPR
14650       || operator_code == PREINCREMENT_EXPR
14651       || operator_code == PREDECREMENT_EXPR)
14652     {
14653       tree arg = TREE_VALUE (argtypes);
14654       tree ret = TREE_TYPE (TREE_TYPE (decl));
14655       if (methodp || TYPE_REF_P (arg))
14656 	arg = TREE_TYPE (arg);
14657       arg = TYPE_MAIN_VARIANT (arg);
14658 
14659       if (operator_code == PREINCREMENT_EXPR
14660 	  || operator_code == PREDECREMENT_EXPR)
14661 	{
14662 	  if (!TYPE_REF_P (ret)
14663 	      || !same_type_p (TYPE_MAIN_VARIANT (TREE_TYPE (ret)), arg))
14664 	    warning_at (loc, OPT_Weffc__, "prefix %qD should return %qT", decl,
14665 			build_reference_type (arg));
14666 	}
14667       else
14668 	{
14669 	  if (!same_type_p (TYPE_MAIN_VARIANT (ret), arg))
14670 	    warning_at (loc, OPT_Weffc__,
14671 			"postfix %qD should return %qT", decl, arg);
14672 	}
14673     }
14674 
14675   /* Effective C++ rule 23.  */
14676   if (!DECL_ASSIGNMENT_OPERATOR_P (decl)
14677       && (operator_code == PLUS_EXPR
14678 	  || operator_code == MINUS_EXPR
14679 	  || operator_code == TRUNC_DIV_EXPR
14680 	  || operator_code == MULT_EXPR
14681 	  || operator_code == TRUNC_MOD_EXPR)
14682       && TYPE_REF_P (TREE_TYPE (TREE_TYPE (decl))))
14683     warning_at (loc, OPT_Weffc__, "%qD should return by value", decl);
14684 
14685   return true;
14686 }
14687 
14688 /* Return a string giving the keyword associate with CODE.  */
14689 
14690 static const char *
tag_name(enum tag_types code)14691 tag_name (enum tag_types code)
14692 {
14693   switch (code)
14694     {
14695     case record_type:
14696       return "struct";
14697     case class_type:
14698       return "class";
14699     case union_type:
14700       return "union";
14701     case enum_type:
14702       return "enum";
14703     case typename_type:
14704       return "typename";
14705     default:
14706       gcc_unreachable ();
14707     }
14708 }
14709 
14710 /* Name lookup in an elaborated-type-specifier (after the keyword
14711    indicated by TAG_CODE) has found the TYPE_DECL DECL.  If the
14712    elaborated-type-specifier is invalid, issue a diagnostic and return
14713    error_mark_node; otherwise, return the *_TYPE to which it referred.
14714    If ALLOW_TEMPLATE_P is true, TYPE may be a class template.  */
14715 
14716 tree
check_elaborated_type_specifier(enum tag_types tag_code,tree decl,bool allow_template_p)14717 check_elaborated_type_specifier (enum tag_types tag_code,
14718 				 tree decl,
14719 				 bool allow_template_p)
14720 {
14721   tree type;
14722 
14723   /* In the case of:
14724 
14725        struct S { struct S *p; };
14726 
14727      name lookup will find the TYPE_DECL for the implicit "S::S"
14728      typedef.  Adjust for that here.  */
14729   if (DECL_SELF_REFERENCE_P (decl))
14730     decl = TYPE_NAME (TREE_TYPE (decl));
14731 
14732   type = TREE_TYPE (decl);
14733 
14734   /* Check TEMPLATE_TYPE_PARM first because DECL_IMPLICIT_TYPEDEF_P
14735      is false for this case as well.  */
14736   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
14737     {
14738       error ("using template type parameter %qT after %qs",
14739 	     type, tag_name (tag_code));
14740       return error_mark_node;
14741     }
14742   /* Accept template template parameters.  */
14743   else if (allow_template_p
14744 	   && (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM
14745 	       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM))
14746     ;
14747   /*   [dcl.type.elab]
14748 
14749        If the identifier resolves to a typedef-name or the
14750        simple-template-id resolves to an alias template
14751        specialization, the elaborated-type-specifier is ill-formed.
14752 
14753      In other words, the only legitimate declaration to use in the
14754      elaborated type specifier is the implicit typedef created when
14755      the type is declared.  */
14756   else if (!DECL_IMPLICIT_TYPEDEF_P (decl)
14757 	   && !DECL_SELF_REFERENCE_P (decl)
14758 	   && tag_code != typename_type)
14759     {
14760       if (alias_template_specialization_p (type, nt_opaque))
14761 	error ("using alias template specialization %qT after %qs",
14762 	       type, tag_name (tag_code));
14763       else
14764 	error ("using typedef-name %qD after %qs", decl, tag_name (tag_code));
14765       inform (DECL_SOURCE_LOCATION (decl),
14766 	      "%qD has a previous declaration here", decl);
14767       return error_mark_node;
14768     }
14769   else if (TREE_CODE (type) != RECORD_TYPE
14770 	   && TREE_CODE (type) != UNION_TYPE
14771 	   && tag_code != enum_type
14772 	   && tag_code != typename_type)
14773     {
14774       error ("%qT referred to as %qs", type, tag_name (tag_code));
14775       inform (location_of (type), "%qT has a previous declaration here", type);
14776       return error_mark_node;
14777     }
14778   else if (TREE_CODE (type) != ENUMERAL_TYPE
14779 	   && tag_code == enum_type)
14780     {
14781       error ("%qT referred to as enum", type);
14782       inform (location_of (type), "%qT has a previous declaration here", type);
14783       return error_mark_node;
14784     }
14785   else if (!allow_template_p
14786 	   && TREE_CODE (type) == RECORD_TYPE
14787 	   && CLASSTYPE_IS_TEMPLATE (type))
14788     {
14789       /* If a class template appears as elaborated type specifier
14790 	 without a template header such as:
14791 
14792 	   template <class T> class C {};
14793 	   void f(class C);		// No template header here
14794 
14795 	 then the required template argument is missing.  */
14796       error ("template argument required for %<%s %T%>",
14797 	     tag_name (tag_code),
14798 	     DECL_NAME (CLASSTYPE_TI_TEMPLATE (type)));
14799       return error_mark_node;
14800     }
14801 
14802   return type;
14803 }
14804 
14805 /* Lookup NAME in elaborate type specifier in scope according to
14806    SCOPE and issue diagnostics if necessary.
14807    Return *_TYPE node upon success, NULL_TREE when the NAME is not
14808    found, and ERROR_MARK_NODE for type error.  */
14809 
14810 static tree
lookup_and_check_tag(enum tag_types tag_code,tree name,tag_scope scope,bool template_header_p)14811 lookup_and_check_tag (enum tag_types tag_code, tree name,
14812 		      tag_scope scope, bool template_header_p)
14813 {
14814   tree t;
14815   tree decl;
14816   if (scope == ts_global)
14817     {
14818       /* First try ordinary name lookup, ignoring hidden class name
14819 	 injected via friend declaration.  */
14820       decl = lookup_name_prefer_type (name, 2);
14821       decl = strip_using_decl (decl);
14822       /* If that fails, the name will be placed in the smallest
14823 	 non-class, non-function-prototype scope according to 3.3.1/5.
14824 	 We may already have a hidden name declared as friend in this
14825 	 scope.  So lookup again but not ignoring hidden names.
14826 	 If we find one, that name will be made visible rather than
14827 	 creating a new tag.  */
14828       if (!decl)
14829 	decl = lookup_type_scope (name, ts_within_enclosing_non_class);
14830     }
14831   else
14832     decl = lookup_type_scope (name, scope);
14833 
14834   if (decl
14835       && (DECL_CLASS_TEMPLATE_P (decl)
14836 	  /* If scope is ts_current we're defining a class, so ignore a
14837 	     template template parameter.  */
14838 	  || (scope != ts_current
14839 	      && DECL_TEMPLATE_TEMPLATE_PARM_P (decl))))
14840     decl = DECL_TEMPLATE_RESULT (decl);
14841 
14842   if (decl && TREE_CODE (decl) == TYPE_DECL)
14843     {
14844       /* Look for invalid nested type:
14845 	   class C {
14846 	     class C {};
14847 	   };  */
14848       if (scope == ts_current && DECL_SELF_REFERENCE_P (decl))
14849 	{
14850 	  error ("%qD has the same name as the class in which it is "
14851 		 "declared",
14852 		 decl);
14853 	  return error_mark_node;
14854 	}
14855 
14856       /* Two cases we need to consider when deciding if a class
14857 	 template is allowed as an elaborated type specifier:
14858 	 1. It is a self reference to its own class.
14859 	 2. It comes with a template header.
14860 
14861 	 For example:
14862 
14863 	   template <class T> class C {
14864 	     class C *c1;		// DECL_SELF_REFERENCE_P is true
14865 	     class D;
14866 	   };
14867 	   template <class U> class C; // template_header_p is true
14868 	   template <class T> class C<T>::D {
14869 	     class C *c2;		// DECL_SELF_REFERENCE_P is true
14870 	   };  */
14871 
14872       t = check_elaborated_type_specifier (tag_code,
14873 					   decl,
14874 					   template_header_p
14875 					   | DECL_SELF_REFERENCE_P (decl));
14876       if (template_header_p && t && CLASS_TYPE_P (t)
14877 	  && (!CLASSTYPE_TEMPLATE_INFO (t)
14878 	      || (!PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)))))
14879 	{
14880 	  error ("%qT is not a template", t);
14881 	  inform (location_of (t), "previous declaration here");
14882 	  if (TYPE_CLASS_SCOPE_P (t)
14883 	      && CLASSTYPE_TEMPLATE_INFO (TYPE_CONTEXT (t)))
14884 	    inform (input_location,
14885 		    "perhaps you want to explicitly add %<%T::%>",
14886 		    TYPE_CONTEXT (t));
14887 	  t = error_mark_node;
14888 	}
14889 
14890       return t;
14891     }
14892   else if (decl && TREE_CODE (decl) == TREE_LIST)
14893     {
14894       error ("reference to %qD is ambiguous", name);
14895       print_candidates (decl);
14896       return error_mark_node;
14897     }
14898   else
14899     return NULL_TREE;
14900 }
14901 
14902 /* Get the struct, enum or union (TAG_CODE says which) with tag NAME.
14903    Define the tag as a forward-reference if it is not defined.
14904 
14905    If a declaration is given, process it here, and report an error if
14906    multiple declarations are not identical.
14907 
14908    SCOPE is TS_CURRENT when this is also a definition.  Only look in
14909    the current frame for the name (since C++ allows new names in any
14910    scope.)  It is TS_WITHIN_ENCLOSING_NON_CLASS if this is a friend
14911    declaration.  Only look beginning from the current scope outward up
14912    till the nearest non-class scope.  Otherwise it is TS_GLOBAL.
14913 
14914    TEMPLATE_HEADER_P is true when this declaration is preceded by
14915    a set of template parameters.  */
14916 
14917 static tree
xref_tag_1(enum tag_types tag_code,tree name,tag_scope scope,bool template_header_p)14918 xref_tag_1 (enum tag_types tag_code, tree name,
14919             tag_scope scope, bool template_header_p)
14920 {
14921   enum tree_code code;
14922   tree context = NULL_TREE;
14923 
14924   gcc_assert (identifier_p (name));
14925 
14926   switch (tag_code)
14927     {
14928     case record_type:
14929     case class_type:
14930       code = RECORD_TYPE;
14931       break;
14932     case union_type:
14933       code = UNION_TYPE;
14934       break;
14935     case enum_type:
14936       code = ENUMERAL_TYPE;
14937       break;
14938     default:
14939       gcc_unreachable ();
14940     }
14941 
14942   /* In case of anonymous name, xref_tag is only called to
14943      make type node and push name.  Name lookup is not required.  */
14944   tree t = NULL_TREE;
14945   if (scope != ts_lambda && !IDENTIFIER_ANON_P (name))
14946     t = lookup_and_check_tag  (tag_code, name, scope, template_header_p);
14947 
14948   if (t == error_mark_node)
14949     return error_mark_node;
14950 
14951   if (scope != ts_current && t && current_class_type
14952       && template_class_depth (current_class_type)
14953       && template_header_p)
14954     {
14955       if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
14956 	return t;
14957 
14958       /* Since SCOPE is not TS_CURRENT, we are not looking at a
14959 	 definition of this tag.  Since, in addition, we are currently
14960 	 processing a (member) template declaration of a template
14961 	 class, we must be very careful; consider:
14962 
14963 	   template <class X> struct S1
14964 
14965 	   template <class U> struct S2
14966 	   {
14967 	     template <class V> friend struct S1;
14968 	   };
14969 
14970 	 Here, the S2::S1 declaration should not be confused with the
14971 	 outer declaration.  In particular, the inner version should
14972 	 have a template parameter of level 2, not level 1.
14973 
14974 	 On the other hand, when presented with:
14975 
14976 	   template <class T> struct S1
14977 	   {
14978 	     template <class U> struct S2 {};
14979 	     template <class U> friend struct S2;
14980 	   };
14981 
14982 	 the friend must find S1::S2 eventually.  We accomplish this
14983 	 by making sure that the new type we create to represent this
14984 	 declaration has the right TYPE_CONTEXT.  */
14985       context = TYPE_CONTEXT (t);
14986       t = NULL_TREE;
14987     }
14988 
14989   if (! t)
14990     {
14991       /* If no such tag is yet defined, create a forward-reference node
14992 	 and record it as the "definition".
14993 	 When a real declaration of this type is found,
14994 	 the forward-reference will be altered into a real type.  */
14995       if (code == ENUMERAL_TYPE)
14996 	{
14997 	  error ("use of enum %q#D without previous declaration", name);
14998 	  return error_mark_node;
14999 	}
15000       else
15001 	{
15002 	  t = make_class_type (code);
15003 	  TYPE_CONTEXT (t) = context;
15004 	  if (scope == ts_lambda)
15005 	    {
15006 	      /* Mark it as a lambda type.  */
15007 	      CLASSTYPE_LAMBDA_EXPR (t) = error_mark_node;
15008 	      /* And push it into current scope.  */
15009 	      scope = ts_current;
15010 	    }
15011 	  t = pushtag (name, t, scope);
15012 	}
15013     }
15014   else
15015     {
15016       if (template_header_p && MAYBE_CLASS_TYPE_P (t))
15017         {
15018           /* Check that we aren't trying to overload a class with different
15019              constraints.  */
15020           tree constr = NULL_TREE;
15021           if (current_template_parms)
15022             {
15023               tree reqs = TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
15024               constr = build_constraints (reqs, NULL_TREE);
15025             }
15026 	  if (!redeclare_class_template (t, current_template_parms, constr))
15027 	    return error_mark_node;
15028         }
15029       else if (!processing_template_decl
15030 	       && CLASS_TYPE_P (t)
15031 	       && CLASSTYPE_IS_TEMPLATE (t))
15032 	{
15033 	  error ("redeclaration of %qT as a non-template", t);
15034 	  inform (location_of (t), "previous declaration %qD", t);
15035 	  return error_mark_node;
15036 	}
15037 
15038       if (scope != ts_within_enclosing_non_class && TYPE_HIDDEN_P (t))
15039 	{
15040 	  /* This is no longer an invisible friend.  Make it
15041 	     visible.  */
15042 	  tree decl = TYPE_NAME (t);
15043 
15044 	  DECL_ANTICIPATED (decl) = false;
15045 	  DECL_FRIEND_P (decl) = false;
15046 
15047 	  if (TYPE_TEMPLATE_INFO (t))
15048 	    {
15049 	      tree tmpl = TYPE_TI_TEMPLATE (t);
15050 	      DECL_ANTICIPATED (tmpl) = false;
15051 	      DECL_FRIEND_P (tmpl) = false;
15052 	    }
15053 	}
15054     }
15055 
15056   return t;
15057 }
15058 
15059 /* Wrapper for xref_tag_1.  */
15060 
15061 tree
xref_tag(enum tag_types tag_code,tree name,tag_scope scope,bool template_header_p)15062 xref_tag (enum tag_types tag_code, tree name,
15063           tag_scope scope, bool template_header_p)
15064 {
15065   tree ret;
15066   bool subtime;
15067   subtime = timevar_cond_start (TV_NAME_LOOKUP);
15068   ret = xref_tag_1 (tag_code, name, scope, template_header_p);
15069   timevar_cond_stop (TV_NAME_LOOKUP, subtime);
15070   return ret;
15071 }
15072 
15073 
15074 tree
xref_tag_from_type(tree old,tree id,tag_scope scope)15075 xref_tag_from_type (tree old, tree id, tag_scope scope)
15076 {
15077   enum tag_types tag_kind;
15078 
15079   if (TREE_CODE (old) == RECORD_TYPE)
15080     tag_kind = (CLASSTYPE_DECLARED_CLASS (old) ? class_type : record_type);
15081   else
15082     tag_kind  = union_type;
15083 
15084   if (id == NULL_TREE)
15085     id = TYPE_IDENTIFIER (old);
15086 
15087   return xref_tag (tag_kind, id, scope, false);
15088 }
15089 
15090 /* Create the binfo hierarchy for REF with (possibly NULL) base list
15091    BASE_LIST.  For each element on BASE_LIST the TREE_PURPOSE is an
15092    access_* node, and the TREE_VALUE is the type of the base-class.
15093    Non-NULL TREE_TYPE indicates virtual inheritance.  */
15094 
15095 void
xref_basetypes(tree ref,tree base_list)15096 xref_basetypes (tree ref, tree base_list)
15097 {
15098   tree *basep;
15099   tree binfo, base_binfo;
15100   unsigned max_vbases = 0; /* Maximum direct & indirect virtual bases.  */
15101   unsigned max_bases = 0;  /* Maximum direct bases.  */
15102   unsigned max_dvbases = 0; /* Maximum direct virtual bases.  */
15103   int i;
15104   tree default_access;
15105   tree igo_prev; /* Track Inheritance Graph Order.  */
15106 
15107   if (ref == error_mark_node)
15108     return;
15109 
15110   /* The base of a derived class is private by default, all others are
15111      public.  */
15112   default_access = (TREE_CODE (ref) == RECORD_TYPE
15113 		    && CLASSTYPE_DECLARED_CLASS (ref)
15114 		    ? access_private_node : access_public_node);
15115 
15116   /* First, make sure that any templates in base-classes are
15117      instantiated.  This ensures that if we call ourselves recursively
15118      we do not get confused about which classes are marked and which
15119      are not.  */
15120   basep = &base_list;
15121   while (*basep)
15122     {
15123       tree basetype = TREE_VALUE (*basep);
15124 
15125       /* The dependent_type_p call below should really be dependent_scope_p
15126 	 so that we give a hard error about using an incomplete type as a
15127 	 base, but we allow it with a pedwarn for backward
15128 	 compatibility.  */
15129       if (processing_template_decl
15130 	  && CLASS_TYPE_P (basetype) && TYPE_BEING_DEFINED (basetype))
15131 	cxx_incomplete_type_diagnostic (NULL_TREE, basetype, DK_PEDWARN);
15132       if (!dependent_type_p (basetype)
15133 	  && !complete_type_or_else (basetype, NULL))
15134 	/* An incomplete type.  Remove it from the list.  */
15135 	*basep = TREE_CHAIN (*basep);
15136       else
15137 	{
15138 	  max_bases++;
15139 	  if (TREE_TYPE (*basep))
15140 	    max_dvbases++;
15141 	  if (CLASS_TYPE_P (basetype))
15142 	    max_vbases += vec_safe_length (CLASSTYPE_VBASECLASSES (basetype));
15143 	  basep = &TREE_CHAIN (*basep);
15144 	}
15145     }
15146   max_vbases += max_dvbases;
15147 
15148   TYPE_MARKED_P (ref) = 1;
15149 
15150   /* The binfo slot should be empty, unless this is an (ill-formed)
15151      redefinition.  */
15152   gcc_assert (!TYPE_BINFO (ref) || TYPE_SIZE (ref));
15153 
15154   gcc_assert (TYPE_MAIN_VARIANT (ref) == ref);
15155 
15156   binfo = make_tree_binfo (max_bases);
15157 
15158   TYPE_BINFO (ref) = binfo;
15159   BINFO_OFFSET (binfo) = size_zero_node;
15160   BINFO_TYPE (binfo) = ref;
15161 
15162   /* Apply base-class info set up to the variants of this type.  */
15163   fixup_type_variants (ref);
15164 
15165   if (max_bases)
15166     {
15167       vec_alloc (BINFO_BASE_ACCESSES (binfo), max_bases);
15168       /* A C++98 POD cannot have base classes.  */
15169       CLASSTYPE_NON_LAYOUT_POD_P (ref) = true;
15170 
15171       if (TREE_CODE (ref) == UNION_TYPE)
15172 	{
15173 	  error ("derived union %qT invalid", ref);
15174 	  return;
15175 	}
15176     }
15177 
15178   if (max_bases > 1)
15179     warning (OPT_Wmultiple_inheritance,
15180 	     "%qT defined with multiple direct bases", ref);
15181 
15182   if (max_vbases)
15183     {
15184       /* An aggregate can't have virtual base classes.  */
15185       CLASSTYPE_NON_AGGREGATE (ref) = true;
15186 
15187       vec_alloc (CLASSTYPE_VBASECLASSES (ref), max_vbases);
15188 
15189       if (max_dvbases)
15190 	warning (OPT_Wvirtual_inheritance,
15191 		 "%qT defined with direct virtual base", ref);
15192     }
15193 
15194   for (igo_prev = binfo; base_list; base_list = TREE_CHAIN (base_list))
15195     {
15196       tree access = TREE_PURPOSE (base_list);
15197       int via_virtual = TREE_TYPE (base_list) != NULL_TREE;
15198       tree basetype = TREE_VALUE (base_list);
15199 
15200       if (access == access_default_node)
15201 	access = default_access;
15202 
15203       /* Before C++17, an aggregate cannot have base classes.  In C++17, an
15204 	 aggregate can't have virtual, private, or protected base classes.  */
15205       if (cxx_dialect < cxx17
15206 	  || access != access_public_node
15207 	  || via_virtual)
15208 	CLASSTYPE_NON_AGGREGATE (ref) = true;
15209 
15210       if (PACK_EXPANSION_P (basetype))
15211         basetype = PACK_EXPANSION_PATTERN (basetype);
15212       if (TREE_CODE (basetype) == TYPE_DECL)
15213 	basetype = TREE_TYPE (basetype);
15214       if (!MAYBE_CLASS_TYPE_P (basetype) || TREE_CODE (basetype) == UNION_TYPE)
15215 	{
15216 	  error ("base type %qT fails to be a struct or class type",
15217 		 basetype);
15218 	  goto dropped_base;
15219 	}
15220 
15221       base_binfo = NULL_TREE;
15222       if (CLASS_TYPE_P (basetype) && !dependent_scope_p (basetype))
15223 	{
15224 	  base_binfo = TYPE_BINFO (basetype);
15225 	  /* The original basetype could have been a typedef'd type.  */
15226 	  basetype = BINFO_TYPE (base_binfo);
15227 
15228 	  /* Inherit flags from the base.  */
15229 	  TYPE_HAS_NEW_OPERATOR (ref)
15230 	    |= TYPE_HAS_NEW_OPERATOR (basetype);
15231 	  TYPE_HAS_ARRAY_NEW_OPERATOR (ref)
15232 	    |= TYPE_HAS_ARRAY_NEW_OPERATOR (basetype);
15233 	  TYPE_GETS_DELETE (ref) |= TYPE_GETS_DELETE (basetype);
15234 	  TYPE_HAS_CONVERSION (ref) |= TYPE_HAS_CONVERSION (basetype);
15235 	  CLASSTYPE_DIAMOND_SHAPED_P (ref)
15236 	    |= CLASSTYPE_DIAMOND_SHAPED_P (basetype);
15237 	  CLASSTYPE_REPEATED_BASE_P (ref)
15238 	    |= CLASSTYPE_REPEATED_BASE_P (basetype);
15239 	}
15240 
15241       /* We must do this test after we've seen through a typedef
15242 	 type.  */
15243       if (TYPE_MARKED_P (basetype))
15244 	{
15245 	  if (basetype == ref)
15246 	    error ("recursive type %qT undefined", basetype);
15247 	  else
15248 	    error ("duplicate base type %qT invalid", basetype);
15249 	  goto dropped_base;
15250 	}
15251 
15252       if (PACK_EXPANSION_P (TREE_VALUE (base_list)))
15253         /* Regenerate the pack expansion for the bases. */
15254         basetype = make_pack_expansion (basetype);
15255 
15256       TYPE_MARKED_P (basetype) = 1;
15257 
15258       base_binfo = copy_binfo (base_binfo, basetype, ref,
15259 			       &igo_prev, via_virtual);
15260       if (!BINFO_INHERITANCE_CHAIN (base_binfo))
15261 	BINFO_INHERITANCE_CHAIN (base_binfo) = binfo;
15262 
15263       BINFO_BASE_APPEND (binfo, base_binfo);
15264       BINFO_BASE_ACCESS_APPEND (binfo, access);
15265       continue;
15266 
15267     dropped_base:
15268       /* Update max_vbases to reflect the reality that we are dropping
15269 	 this base:  if it reaches zero we want to undo the vec_alloc
15270 	 above to avoid inconsistencies during error-recovery: eg, in
15271 	 build_special_member_call, CLASSTYPE_VBASECLASSES non null
15272 	 and vtt null (c++/27952).  */
15273       if (via_virtual)
15274 	max_vbases--;
15275       if (CLASS_TYPE_P (basetype))
15276 	max_vbases
15277 	  -= vec_safe_length (CLASSTYPE_VBASECLASSES (basetype));
15278     }
15279 
15280   if (CLASSTYPE_VBASECLASSES (ref)
15281       && max_vbases == 0)
15282     vec_free (CLASSTYPE_VBASECLASSES (ref));
15283 
15284   if (vec_safe_length (CLASSTYPE_VBASECLASSES (ref)) < max_vbases)
15285     /* If we didn't get max_vbases vbases, we must have shared at
15286        least one of them, and are therefore diamond shaped.  */
15287     CLASSTYPE_DIAMOND_SHAPED_P (ref) = 1;
15288 
15289   /* Unmark all the types.  */
15290   for (i = 0; BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
15291     TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 0;
15292   TYPE_MARKED_P (ref) = 0;
15293 
15294   /* Now see if we have a repeated base type.  */
15295   if (!CLASSTYPE_REPEATED_BASE_P (ref))
15296     {
15297       for (base_binfo = binfo; base_binfo;
15298 	   base_binfo = TREE_CHAIN (base_binfo))
15299 	{
15300 	  if (TYPE_MARKED_P (BINFO_TYPE (base_binfo)))
15301 	    {
15302 	      CLASSTYPE_REPEATED_BASE_P (ref) = 1;
15303 	      break;
15304 	    }
15305 	  TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 1;
15306 	}
15307       for (base_binfo = binfo; base_binfo;
15308 	   base_binfo = TREE_CHAIN (base_binfo))
15309 	if (TYPE_MARKED_P (BINFO_TYPE (base_binfo)))
15310 	  TYPE_MARKED_P (BINFO_TYPE (base_binfo)) = 0;
15311 	else
15312 	  break;
15313     }
15314 }
15315 
15316 
15317 /* Copies the enum-related properties from type SRC to type DST.
15318    Used with the underlying type of an enum and the enum itself.  */
15319 static void
copy_type_enum(tree dst,tree src)15320 copy_type_enum (tree dst, tree src)
15321 {
15322   tree t;
15323   for (t = dst; t; t = TYPE_NEXT_VARIANT (t))
15324     {
15325       TYPE_MIN_VALUE (t) = TYPE_MIN_VALUE (src);
15326       TYPE_MAX_VALUE (t) = TYPE_MAX_VALUE (src);
15327       TYPE_SIZE (t) = TYPE_SIZE (src);
15328       TYPE_SIZE_UNIT (t) = TYPE_SIZE_UNIT (src);
15329       SET_TYPE_MODE (dst, TYPE_MODE (src));
15330       TYPE_PRECISION (t) = TYPE_PRECISION (src);
15331       unsigned valign = TYPE_ALIGN (src);
15332       if (TYPE_USER_ALIGN (t))
15333 	valign = MAX (valign, TYPE_ALIGN (t));
15334       else
15335 	TYPE_USER_ALIGN (t) = TYPE_USER_ALIGN (src);
15336       SET_TYPE_ALIGN (t, valign);
15337       TYPE_UNSIGNED (t) = TYPE_UNSIGNED (src);
15338     }
15339 }
15340 
15341 /* Begin compiling the definition of an enumeration type.
15342    NAME is its name,
15343 
15344    if ENUMTYPE is not NULL_TREE then the type has alredy been found.
15345 
15346    UNDERLYING_TYPE is the type that will be used as the storage for
15347    the enumeration type. This should be NULL_TREE if no storage type
15348    was specified.
15349 
15350    ATTRIBUTES are any attributes specified after the enum-key.
15351 
15352    SCOPED_ENUM_P is true if this is a scoped enumeration type.
15353 
15354    if IS_NEW is not NULL, gets TRUE iff a new type is created.
15355 
15356    Returns the type object, as yet incomplete.
15357    Also records info about it so that build_enumerator
15358    may be used to declare the individual values as they are read.  */
15359 
15360 tree
start_enum(tree name,tree enumtype,tree underlying_type,tree attributes,bool scoped_enum_p,bool * is_new)15361 start_enum (tree name, tree enumtype, tree underlying_type,
15362 	    tree attributes, bool scoped_enum_p, bool *is_new)
15363 {
15364   tree prevtype = NULL_TREE;
15365   gcc_assert (identifier_p (name));
15366 
15367   if (is_new)
15368     *is_new = false;
15369   /* [C++0x dcl.enum]p5:
15370 
15371     If not explicitly specified, the underlying type of a scoped
15372     enumeration type is int.  */
15373   if (!underlying_type && scoped_enum_p)
15374     underlying_type = integer_type_node;
15375 
15376   if (underlying_type)
15377     underlying_type = cv_unqualified (underlying_type);
15378 
15379   /* If this is the real definition for a previous forward reference,
15380      fill in the contents in the same object that used to be the
15381      forward reference.  */
15382   if (!enumtype)
15383     enumtype = lookup_and_check_tag (enum_type, name,
15384 				     /*tag_scope=*/ts_current,
15385 				     /*template_header_p=*/false);
15386 
15387   /* In case of a template_decl, the only check that should be deferred
15388      to instantiation time is the comparison of underlying types.  */
15389   if (enumtype && TREE_CODE (enumtype) == ENUMERAL_TYPE)
15390     {
15391       if (scoped_enum_p != SCOPED_ENUM_P (enumtype))
15392 	{
15393 	  error_at (input_location, "scoped/unscoped mismatch "
15394 		    "in enum %q#T", enumtype);
15395 	  inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
15396 		  "previous definition here");
15397 	  enumtype = error_mark_node;
15398 	}
15399       else if (ENUM_FIXED_UNDERLYING_TYPE_P (enumtype) != !! underlying_type)
15400 	{
15401 	  error_at (input_location, "underlying type mismatch "
15402 		    "in enum %q#T", enumtype);
15403 	  inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
15404 		  "previous definition here");
15405 	  enumtype = error_mark_node;
15406 	}
15407       else if (underlying_type && ENUM_UNDERLYING_TYPE (enumtype)
15408 	       && !same_type_p (underlying_type,
15409 				ENUM_UNDERLYING_TYPE (enumtype)))
15410 	{
15411 	  error_at (input_location, "different underlying type "
15412 		    "in enum %q#T", enumtype);
15413 	  inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
15414 		  "previous definition here");
15415 	  underlying_type = NULL_TREE;
15416 	}
15417     }
15418 
15419   if (!enumtype || TREE_CODE (enumtype) != ENUMERAL_TYPE
15420       || processing_template_decl)
15421     {
15422       /* In case of error, make a dummy enum to allow parsing to
15423 	 continue.  */
15424       if (enumtype == error_mark_node)
15425 	{
15426 	  name = make_anon_name ();
15427 	  enumtype = NULL_TREE;
15428 	}
15429 
15430       /* enumtype may be an ENUMERAL_TYPE if this is a redefinition
15431          of an opaque enum, or an opaque enum of an already defined
15432 	 enumeration (C++11).
15433 	 In any other case, it'll be NULL_TREE. */
15434       if (!enumtype)
15435 	{
15436 	  if (is_new)
15437 	    *is_new = true;
15438 	}
15439       prevtype = enumtype;
15440 
15441       /* Do not push the decl more than once.  */
15442       if (!enumtype
15443 	  || TREE_CODE (enumtype) != ENUMERAL_TYPE)
15444 	{
15445 	  enumtype = cxx_make_type (ENUMERAL_TYPE);
15446 	  enumtype = pushtag (name, enumtype, /*tag_scope=*/ts_current);
15447 
15448 	  /* std::byte aliases anything.  */
15449 	  if (enumtype != error_mark_node
15450 	      && TYPE_CONTEXT (enumtype) == std_node
15451 	      && !strcmp ("byte", TYPE_NAME_STRING (enumtype)))
15452 	    TYPE_ALIAS_SET (enumtype) = 0;
15453 	}
15454       else
15455 	  enumtype = xref_tag (enum_type, name, /*tag_scope=*/ts_current,
15456 			       false);
15457 
15458       if (enumtype == error_mark_node)
15459 	return error_mark_node;
15460 
15461       /* The enum is considered opaque until the opening '{' of the
15462 	 enumerator list.  */
15463       SET_OPAQUE_ENUM_P (enumtype, true);
15464       ENUM_FIXED_UNDERLYING_TYPE_P (enumtype) = !! underlying_type;
15465     }
15466 
15467   SET_SCOPED_ENUM_P (enumtype, scoped_enum_p);
15468 
15469   cplus_decl_attributes (&enumtype, attributes, (int)ATTR_FLAG_TYPE_IN_PLACE);
15470 
15471   if (underlying_type)
15472     {
15473       if (ENUM_UNDERLYING_TYPE (enumtype))
15474 	/* We already checked that it matches, don't change it to a different
15475 	   typedef variant.  */;
15476       else if (CP_INTEGRAL_TYPE_P (underlying_type))
15477         {
15478 	  copy_type_enum (enumtype, underlying_type);
15479           ENUM_UNDERLYING_TYPE (enumtype) = underlying_type;
15480         }
15481       else if (dependent_type_p (underlying_type))
15482 	ENUM_UNDERLYING_TYPE (enumtype) = underlying_type;
15483       else
15484         error ("underlying type %qT of %qT must be an integral type",
15485                underlying_type, enumtype);
15486     }
15487 
15488   /* If into a template class, the returned enum is always the first
15489      declaration (opaque or not) seen. This way all the references to
15490      this type will be to the same declaration. The following ones are used
15491      only to check for definition errors.  */
15492   if (prevtype && processing_template_decl)
15493     return prevtype;
15494   else
15495     return enumtype;
15496 }
15497 
15498 /* After processing and defining all the values of an enumeration type,
15499    install their decls in the enumeration type.
15500    ENUMTYPE is the type object.  */
15501 
15502 void
finish_enum_value_list(tree enumtype)15503 finish_enum_value_list (tree enumtype)
15504 {
15505   tree values;
15506   tree underlying_type;
15507   tree decl;
15508   tree value;
15509   tree minnode, maxnode;
15510   tree t;
15511 
15512   bool fixed_underlying_type_p
15513     = ENUM_UNDERLYING_TYPE (enumtype) != NULL_TREE;
15514 
15515   /* We built up the VALUES in reverse order.  */
15516   TYPE_VALUES (enumtype) = nreverse (TYPE_VALUES (enumtype));
15517 
15518   /* For an enum defined in a template, just set the type of the values;
15519      all further processing is postponed until the template is
15520      instantiated.  We need to set the type so that tsubst of a CONST_DECL
15521      works.  */
15522   if (processing_template_decl)
15523     {
15524       for (values = TYPE_VALUES (enumtype);
15525 	   values;
15526 	   values = TREE_CHAIN (values))
15527 	TREE_TYPE (TREE_VALUE (values)) = enumtype;
15528       return;
15529     }
15530 
15531   /* Determine the minimum and maximum values of the enumerators.  */
15532   if (TYPE_VALUES (enumtype))
15533     {
15534       minnode = maxnode = NULL_TREE;
15535 
15536       for (values = TYPE_VALUES (enumtype);
15537 	   values;
15538 	   values = TREE_CHAIN (values))
15539 	{
15540 	  decl = TREE_VALUE (values);
15541 
15542 	  /* [dcl.enum]: Following the closing brace of an enum-specifier,
15543 	     each enumerator has the type of its enumeration.  Prior to the
15544 	     closing brace, the type of each enumerator is the type of its
15545 	     initializing value.  */
15546 	  TREE_TYPE (decl) = enumtype;
15547 
15548 	  /* Update the minimum and maximum values, if appropriate.  */
15549 	  value = DECL_INITIAL (decl);
15550 	  if (value == error_mark_node)
15551 	    value = integer_zero_node;
15552 	  /* Figure out what the minimum and maximum values of the
15553 	     enumerators are.  */
15554 	  if (!minnode)
15555 	    minnode = maxnode = value;
15556 	  else if (tree_int_cst_lt (maxnode, value))
15557 	    maxnode = value;
15558 	  else if (tree_int_cst_lt (value, minnode))
15559 	    minnode = value;
15560 	}
15561     }
15562   else
15563     /* [dcl.enum]
15564 
15565        If the enumerator-list is empty, the underlying type is as if
15566        the enumeration had a single enumerator with value 0.  */
15567     minnode = maxnode = integer_zero_node;
15568 
15569   if (!fixed_underlying_type_p)
15570     {
15571       /* Compute the number of bits require to represent all values of the
15572 	 enumeration.  We must do this before the type of MINNODE and
15573 	 MAXNODE are transformed, since tree_int_cst_min_precision relies
15574 	 on the TREE_TYPE of the value it is passed.  */
15575       signop sgn = tree_int_cst_sgn (minnode) >= 0 ? UNSIGNED : SIGNED;
15576       int lowprec = tree_int_cst_min_precision (minnode, sgn);
15577       int highprec = tree_int_cst_min_precision (maxnode, sgn);
15578       int precision = MAX (lowprec, highprec);
15579       unsigned int itk;
15580       bool use_short_enum;
15581 
15582       /* Determine the underlying type of the enumeration.
15583 
15584          [dcl.enum]
15585 
15586          The underlying type of an enumeration is an integral type that
15587          can represent all the enumerator values defined in the
15588          enumeration.  It is implementation-defined which integral type is
15589          used as the underlying type for an enumeration except that the
15590          underlying type shall not be larger than int unless the value of
15591          an enumerator cannot fit in an int or unsigned int.
15592 
15593          We use "int" or an "unsigned int" as the underlying type, even if
15594          a smaller integral type would work, unless the user has
15595          explicitly requested that we use the smallest possible type.  The
15596          user can request that for all enumerations with a command line
15597          flag, or for just one enumeration with an attribute.  */
15598 
15599       use_short_enum = flag_short_enums
15600         || lookup_attribute ("packed", TYPE_ATTRIBUTES (enumtype));
15601 
15602       /* If the precision of the type was specified with an attribute and it
15603 	 was too small, give an error.  Otherwise, use it.  */
15604       if (TYPE_PRECISION (enumtype))
15605 	{
15606 	  if (precision > TYPE_PRECISION (enumtype))
15607 	    error ("specified mode too small for enumerated values");
15608 	  else
15609 	    {
15610 	      use_short_enum = true;
15611 	      precision = TYPE_PRECISION (enumtype);
15612 	    }
15613 	}
15614 
15615       for (itk = (use_short_enum ? itk_char : itk_int);
15616            itk != itk_none;
15617            itk++)
15618         {
15619           underlying_type = integer_types[itk];
15620           if (underlying_type != NULL_TREE
15621 	      && TYPE_PRECISION (underlying_type) >= precision
15622               && TYPE_SIGN (underlying_type) == sgn)
15623             break;
15624         }
15625       if (itk == itk_none)
15626         {
15627           /* DR 377
15628 
15629              IF no integral type can represent all the enumerator values, the
15630              enumeration is ill-formed.  */
15631           error ("no integral type can represent all of the enumerator values "
15632                  "for %qT", enumtype);
15633           precision = TYPE_PRECISION (long_long_integer_type_node);
15634           underlying_type = integer_types[itk_unsigned_long_long];
15635         }
15636 
15637       /* [dcl.enum]
15638 
15639          The value of sizeof() applied to an enumeration type, an object
15640          of an enumeration type, or an enumerator, is the value of sizeof()
15641          applied to the underlying type.  */
15642       copy_type_enum (enumtype, underlying_type);
15643 
15644       /* Compute the minimum and maximum values for the type.
15645 
15646 	 [dcl.enum]
15647 
15648 	 For an enumeration where emin is the smallest enumerator and emax
15649 	 is the largest, the values of the enumeration are the values of the
15650 	 underlying type in the range bmin to bmax, where bmin and bmax are,
15651 	 respectively, the smallest and largest values of the smallest bit-
15652 	 field that can store emin and emax.  */
15653 
15654       /* The middle-end currently assumes that types with TYPE_PRECISION
15655 	 narrower than their underlying type are suitably zero or sign
15656 	 extended to fill their mode.  Similarly, it assumes that the front
15657 	 end assures that a value of a particular type must be within
15658 	 TYPE_MIN_VALUE and TYPE_MAX_VALUE.
15659 
15660 	 We used to set these fields based on bmin and bmax, but that led
15661 	 to invalid assumptions like optimizing away bounds checking.  So
15662 	 now we just set the TYPE_PRECISION, TYPE_MIN_VALUE, and
15663 	 TYPE_MAX_VALUE to the values for the mode above and only restrict
15664 	 the ENUM_UNDERLYING_TYPE for the benefit of diagnostics.  */
15665       ENUM_UNDERLYING_TYPE (enumtype)
15666 	= build_distinct_type_copy (underlying_type);
15667       TYPE_PRECISION (ENUM_UNDERLYING_TYPE (enumtype)) = precision;
15668       set_min_and_max_values_for_integral_type
15669         (ENUM_UNDERLYING_TYPE (enumtype), precision, sgn);
15670 
15671       /* If -fstrict-enums, still constrain TYPE_MIN/MAX_VALUE.  */
15672       if (flag_strict_enums)
15673 	set_min_and_max_values_for_integral_type (enumtype, precision, sgn);
15674     }
15675   else
15676     underlying_type = ENUM_UNDERLYING_TYPE (enumtype);
15677 
15678   /* Convert each of the enumerators to the type of the underlying
15679      type of the enumeration.  */
15680   for (values = TYPE_VALUES (enumtype); values; values = TREE_CHAIN (values))
15681     {
15682       decl = TREE_VALUE (values);
15683       iloc_sentinel ils (DECL_SOURCE_LOCATION (decl));
15684       if (fixed_underlying_type_p)
15685         /* If the enumeration type has a fixed underlying type, we
15686            already checked all of the enumerator values.  */
15687         value = DECL_INITIAL (decl);
15688       else
15689         value = perform_implicit_conversion (underlying_type,
15690                                              DECL_INITIAL (decl),
15691                                              tf_warning_or_error);
15692       /* Do not clobber shared ints.  */
15693       if (value != error_mark_node)
15694 	{
15695 	  value = copy_node (value);
15696 
15697 	  TREE_TYPE (value) = enumtype;
15698 	}
15699       DECL_INITIAL (decl) = value;
15700     }
15701 
15702   /* Fix up all variant types of this enum type.  */
15703   for (t = TYPE_MAIN_VARIANT (enumtype); t; t = TYPE_NEXT_VARIANT (t))
15704     TYPE_VALUES (t) = TYPE_VALUES (enumtype);
15705 
15706   if (at_class_scope_p ()
15707       && COMPLETE_TYPE_P (current_class_type)
15708       && UNSCOPED_ENUM_P (enumtype))
15709     {
15710       insert_late_enum_def_bindings (current_class_type, enumtype);
15711       /* TYPE_FIELDS needs fixup.  */
15712       fixup_type_variants (current_class_type);
15713     }
15714 
15715   /* Finish debugging output for this type.  */
15716   rest_of_type_compilation (enumtype, namespace_bindings_p ());
15717 
15718   /* Each enumerator now has the type of its enumeration.  Clear the cache
15719      so that this change in types doesn't confuse us later on.  */
15720   clear_cv_and_fold_caches ();
15721 }
15722 
15723 /* Finishes the enum type. This is called only the first time an
15724    enumeration is seen, be it opaque or odinary.
15725    ENUMTYPE is the type object.  */
15726 
15727 void
finish_enum(tree enumtype)15728 finish_enum (tree enumtype)
15729 {
15730   if (processing_template_decl)
15731     {
15732       if (at_function_scope_p ())
15733 	add_stmt (build_min (TAG_DEFN, enumtype));
15734       return;
15735     }
15736 
15737   /* If this is a forward declaration, there should not be any variants,
15738      though we can get a variant in the middle of an enum-specifier with
15739      wacky code like 'enum E { e = sizeof(const E*) };'  */
15740   gcc_assert (enumtype == TYPE_MAIN_VARIANT (enumtype)
15741 	      && (TYPE_VALUES (enumtype)
15742 		  || !TYPE_NEXT_VARIANT (enumtype)));
15743 }
15744 
15745 /* Build and install a CONST_DECL for an enumeration constant of the
15746    enumeration type ENUMTYPE whose NAME and VALUE (if any) are provided.
15747    Apply ATTRIBUTES if available.  LOC is the location of NAME.
15748    Assignment of sequential values by default is handled here.  */
15749 
15750 void
build_enumerator(tree name,tree value,tree enumtype,tree attributes,location_t loc)15751 build_enumerator (tree name, tree value, tree enumtype, tree attributes,
15752 		  location_t loc)
15753 {
15754   tree decl;
15755   tree context;
15756   tree type;
15757 
15758   /* scalar_constant_value will pull out this expression, so make sure
15759      it's folded as appropriate.  */
15760   if (processing_template_decl)
15761     value = fold_non_dependent_expr (value);
15762 
15763   /* If the VALUE was erroneous, pretend it wasn't there; that will
15764      result in the enum being assigned the next value in sequence.  */
15765   if (value == error_mark_node)
15766     value = NULL_TREE;
15767 
15768   /* Remove no-op casts from the value.  */
15769   if (value)
15770     STRIP_TYPE_NOPS (value);
15771 
15772   if (! processing_template_decl)
15773     {
15774       /* Validate and default VALUE.  */
15775       if (value != NULL_TREE)
15776 	{
15777 	  if (!ENUM_UNDERLYING_TYPE (enumtype))
15778 	    {
15779 	      tree tmp_value = build_expr_type_conversion (WANT_INT | WANT_ENUM,
15780 							   value, true);
15781 	      if (tmp_value)
15782 		value = tmp_value;
15783 	    }
15784 	  else if (! INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P
15785 		   (TREE_TYPE (value)))
15786 	    value = perform_implicit_conversion_flags
15787 	      (ENUM_UNDERLYING_TYPE (enumtype), value, tf_warning_or_error,
15788 	       LOOKUP_IMPLICIT | LOOKUP_NO_NARROWING);
15789 
15790 	  if (value == error_mark_node)
15791 	    value = NULL_TREE;
15792 
15793 	  if (value != NULL_TREE)
15794 	    {
15795 	      if (! INTEGRAL_OR_UNSCOPED_ENUMERATION_TYPE_P
15796 		  (TREE_TYPE (value)))
15797 		{
15798 		  error_at (cp_expr_loc_or_input_loc (value),
15799 			    "enumerator value for %qD must have integral or "
15800 			    "unscoped enumeration type", name);
15801 		  value = NULL_TREE;
15802 		}
15803 	      else
15804 		{
15805 		  value = cxx_constant_value (value);
15806 
15807 		  if (TREE_CODE (value) != INTEGER_CST)
15808 		    {
15809 		      error ("enumerator value for %qD is not an integer "
15810 			     "constant", name);
15811 		      value = NULL_TREE;
15812 		    }
15813 		}
15814 	    }
15815 	}
15816 
15817       /* Default based on previous value.  */
15818       if (value == NULL_TREE)
15819 	{
15820 	  if (TYPE_VALUES (enumtype))
15821 	    {
15822 	      tree prev_value;
15823 
15824 	      /* C++03 7.2/4: If no initializer is specified for the first
15825 		 enumerator, the type is an unspecified integral
15826 		 type. Otherwise the type is the same as the type of the
15827 		 initializing value of the preceding enumerator unless the
15828 		 incremented value is not representable in that type, in
15829 		 which case the type is an unspecified integral type
15830 		 sufficient to contain the incremented value.  */
15831 	      prev_value = DECL_INITIAL (TREE_VALUE (TYPE_VALUES (enumtype)));
15832 	      if (error_operand_p (prev_value))
15833 		value = error_mark_node;
15834 	      else
15835 		{
15836 		  wi::overflow_type overflowed;
15837 		  tree type = TREE_TYPE (prev_value);
15838 		  signop sgn = TYPE_SIGN (type);
15839 		  widest_int wi = wi::add (wi::to_widest (prev_value), 1, sgn,
15840 					   &overflowed);
15841 		  if (!overflowed)
15842 		    {
15843 		      bool pos = !wi::neg_p (wi, sgn);
15844 		      if (!wi::fits_to_tree_p (wi, type))
15845 			{
15846 			  unsigned int itk;
15847 			  for (itk = itk_int; itk != itk_none; itk++)
15848 			    {
15849 			      type = integer_types[itk];
15850 			      if (type != NULL_TREE
15851 				  && (pos || !TYPE_UNSIGNED (type))
15852 				  && wi::fits_to_tree_p (wi, type))
15853 				break;
15854 			    }
15855 			  if (type && cxx_dialect < cxx11
15856 			      && itk > itk_unsigned_long)
15857 			    pedwarn (input_location, OPT_Wlong_long,
15858 				     pos ? G_("\
15859 incremented enumerator value is too large for %<unsigned long%>") : G_("\
15860 incremented enumerator value is too large for %<long%>"));
15861 			}
15862 		      if (type == NULL_TREE)
15863 		        overflowed = wi::OVF_UNKNOWN;
15864 		      else
15865 			value = wide_int_to_tree (type, wi);
15866 		    }
15867 
15868 		  if (overflowed)
15869 		    {
15870 		      error ("overflow in enumeration values at %qD", name);
15871 		      value = error_mark_node;
15872 		    }
15873 		}
15874 	    }
15875 	  else
15876 	    value = integer_zero_node;
15877 	}
15878 
15879       /* Remove no-op casts from the value.  */
15880       STRIP_TYPE_NOPS (value);
15881 
15882       /* If the underlying type of the enum is fixed, check whether
15883          the enumerator values fits in the underlying type.  If it
15884          does not fit, the program is ill-formed [C++0x dcl.enum].  */
15885       if (ENUM_UNDERLYING_TYPE (enumtype)
15886           && value
15887           && TREE_CODE (value) == INTEGER_CST)
15888         {
15889 	  if (!int_fits_type_p (value, ENUM_UNDERLYING_TYPE (enumtype)))
15890 	    error ("enumerator value %qE is outside the range of underlying "
15891 		   "type %qT", value, ENUM_UNDERLYING_TYPE (enumtype));
15892 
15893           /* Convert the value to the appropriate type.  */
15894           value = fold_convert (ENUM_UNDERLYING_TYPE (enumtype), value);
15895         }
15896     }
15897 
15898   /* C++ associates enums with global, function, or class declarations.  */
15899   context = current_scope ();
15900 
15901   /* Build the actual enumeration constant.  Note that the enumeration
15902      constants have the underlying type of the enum (if it is fixed)
15903      or the type of their initializer (if the underlying type of the
15904      enum is not fixed):
15905 
15906       [ C++0x dcl.enum ]
15907 
15908         If the underlying type is fixed, the type of each enumerator
15909         prior to the closing brace is the underlying type; if the
15910         initializing value of an enumerator cannot be represented by
15911         the underlying type, the program is ill-formed. If the
15912         underlying type is not fixed, the type of each enumerator is
15913         the type of its initializing value.
15914 
15915     If the underlying type is not fixed, it will be computed by
15916     finish_enum and we will reset the type of this enumerator.  Of
15917     course, if we're processing a template, there may be no value.  */
15918   type = value ? TREE_TYPE (value) : NULL_TREE;
15919 
15920   decl = build_decl (loc, CONST_DECL, name, type);
15921 
15922   DECL_CONTEXT (decl) = enumtype;
15923   TREE_CONSTANT (decl) = 1;
15924   TREE_READONLY (decl) = 1;
15925   DECL_INITIAL (decl) = value;
15926 
15927   if (attributes)
15928     cplus_decl_attributes (&decl, attributes, 0);
15929 
15930   if (context && context == current_class_type && !SCOPED_ENUM_P (enumtype))
15931     {
15932       /* In something like `struct S { enum E { i = 7 }; };' we put `i'
15933 	 on the TYPE_FIELDS list for `S'.  (That's so that you can say
15934 	 things like `S::i' later.)  */
15935 
15936       /* The enumerator may be getting declared outside of its enclosing
15937 	 class, like so:
15938 
15939 	   class S { public: enum E : int; }; enum S::E : int { i = 7; };
15940 
15941 	 For which case we need to make sure that the access of `S::i'
15942 	 matches the access of `S::E'.  */
15943       tree saved_cas = current_access_specifier;
15944       if (TREE_PRIVATE (TYPE_NAME (enumtype)))
15945 	current_access_specifier = access_private_node;
15946       else if (TREE_PROTECTED (TYPE_NAME (enumtype)))
15947 	current_access_specifier = access_protected_node;
15948       else
15949 	current_access_specifier = access_public_node;
15950 
15951       finish_member_declaration (decl);
15952 
15953       current_access_specifier = saved_cas;
15954     }
15955   else
15956     pushdecl (decl);
15957 
15958   /* Add this enumeration constant to the list for this type.  */
15959   TYPE_VALUES (enumtype) = tree_cons (name, decl, TYPE_VALUES (enumtype));
15960 }
15961 
15962 /* Look for an enumerator with the given NAME within the enumeration
15963    type ENUMTYPE.  This routine is used primarily for qualified name
15964    lookup into an enumerator in C++0x, e.g.,
15965 
15966      enum class Color { Red, Green, Blue };
15967 
15968      Color color = Color::Red;
15969 
15970    Returns the value corresponding to the enumerator, or
15971    NULL_TREE if no such enumerator was found.  */
15972 tree
lookup_enumerator(tree enumtype,tree name)15973 lookup_enumerator (tree enumtype, tree name)
15974 {
15975   tree e;
15976   gcc_assert (enumtype && TREE_CODE (enumtype) == ENUMERAL_TYPE);
15977 
15978   e = purpose_member (name, TYPE_VALUES (enumtype));
15979   return e? TREE_VALUE (e) : NULL_TREE;
15980 }
15981 
15982 /* Implement LANG_HOOKS_SIMULATE_ENUM_DECL.  */
15983 
15984 tree
cxx_simulate_enum_decl(location_t loc,const char * name,vec<string_int_pair> values)15985 cxx_simulate_enum_decl (location_t loc, const char *name,
15986 			vec<string_int_pair> values)
15987 {
15988   location_t saved_loc = input_location;
15989   input_location = loc;
15990 
15991   tree enumtype = start_enum (get_identifier (name), NULL_TREE, NULL_TREE,
15992 			      NULL_TREE, false, NULL);
15993   if (!OPAQUE_ENUM_P (enumtype))
15994     {
15995       error_at (loc, "multiple definition of %q#T", enumtype);
15996       inform (DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (enumtype)),
15997 	      "previous definition here");
15998       return enumtype;
15999     }
16000   SET_OPAQUE_ENUM_P (enumtype, false);
16001   DECL_SOURCE_LOCATION (TYPE_NAME (enumtype)) = loc;
16002 
16003   string_int_pair *value;
16004   unsigned int i;
16005   FOR_EACH_VEC_ELT (values, i, value)
16006     build_enumerator (get_identifier (value->first),
16007 		      build_int_cst (integer_type_node, value->second),
16008 		      enumtype, NULL_TREE, loc);
16009 
16010   finish_enum_value_list (enumtype);
16011   finish_enum (enumtype);
16012 
16013   input_location = saved_loc;
16014   return enumtype;
16015 }
16016 
16017 /* We're defining DECL.  Make sure that its type is OK.  */
16018 
16019 static void
check_function_type(tree decl,tree current_function_parms)16020 check_function_type (tree decl, tree current_function_parms)
16021 {
16022   tree fntype = TREE_TYPE (decl);
16023   tree return_type = complete_type (TREE_TYPE (fntype));
16024 
16025   /* In a function definition, arg types must be complete.  */
16026   require_complete_types_for_parms (current_function_parms);
16027 
16028   if (dependent_type_p (return_type)
16029       || type_uses_auto (return_type))
16030     return;
16031   if (!COMPLETE_OR_VOID_TYPE_P (return_type))
16032     {
16033       tree args = TYPE_ARG_TYPES (fntype);
16034 
16035       error ("return type %q#T is incomplete", return_type);
16036 
16037       /* Make it return void instead.  */
16038       if (TREE_CODE (fntype) == METHOD_TYPE)
16039 	fntype = build_method_type_directly (TREE_TYPE (TREE_VALUE (args)),
16040 					     void_type_node,
16041 					     TREE_CHAIN (args));
16042       else
16043 	fntype = build_function_type (void_type_node, args);
16044       fntype = (cp_build_type_attribute_variant
16045 		(fntype, TYPE_ATTRIBUTES (TREE_TYPE (decl))));
16046       fntype = cxx_copy_lang_qualifiers (fntype, TREE_TYPE (decl));
16047       TREE_TYPE (decl) = fntype;
16048     }
16049   else
16050     {
16051       abstract_virtuals_error (decl, TREE_TYPE (fntype));
16052       maybe_warn_parm_abi (TREE_TYPE (fntype),
16053 			   DECL_SOURCE_LOCATION (decl));
16054     }
16055 }
16056 
16057 /* True iff FN is an implicitly-defined default constructor.  */
16058 
16059 static bool
implicit_default_ctor_p(tree fn)16060 implicit_default_ctor_p (tree fn)
16061 {
16062   return (DECL_CONSTRUCTOR_P (fn)
16063 	  && !user_provided_p (fn)
16064 	  && sufficient_parms_p (FUNCTION_FIRST_USER_PARMTYPE (fn)));
16065 }
16066 
16067 /* Clobber the contents of *this to let the back end know that the object
16068    storage is dead when we enter the constructor or leave the destructor.  */
16069 
16070 static tree
build_clobber_this()16071 build_clobber_this ()
16072 {
16073   /* Clobbering an empty base is pointless, and harmful if its one byte
16074      TYPE_SIZE overlays real data.  */
16075   if (is_empty_class (current_class_type))
16076     return void_node;
16077 
16078   /* If we have virtual bases, clobber the whole object, but only if we're in
16079      charge.  If we don't have virtual bases, clobber the as-base type so we
16080      don't mess with tail padding.  */
16081   bool vbases = CLASSTYPE_VBASECLASSES (current_class_type);
16082 
16083   tree ctype = current_class_type;
16084   if (!vbases)
16085     ctype = CLASSTYPE_AS_BASE (ctype);
16086 
16087   tree clobber = build_clobber (ctype);
16088 
16089   tree thisref = current_class_ref;
16090   if (ctype != current_class_type)
16091     {
16092       thisref = build_nop (build_reference_type (ctype), current_class_ptr);
16093       thisref = convert_from_reference (thisref);
16094     }
16095 
16096   tree exprstmt = build2 (MODIFY_EXPR, void_type_node, thisref, clobber);
16097   if (vbases)
16098     exprstmt = build_if_in_charge (exprstmt);
16099 
16100   return exprstmt;
16101 }
16102 
16103 /* Create the FUNCTION_DECL for a function definition.
16104    DECLSPECS and DECLARATOR are the parts of the declaration;
16105    they describe the function's name and the type it returns,
16106    but twisted together in a fashion that parallels the syntax of C.
16107 
16108    FLAGS is a bitwise or of SF_PRE_PARSED (indicating that the
16109    DECLARATOR is really the DECL for the function we are about to
16110    process and that DECLSPECS should be ignored), SF_INCLASS_INLINE
16111    indicating that the function is an inline defined in-class.
16112 
16113    This function creates a binding context for the function body
16114    as well as setting up the FUNCTION_DECL in current_function_decl.
16115 
16116    For C++, we must first check whether that datum makes any sense.
16117    For example, "class A local_a(1,2);" means that variable local_a
16118    is an aggregate of type A, which should have a constructor
16119    applied to it with the argument list [1, 2].
16120 
16121    On entry, DECL_INITIAL (decl1) should be NULL_TREE or error_mark_node,
16122    or may be a BLOCK if the function has been defined previously
16123    in this translation unit.  On exit, DECL_INITIAL (decl1) will be
16124    error_mark_node if the function has never been defined, or
16125    a BLOCK if the function has been defined somewhere.  */
16126 
16127 bool
start_preparsed_function(tree decl1,tree attrs,int flags)16128 start_preparsed_function (tree decl1, tree attrs, int flags)
16129 {
16130   tree ctype = NULL_TREE;
16131   tree fntype;
16132   tree restype;
16133   int doing_friend = 0;
16134   cp_binding_level *bl;
16135   tree current_function_parms;
16136   struct c_fileinfo *finfo
16137     = get_fileinfo (LOCATION_FILE (DECL_SOURCE_LOCATION (decl1)));
16138   bool honor_interface;
16139 
16140   /* Sanity check.  */
16141   gcc_assert (VOID_TYPE_P (TREE_VALUE (void_list_node)));
16142   gcc_assert (TREE_CHAIN (void_list_node) == NULL_TREE);
16143 
16144   fntype = TREE_TYPE (decl1);
16145   if (TREE_CODE (fntype) == METHOD_TYPE)
16146     ctype = TYPE_METHOD_BASETYPE (fntype);
16147 
16148   /* ISO C++ 11.4/5.  A friend function defined in a class is in
16149      the (lexical) scope of the class in which it is defined.  */
16150   if (!ctype && DECL_FRIEND_P (decl1))
16151     {
16152       ctype = DECL_FRIEND_CONTEXT (decl1);
16153 
16154       /* CTYPE could be null here if we're dealing with a template;
16155 	 for example, `inline friend float foo()' inside a template
16156 	 will have no CTYPE set.  */
16157       if (ctype && TREE_CODE (ctype) != RECORD_TYPE)
16158 	ctype = NULL_TREE;
16159       else
16160 	doing_friend = 1;
16161     }
16162 
16163   if (DECL_DECLARED_INLINE_P (decl1)
16164       && lookup_attribute ("noinline", attrs))
16165     warning_at (DECL_SOURCE_LOCATION (decl1), 0,
16166 		"inline function %qD given attribute %qs", decl1, "noinline");
16167 
16168   /* Handle gnu_inline attribute.  */
16169   if (GNU_INLINE_P (decl1))
16170     {
16171       DECL_EXTERNAL (decl1) = 1;
16172       DECL_NOT_REALLY_EXTERN (decl1) = 0;
16173       DECL_INTERFACE_KNOWN (decl1) = 1;
16174       DECL_DISREGARD_INLINE_LIMITS (decl1) = 1;
16175     }
16176 
16177   if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (decl1))
16178     /* This is a constructor, we must ensure that any default args
16179        introduced by this definition are propagated to the clones
16180        now. The clones are used directly in overload resolution.  */
16181     adjust_clone_args (decl1);
16182 
16183   /* Sometimes we don't notice that a function is a static member, and
16184      build a METHOD_TYPE for it.  Fix that up now.  */
16185   gcc_assert (!(ctype != NULL_TREE && DECL_STATIC_FUNCTION_P (decl1)
16186 		&& TREE_CODE (TREE_TYPE (decl1)) == METHOD_TYPE));
16187 
16188   /* Set up current_class_type, and enter the scope of the class, if
16189      appropriate.  */
16190   if (ctype)
16191     push_nested_class (ctype);
16192   else if (DECL_STATIC_FUNCTION_P (decl1))
16193     push_nested_class (DECL_CONTEXT (decl1));
16194 
16195   /* Now that we have entered the scope of the class, we must restore
16196      the bindings for any template parameters surrounding DECL1, if it
16197      is an inline member template.  (Order is important; consider the
16198      case where a template parameter has the same name as a field of
16199      the class.)  It is not until after this point that
16200      PROCESSING_TEMPLATE_DECL is guaranteed to be set up correctly.  */
16201   if (flags & SF_INCLASS_INLINE)
16202     maybe_begin_member_template_processing (decl1);
16203 
16204   /* Effective C++ rule 15.  */
16205   if (warn_ecpp
16206       && DECL_ASSIGNMENT_OPERATOR_P (decl1)
16207       && DECL_OVERLOADED_OPERATOR_IS (decl1, NOP_EXPR)
16208       && VOID_TYPE_P (TREE_TYPE (fntype)))
16209     warning (OPT_Weffc__,
16210 	     "%<operator=%> should return a reference to %<*this%>");
16211 
16212   /* Make the init_value nonzero so pushdecl knows this is not tentative.
16213      error_mark_node is replaced below (in poplevel) with the BLOCK.  */
16214   if (!DECL_INITIAL (decl1))
16215     DECL_INITIAL (decl1) = error_mark_node;
16216 
16217   /* This function exists in static storage.
16218      (This does not mean `static' in the C sense!)  */
16219   TREE_STATIC (decl1) = 1;
16220 
16221   /* We must call push_template_decl after current_class_type is set
16222      up.  (If we are processing inline definitions after exiting a
16223      class scope, current_class_type will be NULL_TREE until set above
16224      by push_nested_class.)  */
16225   if (processing_template_decl)
16226     {
16227       tree newdecl1 = push_template_decl (decl1);
16228       if (newdecl1 == error_mark_node)
16229 	{
16230 	  if (ctype || DECL_STATIC_FUNCTION_P (decl1))
16231 	    pop_nested_class ();
16232 	  return false;
16233 	}
16234       decl1 = newdecl1;
16235     }
16236 
16237   /* Make sure the parameter and return types are reasonable.  When
16238      you declare a function, these types can be incomplete, but they
16239      must be complete when you define the function.  */
16240   check_function_type (decl1, DECL_ARGUMENTS (decl1));
16241 
16242   /* Build the return declaration for the function.  */
16243   restype = TREE_TYPE (fntype);
16244 
16245   if (DECL_RESULT (decl1) == NULL_TREE)
16246     {
16247       tree resdecl;
16248 
16249       resdecl = build_decl (input_location, RESULT_DECL, 0, restype);
16250       DECL_ARTIFICIAL (resdecl) = 1;
16251       DECL_IGNORED_P (resdecl) = 1;
16252       DECL_RESULT (decl1) = resdecl;
16253 
16254       cp_apply_type_quals_to_decl (cp_type_quals (restype), resdecl);
16255     }
16256 
16257   /* Record the decl so that the function name is defined.
16258      If we already have a decl for this name, and it is a FUNCTION_DECL,
16259      use the old decl.  */
16260   if (!processing_template_decl && !(flags & SF_PRE_PARSED))
16261     {
16262       /* A specialization is not used to guide overload resolution.  */
16263       if (!DECL_FUNCTION_MEMBER_P (decl1)
16264 	  && !(DECL_USE_TEMPLATE (decl1) &&
16265 	       PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl1))))
16266 	{
16267 	  tree olddecl = pushdecl (decl1);
16268 
16269 	  if (olddecl == error_mark_node)
16270 	    /* If something went wrong when registering the declaration,
16271 	       use DECL1; we have to have a FUNCTION_DECL to use when
16272 	       parsing the body of the function.  */
16273 	    ;
16274 	  else
16275 	    {
16276 	      /* Otherwise, OLDDECL is either a previous declaration
16277 		 of the same function or DECL1 itself.  */
16278 
16279 	      if (warn_missing_declarations
16280 		  && olddecl == decl1
16281 		  && !DECL_MAIN_P (decl1)
16282 		  && TREE_PUBLIC (decl1)
16283 		  && !DECL_DECLARED_INLINE_P (decl1))
16284 		{
16285 		  tree context;
16286 
16287 		  /* Check whether DECL1 is in an anonymous
16288 		     namespace.  */
16289 		  for (context = DECL_CONTEXT (decl1);
16290 		       context;
16291 		       context = DECL_CONTEXT (context))
16292 		    {
16293 		      if (TREE_CODE (context) == NAMESPACE_DECL
16294 			  && DECL_NAME (context) == NULL_TREE)
16295 			break;
16296 		    }
16297 
16298 		  if (context == NULL)
16299 		    warning_at (DECL_SOURCE_LOCATION (decl1),
16300 				OPT_Wmissing_declarations,
16301 				"no previous declaration for %qD", decl1);
16302 		}
16303 
16304 	      decl1 = olddecl;
16305 	    }
16306 	}
16307       else
16308 	{
16309 	  /* We need to set the DECL_CONTEXT.  */
16310 	  if (!DECL_CONTEXT (decl1) && DECL_TEMPLATE_INFO (decl1))
16311 	    DECL_CONTEXT (decl1) = DECL_CONTEXT (DECL_TI_TEMPLATE (decl1));
16312 	}
16313       fntype = TREE_TYPE (decl1);
16314       restype = TREE_TYPE (fntype);
16315 
16316       /* If #pragma weak applies, mark the decl appropriately now.
16317 	 The pragma only applies to global functions.  Because
16318 	 determining whether or not the #pragma applies involves
16319 	 computing the mangled name for the declaration, we cannot
16320 	 apply the pragma until after we have merged this declaration
16321 	 with any previous declarations; if the original declaration
16322 	 has a linkage specification, that specification applies to
16323 	 the definition as well, and may affect the mangled name.  */
16324       if (DECL_FILE_SCOPE_P (decl1))
16325 	maybe_apply_pragma_weak (decl1);
16326     }
16327 
16328   /* We are now in the scope of the function being defined.  */
16329   current_function_decl = decl1;
16330 
16331   /* Save the parm names or decls from this function's declarator
16332      where store_parm_decls will find them.  */
16333   current_function_parms = DECL_ARGUMENTS (decl1);
16334 
16335   /* Let the user know we're compiling this function.  */
16336   announce_function (decl1);
16337 
16338   gcc_assert (DECL_INITIAL (decl1));
16339 
16340   /* This function may already have been parsed, in which case just
16341      return; our caller will skip over the body without parsing.  */
16342   if (DECL_INITIAL (decl1) != error_mark_node)
16343     return true;
16344 
16345   /* Initialize RTL machinery.  We cannot do this until
16346      CURRENT_FUNCTION_DECL and DECL_RESULT are set up.  We do this
16347      even when processing a template; this is how we get
16348      CFUN set up, and our per-function variables initialized.
16349      FIXME factor out the non-RTL stuff.  */
16350   bl = current_binding_level;
16351   allocate_struct_function (decl1, processing_template_decl);
16352 
16353   /* Initialize the language data structures.  Whenever we start
16354      a new function, we destroy temporaries in the usual way.  */
16355   cfun->language = ggc_cleared_alloc<language_function> ();
16356   current_stmt_tree ()->stmts_are_full_exprs_p = 1;
16357   current_binding_level = bl;
16358 
16359   /* If we are (erroneously) defining a function that we have already
16360      defined before, wipe out what we knew before.  */
16361   gcc_checking_assert (!DECL_PENDING_INLINE_P (decl1));
16362   FNDECL_USED_AUTO (decl1) = false;
16363   DECL_SAVED_AUTO_RETURN_TYPE (decl1) = NULL;
16364 
16365   if (!processing_template_decl && type_uses_auto (restype))
16366     {
16367       FNDECL_USED_AUTO (decl1) = true;
16368       DECL_SAVED_AUTO_RETURN_TYPE (decl1) = restype;
16369     }
16370 
16371   /* Start the statement-tree, start the tree now.  */
16372   DECL_SAVED_TREE (decl1) = push_stmt_list ();
16373 
16374   if (ctype && !doing_friend && !DECL_STATIC_FUNCTION_P (decl1))
16375     {
16376       /* We know that this was set up by `grokclassfn'.  We do not
16377 	 wait until `store_parm_decls', since evil parse errors may
16378 	 never get us to that point.  Here we keep the consistency
16379 	 between `current_class_type' and `current_class_ptr'.  */
16380       tree t = DECL_ARGUMENTS (decl1);
16381 
16382       gcc_assert (t != NULL_TREE && TREE_CODE (t) == PARM_DECL);
16383       gcc_assert (TYPE_PTR_P (TREE_TYPE (t)));
16384 
16385       cp_function_chain->x_current_class_ref
16386 	= cp_build_fold_indirect_ref (t);
16387       /* Set this second to avoid shortcut in cp_build_indirect_ref.  */
16388       cp_function_chain->x_current_class_ptr = t;
16389 
16390       /* Constructors and destructors need to know whether they're "in
16391 	 charge" of initializing virtual base classes.  */
16392       t = DECL_CHAIN (t);
16393       if (DECL_HAS_IN_CHARGE_PARM_P (decl1))
16394 	{
16395 	  current_in_charge_parm = t;
16396 	  t = DECL_CHAIN (t);
16397 	}
16398       if (DECL_HAS_VTT_PARM_P (decl1))
16399 	{
16400 	  gcc_assert (DECL_NAME (t) == vtt_parm_identifier);
16401 	  current_vtt_parm = t;
16402 	}
16403     }
16404 
16405   honor_interface = (!DECL_TEMPLATE_INSTANTIATION (decl1)
16406 		     /* Implicitly-defined methods (like the
16407 			destructor for a class in which no destructor
16408 			is explicitly declared) must not be defined
16409 			until their definition is needed.  So, we
16410 			ignore interface specifications for
16411 			compiler-generated functions.  */
16412 		     && !DECL_ARTIFICIAL (decl1));
16413 
16414   if (processing_template_decl)
16415     /* Don't mess with interface flags.  */;
16416   else if (DECL_INTERFACE_KNOWN (decl1))
16417     {
16418       tree ctx = decl_function_context (decl1);
16419 
16420       if (DECL_NOT_REALLY_EXTERN (decl1))
16421 	DECL_EXTERNAL (decl1) = 0;
16422 
16423       if (ctx != NULL_TREE && vague_linkage_p (ctx))
16424 	/* This is a function in a local class in an extern inline
16425 	   or template function.  */
16426 	comdat_linkage (decl1);
16427     }
16428   /* If this function belongs to an interface, it is public.
16429      If it belongs to someone else's interface, it is also external.
16430      This only affects inlines and template instantiations.  */
16431   else if (!finfo->interface_unknown && honor_interface)
16432     {
16433       if (DECL_DECLARED_INLINE_P (decl1)
16434 	  || DECL_TEMPLATE_INSTANTIATION (decl1))
16435 	{
16436 	  DECL_EXTERNAL (decl1)
16437 	    = (finfo->interface_only
16438 	       || (DECL_DECLARED_INLINE_P (decl1)
16439 		   && ! flag_implement_inlines
16440 		   && !DECL_VINDEX (decl1)));
16441 
16442 	  /* For WIN32 we also want to put these in linkonce sections.  */
16443 	  maybe_make_one_only (decl1);
16444 	}
16445       else
16446 	DECL_EXTERNAL (decl1) = 0;
16447       DECL_INTERFACE_KNOWN (decl1) = 1;
16448       /* If this function is in an interface implemented in this file,
16449 	 make sure that the back end knows to emit this function
16450 	 here.  */
16451       if (!DECL_EXTERNAL (decl1))
16452 	mark_needed (decl1);
16453     }
16454   else if (finfo->interface_unknown && finfo->interface_only
16455 	   && honor_interface)
16456     {
16457       /* If MULTIPLE_SYMBOL_SPACES is defined and we saw a #pragma
16458 	 interface, we will have both finfo->interface_unknown and
16459 	 finfo->interface_only set.  In that case, we don't want to
16460 	 use the normal heuristics because someone will supply a
16461 	 #pragma implementation elsewhere, and deducing it here would
16462 	 produce a conflict.  */
16463       comdat_linkage (decl1);
16464       DECL_EXTERNAL (decl1) = 0;
16465       DECL_INTERFACE_KNOWN (decl1) = 1;
16466       DECL_DEFER_OUTPUT (decl1) = 1;
16467     }
16468   else
16469     {
16470       /* This is a definition, not a reference.
16471 	 So clear DECL_EXTERNAL, unless this is a GNU extern inline.  */
16472       if (!GNU_INLINE_P (decl1))
16473 	DECL_EXTERNAL (decl1) = 0;
16474 
16475       if ((DECL_DECLARED_INLINE_P (decl1)
16476 	   || DECL_TEMPLATE_INSTANTIATION (decl1))
16477 	  && ! DECL_INTERFACE_KNOWN (decl1))
16478 	DECL_DEFER_OUTPUT (decl1) = 1;
16479       else
16480 	DECL_INTERFACE_KNOWN (decl1) = 1;
16481     }
16482 
16483   /* Determine the ELF visibility attribute for the function.  We must not
16484      do this before calling "pushdecl", as we must allow "duplicate_decls"
16485      to merge any attributes appropriately.  We also need to wait until
16486      linkage is set.  */
16487   if (!DECL_CLONED_FUNCTION_P (decl1))
16488     determine_visibility (decl1);
16489 
16490   if (!processing_template_decl)
16491     maybe_instantiate_noexcept (decl1);
16492 
16493   begin_scope (sk_function_parms, decl1);
16494 
16495   ++function_depth;
16496 
16497   if (DECL_DESTRUCTOR_P (decl1)
16498       || (DECL_CONSTRUCTOR_P (decl1)
16499 	  && targetm.cxx.cdtor_returns_this ()))
16500     {
16501       cdtor_label = create_artificial_label (input_location);
16502       LABEL_DECL_CDTOR (cdtor_label) = true;
16503     }
16504 
16505   start_fname_decls ();
16506 
16507   store_parm_decls (current_function_parms);
16508 
16509   push_operator_bindings ();
16510 
16511   if (!processing_template_decl
16512       && (flag_lifetime_dse > 1)
16513       && DECL_CONSTRUCTOR_P (decl1)
16514       && !DECL_CLONED_FUNCTION_P (decl1)
16515       /* Clobbering an empty base is harmful if it overlays real data.  */
16516       && !is_empty_class (current_class_type)
16517       /* We can't clobber safely for an implicitly-defined default constructor
16518 	 because part of the initialization might happen before we enter the
16519 	 constructor, via AGGR_INIT_ZERO_FIRST (c++/68006).  */
16520       && !implicit_default_ctor_p (decl1))
16521     finish_expr_stmt (build_clobber_this ());
16522 
16523   if (!processing_template_decl
16524       && DECL_CONSTRUCTOR_P (decl1)
16525       && sanitize_flags_p (SANITIZE_VPTR)
16526       && !DECL_CLONED_FUNCTION_P (decl1)
16527       && !implicit_default_ctor_p (decl1))
16528     cp_ubsan_maybe_initialize_vtbl_ptrs (current_class_ptr);
16529 
16530   if (!DECL_OMP_DECLARE_REDUCTION_P (decl1))
16531     start_lambda_scope (decl1);
16532 
16533   return true;
16534 }
16535 
16536 
16537 /* Like start_preparsed_function, except that instead of a
16538    FUNCTION_DECL, this function takes DECLSPECS and DECLARATOR.
16539 
16540    Returns true on success.  If the DECLARATOR is not suitable
16541    for a function, we return false, which tells the parser to
16542    skip the entire function.  */
16543 
16544 bool
start_function(cp_decl_specifier_seq * declspecs,const cp_declarator * declarator,tree attrs)16545 start_function (cp_decl_specifier_seq *declspecs,
16546 		const cp_declarator *declarator,
16547 		tree attrs)
16548 {
16549   tree decl1;
16550 
16551   decl1 = grokdeclarator (declarator, declspecs, FUNCDEF, 1, &attrs);
16552   invoke_plugin_callbacks (PLUGIN_START_PARSE_FUNCTION, decl1);
16553   if (decl1 == error_mark_node)
16554     return false;
16555 
16556   if (DECL_MAIN_P (decl1))
16557     /* main must return int.  grokfndecl should have corrected it
16558        (and issued a diagnostic) if the user got it wrong.  */
16559     gcc_assert (same_type_p (TREE_TYPE (TREE_TYPE (decl1)),
16560 			     integer_type_node));
16561 
16562   return start_preparsed_function (decl1, attrs, /*flags=*/SF_DEFAULT);
16563 }
16564 
16565 /* Returns true iff an EH_SPEC_BLOCK should be created in the body of
16566    FN.  */
16567 
16568 static bool
use_eh_spec_block(tree fn)16569 use_eh_spec_block (tree fn)
16570 {
16571   return (flag_exceptions && flag_enforce_eh_specs
16572 	  && !processing_template_decl
16573 	  /* We insert the EH_SPEC_BLOCK only in the original
16574 	     function; then, it is copied automatically to the
16575 	     clones.  */
16576 	  && !DECL_CLONED_FUNCTION_P (fn)
16577 	  /* Implicitly-generated constructors and destructors have
16578 	     exception specifications.  However, those specifications
16579 	     are the union of the possible exceptions specified by the
16580 	     constructors/destructors for bases and members, so no
16581 	     unallowed exception will ever reach this function.  By
16582 	     not creating the EH_SPEC_BLOCK we save a little memory,
16583 	     and we avoid spurious warnings about unreachable
16584 	     code.  */
16585 	  && !DECL_DEFAULTED_FN (fn)
16586 	  && !type_throw_all_p (TREE_TYPE (fn)));
16587 }
16588 
16589 /* Helper function to push ARGS into the current lexical scope.  DECL
16590    is the function declaration.  NONPARMS is used to handle enum
16591    constants.  */
16592 
16593 void
do_push_parm_decls(tree decl,tree args,tree * nonparms)16594 do_push_parm_decls (tree decl, tree args, tree *nonparms)
16595 {
16596   /* If we're doing semantic analysis, then we'll call pushdecl
16597      for each of these.  We must do them in reverse order so that
16598      they end in the correct forward order.  */
16599   args = nreverse (args);
16600 
16601   tree next;
16602   for (tree parm = args; parm; parm = next)
16603     {
16604       next = DECL_CHAIN (parm);
16605       if (TREE_CODE (parm) == PARM_DECL)
16606 	pushdecl (parm);
16607       else if (nonparms)
16608 	{
16609 	  /* If we find an enum constant or a type tag, put it aside for
16610 	     the moment.  */
16611 	  TREE_CHAIN (parm) = NULL_TREE;
16612 	  *nonparms = chainon (*nonparms, parm);
16613 	}
16614     }
16615 
16616   /* Get the decls in their original chain order and record in the
16617      function.  This is all and only the PARM_DECLs that were
16618      pushed into scope by the loop above.  */
16619   DECL_ARGUMENTS (decl) = get_local_decls ();
16620 }
16621 
16622 /* Store the parameter declarations into the current function declaration.
16623    This is called after parsing the parameter declarations, before
16624    digesting the body of the function.
16625 
16626    Also install to binding contour return value identifier, if any.  */
16627 
16628 static void
store_parm_decls(tree current_function_parms)16629 store_parm_decls (tree current_function_parms)
16630 {
16631   tree fndecl = current_function_decl;
16632 
16633   /* This is a chain of any other decls that came in among the parm
16634      declarations.  If a parm is declared with  enum {foo, bar} x;
16635      then CONST_DECLs for foo and bar are put here.  */
16636   tree nonparms = NULL_TREE;
16637 
16638   if (current_function_parms)
16639     {
16640       /* This case is when the function was defined with an ANSI prototype.
16641 	 The parms already have decls, so we need not do anything here
16642 	 except record them as in effect
16643 	 and complain if any redundant old-style parm decls were written.  */
16644 
16645       tree specparms = current_function_parms;
16646 
16647       /* Must clear this because it might contain TYPE_DECLs declared
16648 	     at class level.  */
16649       current_binding_level->names = NULL;
16650 
16651       do_push_parm_decls (fndecl, specparms, &nonparms);
16652     }
16653   else
16654     DECL_ARGUMENTS (fndecl) = NULL_TREE;
16655 
16656   /* Now store the final chain of decls for the arguments
16657      as the decl-chain of the current lexical scope.
16658      Put the enumerators in as well, at the front so that
16659      DECL_ARGUMENTS is not modified.  */
16660   current_binding_level->names = chainon (nonparms, DECL_ARGUMENTS (fndecl));
16661 
16662   if (use_eh_spec_block (current_function_decl))
16663     current_eh_spec_block = begin_eh_spec_block ();
16664 }
16665 
16666 
16667 /* Set the return value of the constructor (if present).  */
16668 
16669 static void
finish_constructor_body(void)16670 finish_constructor_body (void)
16671 {
16672   tree val;
16673   tree exprstmt;
16674 
16675   if (targetm.cxx.cdtor_returns_this ())
16676     {
16677       /* Any return from a constructor will end up here.  */
16678       add_stmt (build_stmt (input_location, LABEL_EXPR, cdtor_label));
16679 
16680       val = DECL_ARGUMENTS (current_function_decl);
16681       val = build2 (MODIFY_EXPR, TREE_TYPE (val),
16682 		    DECL_RESULT (current_function_decl), val);
16683       /* Return the address of the object.  */
16684       exprstmt = build_stmt (input_location, RETURN_EXPR, val);
16685       add_stmt (exprstmt);
16686     }
16687 }
16688 
16689 /* Do all the processing for the beginning of a destructor; set up the
16690    vtable pointers and cleanups for bases and members.  */
16691 
16692 static void
begin_destructor_body(void)16693 begin_destructor_body (void)
16694 {
16695   tree compound_stmt;
16696 
16697   /* If the CURRENT_CLASS_TYPE is incomplete, we will have already
16698      issued an error message.  We still want to try to process the
16699      body of the function, but initialize_vtbl_ptrs will crash if
16700      TYPE_BINFO is NULL.  */
16701   if (COMPLETE_TYPE_P (current_class_type))
16702     {
16703       compound_stmt = begin_compound_stmt (0);
16704       /* Make all virtual function table pointers in non-virtual base
16705 	 classes point to CURRENT_CLASS_TYPE's virtual function
16706 	 tables.  */
16707       initialize_vtbl_ptrs (current_class_ptr);
16708       finish_compound_stmt (compound_stmt);
16709 
16710       if (flag_lifetime_dse
16711 	  /* Clobbering an empty base is harmful if it overlays real data.  */
16712 	  && !is_empty_class (current_class_type))
16713       {
16714 	if (sanitize_flags_p (SANITIZE_VPTR)
16715 	    && (flag_sanitize_recover & SANITIZE_VPTR) == 0
16716 	    && TYPE_CONTAINS_VPTR_P (current_class_type))
16717 	  {
16718 	    tree binfo = TYPE_BINFO (current_class_type);
16719 	    tree ref
16720 	      = cp_build_fold_indirect_ref (current_class_ptr);
16721 
16722 	    tree vtbl_ptr = build_vfield_ref (ref, TREE_TYPE (binfo));
16723 	    tree vtbl = build_zero_cst (TREE_TYPE (vtbl_ptr));
16724 	    tree stmt = cp_build_modify_expr (input_location, vtbl_ptr,
16725 					      NOP_EXPR, vtbl,
16726 					      tf_warning_or_error);
16727 	    /* If the vptr is shared with some virtual nearly empty base,
16728 	       don't clear it if not in charge, the dtor of the virtual
16729 	       nearly empty base will do that later.  */
16730 	    if (CLASSTYPE_VBASECLASSES (current_class_type))
16731 	      {
16732 		tree c = current_class_type;
16733 		while (CLASSTYPE_PRIMARY_BINFO (c))
16734 		  {
16735 		    if (BINFO_VIRTUAL_P (CLASSTYPE_PRIMARY_BINFO (c)))
16736 		      {
16737 			stmt = convert_to_void (stmt, ICV_STATEMENT,
16738 						tf_warning_or_error);
16739 			stmt = build_if_in_charge (stmt);
16740 			break;
16741 		      }
16742 		    c = BINFO_TYPE (CLASSTYPE_PRIMARY_BINFO (c));
16743 		  }
16744 	      }
16745 	    finish_decl_cleanup (NULL_TREE, stmt);
16746 	  }
16747 	else
16748 	  finish_decl_cleanup (NULL_TREE, build_clobber_this ());
16749       }
16750 
16751       /* And insert cleanups for our bases and members so that they
16752 	 will be properly destroyed if we throw.  */
16753       push_base_cleanups ();
16754     }
16755 }
16756 
16757 /* At the end of every destructor we generate code to delete the object if
16758    necessary.  Do that now.  */
16759 
16760 static void
finish_destructor_body(void)16761 finish_destructor_body (void)
16762 {
16763   tree exprstmt;
16764 
16765   /* Any return from a destructor will end up here; that way all base
16766      and member cleanups will be run when the function returns.  */
16767   add_stmt (build_stmt (input_location, LABEL_EXPR, cdtor_label));
16768 
16769   if (targetm.cxx.cdtor_returns_this ())
16770     {
16771       tree val;
16772 
16773       val = DECL_ARGUMENTS (current_function_decl);
16774       val = build2 (MODIFY_EXPR, TREE_TYPE (val),
16775 		    DECL_RESULT (current_function_decl), val);
16776       /* Return the address of the object.  */
16777       exprstmt = build_stmt (input_location, RETURN_EXPR, val);
16778       add_stmt (exprstmt);
16779     }
16780 }
16781 
16782 /* Do the necessary processing for the beginning of a function body, which
16783    in this case includes member-initializers, but not the catch clauses of
16784    a function-try-block.  Currently, this means opening a binding level
16785    for the member-initializers (in a ctor), member cleanups (in a dtor),
16786    and capture proxies (in a lambda operator()).  */
16787 
16788 tree
begin_function_body(void)16789 begin_function_body (void)
16790 {
16791   tree stmt;
16792 
16793   if (! FUNCTION_NEEDS_BODY_BLOCK (current_function_decl))
16794     return NULL_TREE;
16795 
16796   if (processing_template_decl)
16797     /* Do nothing now.  */;
16798   else
16799     /* Always keep the BLOCK node associated with the outermost pair of
16800        curly braces of a function.  These are needed for correct
16801        operation of dwarfout.c.  */
16802     keep_next_level (true);
16803 
16804   stmt = begin_compound_stmt (BCS_FN_BODY);
16805 
16806   if (processing_template_decl)
16807     /* Do nothing now.  */;
16808   else if (DECL_DESTRUCTOR_P (current_function_decl))
16809     begin_destructor_body ();
16810 
16811   return stmt;
16812 }
16813 
16814 /* Do the processing for the end of a function body.  Currently, this means
16815    closing out the cleanups for fully-constructed bases and members, and in
16816    the case of the destructor, deleting the object if desired.  Again, this
16817    is only meaningful for [cd]tors, since they are the only functions where
16818    there is a significant distinction between the main body and any
16819    function catch clauses.  Handling, say, main() return semantics here
16820    would be wrong, as flowing off the end of a function catch clause for
16821    main() would also need to return 0.  */
16822 
16823 void
finish_function_body(tree compstmt)16824 finish_function_body (tree compstmt)
16825 {
16826   if (compstmt == NULL_TREE)
16827     return;
16828 
16829   /* Close the block.  */
16830   finish_compound_stmt (compstmt);
16831 
16832   if (processing_template_decl)
16833     /* Do nothing now.  */;
16834   else if (DECL_CONSTRUCTOR_P (current_function_decl))
16835     finish_constructor_body ();
16836   else if (DECL_DESTRUCTOR_P (current_function_decl))
16837     finish_destructor_body ();
16838 }
16839 
16840 /* Given a function, returns the BLOCK corresponding to the outermost level
16841    of curly braces, skipping the artificial block created for constructor
16842    initializers.  */
16843 
16844 tree
outer_curly_brace_block(tree fndecl)16845 outer_curly_brace_block (tree fndecl)
16846 {
16847   tree block = DECL_INITIAL (fndecl);
16848   if (BLOCK_OUTER_CURLY_BRACE_P (block))
16849     return block;
16850   block = BLOCK_SUBBLOCKS (block);
16851   if (BLOCK_OUTER_CURLY_BRACE_P (block))
16852     return block;
16853   block = BLOCK_SUBBLOCKS (block);
16854   gcc_assert (BLOCK_OUTER_CURLY_BRACE_P (block));
16855   return block;
16856 }
16857 
16858 /* If FNDECL is a class's key method, add the class to the list of
16859    keyed classes that should be emitted.  */
16860 
16861 static void
record_key_method_defined(tree fndecl)16862 record_key_method_defined (tree fndecl)
16863 {
16864   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fndecl)
16865       && DECL_VIRTUAL_P (fndecl)
16866       && !processing_template_decl)
16867     {
16868       tree fnclass = DECL_CONTEXT (fndecl);
16869       if (fndecl == CLASSTYPE_KEY_METHOD (fnclass))
16870 	vec_safe_push (keyed_classes, fnclass);
16871     }
16872 }
16873 
16874 /* Subroutine of finish_function.
16875    Save the body of constexpr functions for possible
16876    future compile time evaluation.  */
16877 
16878 static void
maybe_save_function_definition(tree fun)16879 maybe_save_function_definition (tree fun)
16880 {
16881   if (!processing_template_decl
16882       && DECL_DECLARED_CONSTEXPR_P (fun)
16883       && !cp_function_chain->invalid_constexpr
16884       && !DECL_CLONED_FUNCTION_P (fun))
16885     register_constexpr_fundef (fun, DECL_SAVED_TREE (fun));
16886 }
16887 
16888 /* Attempt to add a fix-it hint to RICHLOC suggesting the insertion
16889    of "return *this;" immediately before its location, using FNDECL's
16890    first statement (if any) to give the indentation, if appropriate.  */
16891 
16892 static void
add_return_star_this_fixit(gcc_rich_location * richloc,tree fndecl)16893 add_return_star_this_fixit (gcc_rich_location *richloc, tree fndecl)
16894 {
16895   location_t indent = UNKNOWN_LOCATION;
16896   tree stmts = expr_first (DECL_SAVED_TREE (fndecl));
16897   if (stmts)
16898     indent = EXPR_LOCATION (stmts);
16899   richloc->add_fixit_insert_formatted ("return *this;",
16900 				       richloc->get_loc (),
16901 				       indent);
16902 }
16903 
16904 /* This function carries out the subset of finish_function operations needed
16905    to emit the compiler-generated outlined helper functions used by the
16906    coroutines implementation.  */
16907 
16908 static void
emit_coro_helper(tree helper)16909 emit_coro_helper (tree helper)
16910 {
16911   /* This is a partial set of the operations done by finish_function()
16912      plus emitting the result.  */
16913   set_cfun (NULL);
16914   current_function_decl = helper;
16915   begin_scope (sk_function_parms, NULL);
16916   store_parm_decls (DECL_ARGUMENTS (helper));
16917   announce_function (helper);
16918   allocate_struct_function (helper, false);
16919   cfun->language = ggc_cleared_alloc<language_function> ();
16920   poplevel (1, 0, 1);
16921   maybe_save_function_definition (helper);
16922   /* We must start each function with a clear fold cache.  */
16923   clear_fold_cache ();
16924   cp_fold_function (helper);
16925   DECL_CONTEXT (DECL_RESULT (helper)) = helper;
16926   BLOCK_SUPERCONTEXT (DECL_INITIAL (helper)) = helper;
16927   /* This function has coroutine IFNs that we should handle in middle
16928      end lowering.  */
16929   cfun->coroutine_component = true;
16930   cp_genericize (helper);
16931   expand_or_defer_fn (helper);
16932 }
16933 
16934 /* Finish up a function declaration and compile that function
16935    all the way to assembler language output.  The free the storage
16936    for the function definition. INLINE_P is TRUE if we just
16937    finished processing the body of an in-class inline function
16938    definition.  (This processing will have taken place after the
16939    class definition is complete.)  */
16940 
16941 tree
finish_function(bool inline_p)16942 finish_function (bool inline_p)
16943 {
16944   tree fndecl = current_function_decl;
16945   tree fntype, ctype = NULL_TREE;
16946   tree resumer = NULL_TREE, destroyer = NULL_TREE;
16947   bool coro_p = flag_coroutines
16948 		&& !processing_template_decl
16949 		&& DECL_COROUTINE_P (fndecl);
16950   bool coro_emit_helpers = false;
16951 
16952   /* When we get some parse errors, we can end up without a
16953      current_function_decl, so cope.  */
16954   if (fndecl == NULL_TREE)
16955     return error_mark_node;
16956 
16957   if (!DECL_OMP_DECLARE_REDUCTION_P (fndecl))
16958     finish_lambda_scope ();
16959 
16960   if (c_dialect_objc ())
16961     objc_finish_function ();
16962 
16963   record_key_method_defined (fndecl);
16964 
16965   fntype = TREE_TYPE (fndecl);
16966 
16967   /*  TREE_READONLY (fndecl) = 1;
16968       This caused &foo to be of type ptr-to-const-function
16969       which then got a warning when stored in a ptr-to-function variable.  */
16970 
16971   gcc_assert (building_stmt_list_p ());
16972   /* The current function is being defined, so its DECL_INITIAL should
16973      be set, and unless there's a multiple definition, it should be
16974      error_mark_node.  */
16975   gcc_assert (DECL_INITIAL (fndecl) == error_mark_node);
16976 
16977   if (coro_p)
16978     {
16979       /* Only try to emit the coroutine outlined helper functions if the
16980 	 transforms succeeded.  Otherwise, treat errors in the same way as
16981 	 a regular function.  */
16982       coro_emit_helpers = morph_fn_to_coro (fndecl, &resumer, &destroyer);
16983 
16984       /* We should handle coroutine IFNs in middle end lowering.  */
16985       cfun->coroutine_component = true;
16986 
16987       /* Do not try to process the ramp's EH unless outlining succeeded.  */
16988       if (coro_emit_helpers && use_eh_spec_block (fndecl))
16989 	finish_eh_spec_block (TYPE_RAISES_EXCEPTIONS
16990 			      (TREE_TYPE (fndecl)),
16991 			      current_eh_spec_block);
16992     }
16993   else
16994   /* For a cloned function, we've already got all the code we need;
16995      there's no need to add any extra bits.  */
16996   if (!DECL_CLONED_FUNCTION_P (fndecl))
16997     {
16998       /* Make it so that `main' always returns 0 by default.  */
16999       if (DECL_MAIN_P (current_function_decl))
17000 	finish_return_stmt (integer_zero_node);
17001 
17002       if (use_eh_spec_block (current_function_decl))
17003 	finish_eh_spec_block (TYPE_RAISES_EXCEPTIONS
17004 			      (TREE_TYPE (current_function_decl)),
17005 			      current_eh_spec_block);
17006     }
17007 
17008   /* If we're saving up tree structure, tie off the function now.  */
17009   DECL_SAVED_TREE (fndecl) = pop_stmt_list (DECL_SAVED_TREE (fndecl));
17010 
17011   finish_fname_decls ();
17012 
17013   /* If this function can't throw any exceptions, remember that.  */
17014   if (!processing_template_decl
17015       && !cp_function_chain->can_throw
17016       && !flag_non_call_exceptions
17017       && !decl_replaceable_p (fndecl))
17018     TREE_NOTHROW (fndecl) = 1;
17019 
17020   /* This must come after expand_function_end because cleanups might
17021      have declarations (from inline functions) that need to go into
17022      this function's blocks.  */
17023 
17024   /* If the current binding level isn't the outermost binding level
17025      for this function, either there is a bug, or we have experienced
17026      syntax errors and the statement tree is malformed.  */
17027   if (current_binding_level->kind != sk_function_parms)
17028     {
17029       /* Make sure we have already experienced errors.  */
17030       gcc_assert (errorcount);
17031 
17032       /* Throw away the broken statement tree and extra binding
17033 	 levels.  */
17034       DECL_SAVED_TREE (fndecl) = alloc_stmt_list ();
17035 
17036       while (current_binding_level->kind != sk_function_parms)
17037 	{
17038 	  if (current_binding_level->kind == sk_class)
17039 	    pop_nested_class ();
17040 	  else
17041 	    poplevel (0, 0, 0);
17042 	}
17043     }
17044   poplevel (1, 0, 1);
17045 
17046   /* Statements should always be full-expressions at the outermost set
17047      of curly braces for a function.  */
17048   gcc_assert (stmts_are_full_exprs_p ());
17049 
17050   /* If there are no return statements in a function with auto return type,
17051      the return type is void.  But if the declared type is something like
17052      auto*, this is an error.  */
17053   if (!processing_template_decl && FNDECL_USED_AUTO (fndecl)
17054       && TREE_TYPE (fntype) == DECL_SAVED_AUTO_RETURN_TYPE (fndecl))
17055     {
17056       if (is_auto (DECL_SAVED_AUTO_RETURN_TYPE (fndecl))
17057           && !current_function_returns_value
17058           && !current_function_returns_null)
17059 	{
17060 	  /* We haven't applied return type deduction because we haven't
17061              seen any return statements. Do that now.  */
17062 	  tree node = type_uses_auto (DECL_SAVED_AUTO_RETURN_TYPE (fndecl));
17063 	  do_auto_deduction (DECL_SAVED_AUTO_RETURN_TYPE (fndecl),
17064 			     void_node, node, tf_warning_or_error,
17065                              adc_return_type);
17066 
17067 	  apply_deduced_return_type (fndecl, void_type_node);
17068 	  fntype = TREE_TYPE (fndecl);
17069 	}
17070       else if (!current_function_returns_value
17071 	       && !current_function_returns_null)
17072 	{
17073 	  error ("no return statements in function returning %qT",
17074 		 DECL_SAVED_AUTO_RETURN_TYPE (fndecl));
17075 	  inform (input_location, "only plain %<auto%> return type can be "
17076 		  "deduced to %<void%>");
17077 	}
17078     }
17079 
17080   /* Remember that we were in class scope.  */
17081   if (current_class_name)
17082     ctype = current_class_type;
17083 
17084   if (DECL_DELETED_FN (fndecl))
17085     {
17086       DECL_INITIAL (fndecl) = error_mark_node;
17087       DECL_SAVED_TREE (fndecl) = NULL_TREE;
17088       goto cleanup;
17089     }
17090 
17091   // If this is a concept, check that the definition is reasonable.
17092   if (DECL_DECLARED_CONCEPT_P (fndecl))
17093     check_function_concept (fndecl);
17094 
17095   if (flag_openmp)
17096     if (tree attr = lookup_attribute ("omp declare variant base",
17097 				      DECL_ATTRIBUTES (fndecl)))
17098       omp_declare_variant_finalize (fndecl, attr);
17099 
17100   /* Lambda closure members are implicitly constexpr if possible.  */
17101   if (cxx_dialect >= cxx17
17102       && LAMBDA_TYPE_P (CP_DECL_CONTEXT (fndecl)))
17103     DECL_DECLARED_CONSTEXPR_P (fndecl)
17104       = ((processing_template_decl
17105 	  || is_valid_constexpr_fn (fndecl, /*complain*/false))
17106 	 && potential_constant_expression (DECL_SAVED_TREE (fndecl)));
17107 
17108   /* Save constexpr function body before it gets munged by
17109      the NRV transformation.   */
17110   maybe_save_function_definition (fndecl);
17111 
17112   /* Invoke the pre-genericize plugin before we start munging things.  */
17113   if (!processing_template_decl)
17114     invoke_plugin_callbacks (PLUGIN_PRE_GENERICIZE, fndecl);
17115 
17116   /* Perform delayed folding before NRV transformation.  */
17117   if (!processing_template_decl
17118       && !DECL_IMMEDIATE_FUNCTION_P (fndecl)
17119       && !DECL_OMP_DECLARE_REDUCTION_P (fndecl))
17120     cp_fold_function (fndecl);
17121 
17122   /* Set up the named return value optimization, if we can.  Candidate
17123      variables are selected in check_return_expr.  */
17124   if (current_function_return_value)
17125     {
17126       tree r = current_function_return_value;
17127       tree outer;
17128 
17129       if (r != error_mark_node
17130 	  /* This is only worth doing for fns that return in memory--and
17131 	     simpler, since we don't have to worry about promoted modes.  */
17132 	  && aggregate_value_p (TREE_TYPE (TREE_TYPE (fndecl)), fndecl)
17133 	  /* Only allow this for variables declared in the outer scope of
17134 	     the function so we know that their lifetime always ends with a
17135 	     return; see g++.dg/opt/nrv6.C.  We could be more flexible if
17136 	     we were to do this optimization in tree-ssa.  */
17137 	  && (outer = outer_curly_brace_block (fndecl))
17138 	  && chain_member (r, BLOCK_VARS (outer)))
17139 	finalize_nrv (&DECL_SAVED_TREE (fndecl), r, DECL_RESULT (fndecl));
17140 
17141       current_function_return_value = NULL_TREE;
17142     }
17143 
17144   /* Must mark the RESULT_DECL as being in this function.  */
17145   DECL_CONTEXT (DECL_RESULT (fndecl)) = fndecl;
17146 
17147   /* Set the BLOCK_SUPERCONTEXT of the outermost function scope to point
17148      to the FUNCTION_DECL node itself.  */
17149   BLOCK_SUPERCONTEXT (DECL_INITIAL (fndecl)) = fndecl;
17150 
17151   /* Complain if there's just no return statement.  */
17152   if (warn_return_type
17153       && !VOID_TYPE_P (TREE_TYPE (fntype))
17154       && !dependent_type_p (TREE_TYPE (fntype))
17155       && !current_function_returns_value && !current_function_returns_null
17156       /* Don't complain if we abort or throw.  */
17157       && !current_function_returns_abnormally
17158       /* Don't complain if there's an infinite loop.  */
17159       && !current_function_infinite_loop
17160       /* Don't complain if we are declared noreturn.  */
17161       && !TREE_THIS_VOLATILE (fndecl)
17162       && !DECL_NAME (DECL_RESULT (fndecl))
17163       && !TREE_NO_WARNING (fndecl)
17164       /* Structor return values (if any) are set by the compiler.  */
17165       && !DECL_CONSTRUCTOR_P (fndecl)
17166       && !DECL_DESTRUCTOR_P (fndecl)
17167       && targetm.warn_func_return (fndecl))
17168     {
17169       gcc_rich_location richloc (input_location);
17170       /* Potentially add a "return *this;" fix-it hint for
17171 	 assignment operators.  */
17172       if (IDENTIFIER_ASSIGN_OP_P (DECL_NAME (fndecl)))
17173 	{
17174 	  tree valtype = TREE_TYPE (DECL_RESULT (fndecl));
17175 	  if (TREE_CODE (valtype) == REFERENCE_TYPE
17176 	      && current_class_ref
17177 	      && same_type_ignoring_top_level_qualifiers_p
17178 		  (TREE_TYPE (valtype), TREE_TYPE (current_class_ref))
17179 	      && global_dc->option_enabled (OPT_Wreturn_type,
17180 					    global_dc->lang_mask,
17181 					    global_dc->option_state))
17182 	    add_return_star_this_fixit (&richloc, fndecl);
17183 	}
17184       if (warning_at (&richloc, OPT_Wreturn_type,
17185 	  "no return statement in function returning non-void"))
17186 	TREE_NO_WARNING (fndecl) = 1;
17187     }
17188 
17189   /* Store the end of the function, so that we get good line number
17190      info for the epilogue.  */
17191   cfun->function_end_locus = input_location;
17192 
17193   /* Complain about parameters that are only set, but never otherwise used.  */
17194   if (warn_unused_but_set_parameter
17195       && !processing_template_decl
17196       && errorcount == unused_but_set_errorcount
17197       && !DECL_CLONED_FUNCTION_P (fndecl))
17198     {
17199       tree decl;
17200 
17201       for (decl = DECL_ARGUMENTS (fndecl);
17202 	   decl;
17203 	   decl = DECL_CHAIN (decl))
17204 	if (TREE_USED (decl)
17205 	    && TREE_CODE (decl) == PARM_DECL
17206 	    && !DECL_READ_P (decl)
17207 	    && DECL_NAME (decl)
17208 	    && !DECL_ARTIFICIAL (decl)
17209 	    && !TREE_NO_WARNING (decl)
17210 	    && !DECL_IN_SYSTEM_HEADER (decl)
17211 	    && TREE_TYPE (decl) != error_mark_node
17212 	    && !TYPE_REF_P (TREE_TYPE (decl))
17213 	    && (!CLASS_TYPE_P (TREE_TYPE (decl))
17214 	        || !TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (decl))))
17215 	  warning_at (DECL_SOURCE_LOCATION (decl),
17216 		      OPT_Wunused_but_set_parameter,
17217 		      "parameter %qD set but not used", decl);
17218       unused_but_set_errorcount = errorcount;
17219     }
17220 
17221   /* Complain about locally defined typedefs that are not used in this
17222      function.  */
17223   maybe_warn_unused_local_typedefs ();
17224 
17225   /* Possibly warn about unused parameters.  */
17226   if (warn_unused_parameter
17227       && !processing_template_decl
17228       && !DECL_CLONED_FUNCTION_P (fndecl))
17229     do_warn_unused_parameter (fndecl);
17230 
17231   /* Genericize before inlining.  */
17232   if (!processing_template_decl
17233       && !DECL_IMMEDIATE_FUNCTION_P (fndecl)
17234       && !DECL_OMP_DECLARE_REDUCTION_P (fndecl))
17235     cp_genericize (fndecl);
17236 
17237   /* Emit the resumer and destroyer functions now, providing that we have
17238      not encountered some fatal error.  */
17239   if (coro_emit_helpers)
17240     {
17241       emit_coro_helper (resumer);
17242       emit_coro_helper (destroyer);
17243     }
17244 
17245  cleanup:
17246   /* We're leaving the context of this function, so zap cfun.  It's still in
17247      DECL_STRUCT_FUNCTION, and we'll restore it in tree_rest_of_compilation.  */
17248   set_cfun (NULL);
17249   current_function_decl = NULL;
17250 
17251   /* If this is an in-class inline definition, we may have to pop the
17252      bindings for the template parameters that we added in
17253      maybe_begin_member_template_processing when start_function was
17254      called.  */
17255   if (inline_p)
17256     maybe_end_member_template_processing ();
17257 
17258   /* Leave the scope of the class.  */
17259   if (ctype)
17260     pop_nested_class ();
17261 
17262   --function_depth;
17263 
17264   /* Clean up.  */
17265   current_function_decl = NULL_TREE;
17266 
17267   invoke_plugin_callbacks (PLUGIN_FINISH_PARSE_FUNCTION, fndecl);
17268   return fndecl;
17269 }
17270 
17271 /* Create the FUNCTION_DECL for a function definition.
17272    DECLSPECS and DECLARATOR are the parts of the declaration;
17273    they describe the return type and the name of the function,
17274    but twisted together in a fashion that parallels the syntax of C.
17275 
17276    This function creates a binding context for the function body
17277    as well as setting up the FUNCTION_DECL in current_function_decl.
17278 
17279    Returns a FUNCTION_DECL on success.
17280 
17281    If the DECLARATOR is not suitable for a function (it defines a datum
17282    instead), we return 0, which tells yyparse to report a parse error.
17283 
17284    May return void_type_node indicating that this method is actually
17285    a friend.  See grokfield for more details.
17286 
17287    Came here with a `.pushlevel' .
17288 
17289    DO NOT MAKE ANY CHANGES TO THIS CODE WITHOUT MAKING CORRESPONDING
17290    CHANGES TO CODE IN `grokfield'.  */
17291 
17292 tree
grokmethod(cp_decl_specifier_seq * declspecs,const cp_declarator * declarator,tree attrlist)17293 grokmethod (cp_decl_specifier_seq *declspecs,
17294 	    const cp_declarator *declarator, tree attrlist)
17295 {
17296   tree fndecl = grokdeclarator (declarator, declspecs, MEMFUNCDEF, 0,
17297 				&attrlist);
17298 
17299   if (fndecl == error_mark_node)
17300     return error_mark_node;
17301 
17302   if (attrlist)
17303     cplus_decl_attributes (&fndecl, attrlist, 0);
17304 
17305   /* Pass friends other than inline friend functions back.  */
17306   if (fndecl == void_type_node)
17307     return fndecl;
17308 
17309   if (DECL_IN_AGGR_P (fndecl))
17310     {
17311       if (DECL_CLASS_SCOPE_P (fndecl))
17312 	error ("%qD is already defined in class %qT", fndecl,
17313 	       DECL_CONTEXT (fndecl));
17314       return error_mark_node;
17315     }
17316 
17317   check_template_shadow (fndecl);
17318 
17319   if (TREE_PUBLIC (fndecl))
17320     DECL_COMDAT (fndecl) = 1;
17321   DECL_DECLARED_INLINE_P (fndecl) = 1;
17322   DECL_NO_INLINE_WARNING_P (fndecl) = 1;
17323 
17324   /* We process method specializations in finish_struct_1.  */
17325   if (processing_template_decl && !DECL_TEMPLATE_SPECIALIZATION (fndecl))
17326     {
17327       fndecl = push_template_decl (fndecl);
17328       if (fndecl == error_mark_node)
17329 	return fndecl;
17330     }
17331 
17332   if (! DECL_FRIEND_P (fndecl))
17333     {
17334       if (DECL_CHAIN (fndecl))
17335 	{
17336 	  fndecl = copy_node (fndecl);
17337 	  TREE_CHAIN (fndecl) = NULL_TREE;
17338 	}
17339     }
17340 
17341   cp_finish_decl (fndecl, NULL_TREE, false, NULL_TREE, 0);
17342 
17343   DECL_IN_AGGR_P (fndecl) = 1;
17344   return fndecl;
17345 }
17346 
17347 
17348 /* VAR is a VAR_DECL.  If its type is incomplete, remember VAR so that
17349    we can lay it out later, when and if its type becomes complete.
17350 
17351    Also handle constexpr variables where the initializer involves
17352    an unlowered PTRMEM_CST because the class isn't complete yet.  */
17353 
17354 void
maybe_register_incomplete_var(tree var)17355 maybe_register_incomplete_var (tree var)
17356 {
17357   gcc_assert (VAR_P (var));
17358 
17359   /* Keep track of variables with incomplete types.  */
17360   if (!processing_template_decl && TREE_TYPE (var) != error_mark_node
17361       && DECL_EXTERNAL (var))
17362     {
17363       tree inner_type = TREE_TYPE (var);
17364 
17365       while (TREE_CODE (inner_type) == ARRAY_TYPE)
17366 	inner_type = TREE_TYPE (inner_type);
17367       inner_type = TYPE_MAIN_VARIANT (inner_type);
17368 
17369       if ((!COMPLETE_TYPE_P (inner_type) && CLASS_TYPE_P (inner_type))
17370 	  /* RTTI TD entries are created while defining the type_info.  */
17371 	  || (TYPE_LANG_SPECIFIC (inner_type)
17372 	      && TYPE_BEING_DEFINED (inner_type)))
17373 	{
17374 	  incomplete_var iv = {var, inner_type};
17375 	  vec_safe_push (incomplete_vars, iv);
17376 	}
17377       else if (!(DECL_LANG_SPECIFIC (var) && DECL_TEMPLATE_INFO (var))
17378 	       && decl_constant_var_p (var)
17379 	       && (TYPE_PTRMEM_P (inner_type) || CLASS_TYPE_P (inner_type)))
17380 	{
17381 	  /* When the outermost open class is complete we can resolve any
17382 	     pointers-to-members.  */
17383 	  tree context = outermost_open_class ();
17384 	  incomplete_var iv = {var, context};
17385 	  vec_safe_push (incomplete_vars, iv);
17386 	}
17387     }
17388 }
17389 
17390 /* Called when a class type (given by TYPE) is defined.  If there are
17391    any existing VAR_DECLs whose type has been completed by this
17392    declaration, update them now.  */
17393 
17394 void
complete_vars(tree type)17395 complete_vars (tree type)
17396 {
17397   unsigned ix;
17398   incomplete_var *iv;
17399 
17400   for (ix = 0; vec_safe_iterate (incomplete_vars, ix, &iv); )
17401     {
17402       if (same_type_p (type, iv->incomplete_type))
17403 	{
17404 	  tree var = iv->decl;
17405 	  tree type = TREE_TYPE (var);
17406 
17407 	  if (type != error_mark_node
17408 	      && (TYPE_MAIN_VARIANT (strip_array_types (type))
17409 		  == iv->incomplete_type))
17410 	    {
17411 	      /* Complete the type of the variable.  The VAR_DECL itself
17412 		 will be laid out in expand_expr.  */
17413 	      complete_type (type);
17414 	      cp_apply_type_quals_to_decl (cp_type_quals (type), var);
17415 	    }
17416 
17417 	  /* Remove this entry from the list.  */
17418 	  incomplete_vars->unordered_remove (ix);
17419 	}
17420       else
17421 	ix++;
17422     }
17423 
17424   /* Check for pending declarations which may have abstract type.  */
17425   complete_type_check_abstract (type);
17426 }
17427 
17428 /* If DECL is of a type which needs a cleanup, build and return an
17429    expression to perform that cleanup here.  Return NULL_TREE if no
17430    cleanup need be done.  DECL can also be a _REF when called from
17431    split_nonconstant_init_1.  */
17432 
17433 tree
cxx_maybe_build_cleanup(tree decl,tsubst_flags_t complain)17434 cxx_maybe_build_cleanup (tree decl, tsubst_flags_t complain)
17435 {
17436   tree type;
17437   tree attr;
17438   tree cleanup;
17439 
17440   /* Assume no cleanup is required.  */
17441   cleanup = NULL_TREE;
17442 
17443   if (error_operand_p (decl))
17444     return cleanup;
17445 
17446   /* Handle "__attribute__((cleanup))".  We run the cleanup function
17447      before the destructor since the destructor is what actually
17448      terminates the lifetime of the object.  */
17449   if (DECL_P (decl))
17450     attr = lookup_attribute ("cleanup", DECL_ATTRIBUTES (decl));
17451   else
17452     attr = NULL_TREE;
17453   if (attr)
17454     {
17455       tree id;
17456       tree fn;
17457       tree arg;
17458 
17459       /* Get the name specified by the user for the cleanup function.  */
17460       id = TREE_VALUE (TREE_VALUE (attr));
17461       /* Look up the name to find the cleanup function to call.  It is
17462 	 important to use lookup_name here because that is what is
17463 	 used in c-common.c:handle_cleanup_attribute when performing
17464 	 initial checks on the attribute.  Note that those checks
17465 	 include ensuring that the function found is not an overloaded
17466 	 function, or an object with an overloaded call operator,
17467 	 etc.; we can rely on the fact that the function found is an
17468 	 ordinary FUNCTION_DECL.  */
17469       fn = lookup_name (id);
17470       arg = build_address (decl);
17471       if (!mark_used (decl, complain) && !(complain & tf_error))
17472 	return error_mark_node;
17473       cleanup = cp_build_function_call_nary (fn, complain, arg, NULL_TREE);
17474       if (cleanup == error_mark_node)
17475 	return error_mark_node;
17476     }
17477   /* Handle ordinary C++ destructors.  */
17478   type = TREE_TYPE (decl);
17479   if (type_build_dtor_call (type))
17480     {
17481       int flags = LOOKUP_NORMAL|LOOKUP_NONVIRTUAL|LOOKUP_DESTRUCTOR;
17482       tree addr;
17483       tree call;
17484 
17485       if (TREE_CODE (type) == ARRAY_TYPE)
17486 	addr = decl;
17487       else
17488 	addr = build_address (decl);
17489 
17490       call = build_delete (input_location, TREE_TYPE (addr), addr,
17491 			   sfk_complete_destructor, flags, 0, complain);
17492       if (call == error_mark_node)
17493 	cleanup = error_mark_node;
17494       else if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
17495 	/* Discard the call.  */;
17496       else if (decl_maybe_constant_destruction (decl, type)
17497 	       && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
17498 	cxx_constant_dtor (call, decl);
17499       else if (cleanup)
17500 	cleanup = cp_build_compound_expr (cleanup, call, complain);
17501       else
17502 	cleanup = call;
17503     }
17504 
17505   /* build_delete sets the location of the destructor call to the
17506      current location, even though the destructor is going to be
17507      called later, at the end of the current scope.  This can lead to
17508      a "jumpy" behavior for users of debuggers when they step around
17509      the end of the block.  So let's unset the location of the
17510      destructor call instead.  */
17511   protected_set_expr_location (cleanup, UNKNOWN_LOCATION);
17512   if (cleanup && CONVERT_EXPR_P (cleanup))
17513     protected_set_expr_location (TREE_OPERAND (cleanup, 0), UNKNOWN_LOCATION);
17514 
17515   if (cleanup
17516       && DECL_P (decl)
17517       && !lookup_attribute ("warn_unused", TYPE_ATTRIBUTES (TREE_TYPE (decl)))
17518       /* Treat objects with destructors as used; the destructor may do
17519 	 something substantive.  */
17520       && !mark_used (decl, complain) && !(complain & tf_error))
17521     return error_mark_node;
17522 
17523   if (cleanup && cfun && !processing_template_decl
17524       && !expr_noexcept_p (cleanup, tf_none))
17525     cp_function_chain->throwing_cleanup = true;
17526 
17527   return cleanup;
17528 }
17529 
17530 
17531 /* Return the FUNCTION_TYPE that corresponds to MEMFNTYPE, which can be a
17532    FUNCTION_DECL, METHOD_TYPE, FUNCTION_TYPE, pointer or reference to
17533    METHOD_TYPE or FUNCTION_TYPE, or pointer to member function.  */
17534 
17535 tree
static_fn_type(tree memfntype)17536 static_fn_type (tree memfntype)
17537 {
17538   tree fntype;
17539   tree args;
17540 
17541   if (TYPE_PTRMEMFUNC_P (memfntype))
17542     memfntype = TYPE_PTRMEMFUNC_FN_TYPE (memfntype);
17543   if (INDIRECT_TYPE_P (memfntype)
17544       || TREE_CODE (memfntype) == FUNCTION_DECL)
17545     memfntype = TREE_TYPE (memfntype);
17546   if (TREE_CODE (memfntype) == FUNCTION_TYPE)
17547     return memfntype;
17548   gcc_assert (TREE_CODE (memfntype) == METHOD_TYPE);
17549   args = TYPE_ARG_TYPES (memfntype);
17550   fntype = build_function_type (TREE_TYPE (memfntype), TREE_CHAIN (args));
17551   fntype = apply_memfn_quals (fntype, type_memfn_quals (memfntype));
17552   fntype = (cp_build_type_attribute_variant
17553 	    (fntype, TYPE_ATTRIBUTES (memfntype)));
17554   fntype = cxx_copy_lang_qualifiers (fntype, memfntype);
17555   return fntype;
17556 }
17557 
17558 /* DECL was originally constructed as a non-static member function,
17559    but turned out to be static.  Update it accordingly.  */
17560 
17561 void
revert_static_member_fn(tree decl)17562 revert_static_member_fn (tree decl)
17563 {
17564   tree stype = static_fn_type (decl);
17565   cp_cv_quals quals = type_memfn_quals (stype);
17566   cp_ref_qualifier rqual = type_memfn_rqual (stype);
17567 
17568   if (quals != TYPE_UNQUALIFIED || rqual != REF_QUAL_NONE)
17569     stype = apply_memfn_quals (stype, TYPE_UNQUALIFIED, REF_QUAL_NONE);
17570 
17571   TREE_TYPE (decl) = stype;
17572 
17573   if (DECL_ARGUMENTS (decl))
17574     DECL_ARGUMENTS (decl) = DECL_CHAIN (DECL_ARGUMENTS (decl));
17575   DECL_STATIC_FUNCTION_P (decl) = 1;
17576 }
17577 
17578 /* Return which tree structure is used by T, or TS_CP_GENERIC if T is
17579    one of the language-independent trees.  */
17580 
17581 enum cp_tree_node_structure_enum
cp_tree_node_structure(union lang_tree_node * t)17582 cp_tree_node_structure (union lang_tree_node * t)
17583 {
17584   switch (TREE_CODE (&t->generic))
17585     {
17586     case ARGUMENT_PACK_SELECT:  return TS_CP_ARGUMENT_PACK_SELECT;
17587     case BASELINK:		return TS_CP_BASELINK;
17588     case CONSTRAINT_INFO:       return TS_CP_CONSTRAINT_INFO;
17589     case DEFERRED_NOEXCEPT:	return TS_CP_DEFERRED_NOEXCEPT;
17590     case DEFERRED_PARSE:	return TS_CP_DEFERRED_PARSE;
17591     case IDENTIFIER_NODE:	return TS_CP_IDENTIFIER;
17592     case LAMBDA_EXPR:		return TS_CP_LAMBDA_EXPR;
17593     case OVERLOAD:		return TS_CP_OVERLOAD;
17594     case PTRMEM_CST:		return TS_CP_PTRMEM;
17595     case STATIC_ASSERT:		return TS_CP_STATIC_ASSERT;
17596     case TEMPLATE_DECL:		return TS_CP_TEMPLATE_DECL;
17597     case TEMPLATE_INFO:		return TS_CP_TEMPLATE_INFO;
17598     case TEMPLATE_PARM_INDEX:	return TS_CP_TPI;
17599     case TRAIT_EXPR:		return TS_CP_TRAIT_EXPR;
17600     case USERDEF_LITERAL:	return TS_CP_USERDEF_LITERAL;
17601     default:			return TS_CP_GENERIC;
17602     }
17603 }
17604 
17605 /* Build the void_list_node (void_type_node having been created).  */
17606 tree
build_void_list_node(void)17607 build_void_list_node (void)
17608 {
17609   tree t = build_tree_list (NULL_TREE, void_type_node);
17610   return t;
17611 }
17612 
17613 bool
cp_missing_noreturn_ok_p(tree decl)17614 cp_missing_noreturn_ok_p (tree decl)
17615 {
17616   /* A missing noreturn is ok for the `main' function.  */
17617   return DECL_MAIN_P (decl);
17618 }
17619 
17620 /* Return the decl used to identify the COMDAT group into which DECL should
17621    be placed.  */
17622 
17623 tree
cxx_comdat_group(tree decl)17624 cxx_comdat_group (tree decl)
17625 {
17626   /* Virtual tables, construction virtual tables, and virtual table
17627      tables all go in a single COMDAT group, named after the primary
17628      virtual table.  */
17629   if (VAR_P (decl) && DECL_VTABLE_OR_VTT_P (decl))
17630     decl = CLASSTYPE_VTABLES (DECL_CONTEXT (decl));
17631   /* For all other DECLs, the COMDAT group is the mangled name of the
17632      declaration itself.  */
17633   else
17634     {
17635       while (DECL_THUNK_P (decl))
17636 	{
17637 	  /* If TARGET_USE_LOCAL_THUNK_ALIAS_P, use_thunk puts the thunk
17638 	     into the same section as the target function.  In that case
17639 	     we must return target's name.  */
17640 	  tree target = THUNK_TARGET (decl);
17641 	  if (TARGET_USE_LOCAL_THUNK_ALIAS_P (target)
17642 	      && DECL_SECTION_NAME (target) != NULL
17643 	      && DECL_ONE_ONLY (target))
17644 	    decl = target;
17645 	  else
17646 	    break;
17647 	}
17648     }
17649 
17650   return decl;
17651 }
17652 
17653 /* Returns the return type for FN as written by the user, which may include
17654    a placeholder for a deduced return type.  */
17655 
17656 tree
fndecl_declared_return_type(tree fn)17657 fndecl_declared_return_type (tree fn)
17658 {
17659   fn = STRIP_TEMPLATE (fn);
17660   if (FNDECL_USED_AUTO (fn))
17661     return DECL_SAVED_AUTO_RETURN_TYPE (fn);
17662 
17663   return TREE_TYPE (TREE_TYPE (fn));
17664 }
17665 
17666 /* Returns true iff DECL is a variable or function declared with an auto type
17667    that has not yet been deduced to a real type.  */
17668 
17669 bool
undeduced_auto_decl(tree decl)17670 undeduced_auto_decl (tree decl)
17671 {
17672   if (cxx_dialect < cxx11)
17673     return false;
17674   STRIP_ANY_LOCATION_WRAPPER (decl);
17675   return ((VAR_OR_FUNCTION_DECL_P (decl)
17676 	   || TREE_CODE (decl) == TEMPLATE_DECL)
17677 	  && type_uses_auto (TREE_TYPE (decl)));
17678 }
17679 
17680 /* Complain if DECL has an undeduced return type.  */
17681 
17682 bool
require_deduced_type(tree decl,tsubst_flags_t complain)17683 require_deduced_type (tree decl, tsubst_flags_t complain)
17684 {
17685   if (undeduced_auto_decl (decl))
17686     {
17687       if (TREE_NO_WARNING (decl) && seen_error ())
17688 	/* We probably already complained about deduction failure.  */;
17689       else if (complain & tf_error)
17690 	error ("use of %qD before deduction of %<auto%>", decl);
17691       return false;
17692     }
17693   return true;
17694 }
17695 
17696 /* Create a representation of the explicit-specifier with
17697    constant-expression of EXPR.  COMPLAIN is as for tsubst.  */
17698 
17699 tree
build_explicit_specifier(tree expr,tsubst_flags_t complain)17700 build_explicit_specifier (tree expr, tsubst_flags_t complain)
17701 {
17702   if (instantiation_dependent_expression_p (expr))
17703     /* Wait for instantiation, tsubst_function_decl will handle it.  */
17704     return expr;
17705 
17706   expr = build_converted_constant_bool_expr (expr, complain);
17707   expr = instantiate_non_dependent_expr_sfinae (expr, complain);
17708   expr = cxx_constant_value (expr);
17709   return expr;
17710 }
17711 
17712 #include "gt-cp-decl.h"
17713