1/* Handle initialization things in -*- C++ -*-
2   Copyright (C) 1987-2022 Free Software Foundation, Inc.
3   Contributed by Michael Tiemann (tiemann@cygnus.com)
4
5This file is part of GCC.
6
7GCC is free software; you can redistribute it and/or modify
8it under the terms of the GNU General Public License as published by
9the Free Software Foundation; either version 3, or (at your option)
10any later version.
11
12GCC is distributed in the hope that it will be useful,
13but WITHOUT ANY WARRANTY; without even the implied warranty of
14MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15GNU General Public License for more details.
16
17You should have received a copy of the GNU General Public License
18along with GCC; see the file COPYING3.  If not see
19<http://www.gnu.org/licenses/>.  */
20
21/* High-level class interface.  */
22
23#include "config.h"
24#include "system.h"
25#include "coretypes.h"
26#include "target.h"
27#include "cp-tree.h"
28#include "stringpool.h"
29#include "varasm.h"
30#include "gimplify.h"
31#include "c-family/c-ubsan.h"
32#include "intl.h"
33#include "stringpool.h"
34#include "attribs.h"
35#include "asan.h"
36#include "stor-layout.h"
37#include "pointer-query.h"
38
39static bool begin_init_stmts (tree *, tree *);
40static tree finish_init_stmts (bool, tree, tree);
41static void construct_virtual_base (tree, tree);
42static bool expand_aggr_init_1 (tree, tree, tree, tree, int, tsubst_flags_t);
43static bool expand_default_init (tree, tree, tree, tree, int, tsubst_flags_t);
44static int member_init_ok_or_else (tree, tree, tree);
45static void expand_virtual_init (tree, tree);
46static tree sort_mem_initializers (tree, tree);
47static tree initializing_context (tree);
48static void expand_cleanup_for_base (tree, tree);
49static tree dfs_initialize_vtbl_ptrs (tree, void *);
50static tree build_field_list (tree, tree, int *);
51static int diagnose_uninitialized_cst_or_ref_member_1 (tree, tree, bool, bool);
52
53static GTY(()) tree fn;
54
55/* We are about to generate some complex initialization code.
56   Conceptually, it is all a single expression.  However, we may want
57   to include conditionals, loops, and other such statement-level
58   constructs.  Therefore, we build the initialization code inside a
59   statement-expression.  This function starts such an expression.
60   STMT_EXPR_P and COMPOUND_STMT_P are filled in by this function;
61   pass them back to finish_init_stmts when the expression is
62   complete.  */
63
64static bool
65begin_init_stmts (tree *stmt_expr_p, tree *compound_stmt_p)
66{
67  bool is_global = !building_stmt_list_p ();
68
69  *stmt_expr_p = begin_stmt_expr ();
70  *compound_stmt_p = begin_compound_stmt (BCS_NO_SCOPE);
71
72  return is_global;
73}
74
75/* Finish out the statement-expression begun by the previous call to
76   begin_init_stmts.  Returns the statement-expression itself.  */
77
78static tree
79finish_init_stmts (bool is_global, tree stmt_expr, tree compound_stmt)
80{
81  finish_compound_stmt (compound_stmt);
82
83  stmt_expr = finish_stmt_expr (stmt_expr, true);
84
85  gcc_assert (!building_stmt_list_p () == is_global);
86
87  return stmt_expr;
88}
89
90/* Constructors */
91
92/* Called from initialize_vtbl_ptrs via dfs_walk.  BINFO is the base
93   which we want to initialize the vtable pointer for, DATA is
94   TREE_LIST whose TREE_VALUE is the this ptr expression.  */
95
96static tree
97dfs_initialize_vtbl_ptrs (tree binfo, void *data)
98{
99  if (!TYPE_CONTAINS_VPTR_P (BINFO_TYPE (binfo)))
100    return dfs_skip_bases;
101
102  if (!BINFO_PRIMARY_P (binfo) || BINFO_VIRTUAL_P (binfo))
103    {
104      tree base_ptr = TREE_VALUE ((tree) data);
105
106      base_ptr = build_base_path (PLUS_EXPR, base_ptr, binfo, /*nonnull=*/1,
107				  tf_warning_or_error);
108
109      expand_virtual_init (binfo, base_ptr);
110    }
111
112  return NULL_TREE;
113}
114
115/* Initialize all the vtable pointers in the object pointed to by
116   ADDR.  */
117
118void
119initialize_vtbl_ptrs (tree addr)
120{
121  tree list;
122  tree type;
123
124  type = TREE_TYPE (TREE_TYPE (addr));
125  list = build_tree_list (type, addr);
126
127  /* Walk through the hierarchy, initializing the vptr in each base
128     class.  We do these in pre-order because we can't find the virtual
129     bases for a class until we've initialized the vtbl for that
130     class.  */
131  dfs_walk_once (TYPE_BINFO (type), dfs_initialize_vtbl_ptrs, NULL, list);
132}
133
134/* Return an expression for the zero-initialization of an object with
135   type T.  This expression will either be a constant (in the case
136   that T is a scalar), or a CONSTRUCTOR (in the case that T is an
137   aggregate), or NULL (in the case that T does not require
138   initialization).  In either case, the value can be used as
139   DECL_INITIAL for a decl of the indicated TYPE; it is a valid static
140   initializer. If NELTS is non-NULL, and TYPE is an ARRAY_TYPE, NELTS
141   is the number of elements in the array.  If STATIC_STORAGE_P is
142   TRUE, initializers are only generated for entities for which
143   zero-initialization does not simply mean filling the storage with
144   zero bytes.  FIELD_SIZE, if non-NULL, is the bit size of the field,
145   subfields with bit positions at or above that bit size shouldn't
146   be added.  Note that this only works when the result is assigned
147   to a base COMPONENT_REF; if we only have a pointer to the base subobject,
148   expand_assignment will end up clearing the full size of TYPE.  */
149
150static tree
151build_zero_init_1 (tree type, tree nelts, bool static_storage_p,
152		   tree field_size)
153{
154  tree init = NULL_TREE;
155
156  /* [dcl.init]
157
158     To zero-initialize an object of type T means:
159
160     -- if T is a scalar type, the storage is set to the value of zero
161	converted to T.
162
163     -- if T is a non-union class type, the storage for each non-static
164	data member and each base-class subobject is zero-initialized.
165
166     -- if T is a union type, the storage for its first data member is
167	zero-initialized.
168
169     -- if T is an array type, the storage for each element is
170	zero-initialized.
171
172     -- if T is a reference type, no initialization is performed.  */
173
174  gcc_assert (nelts == NULL_TREE || TREE_CODE (nelts) == INTEGER_CST);
175
176  if (type == error_mark_node)
177    ;
178  else if (static_storage_p && zero_init_p (type))
179    /* In order to save space, we do not explicitly build initializers
180       for items that do not need them.  GCC's semantics are that
181       items with static storage duration that are not otherwise
182       initialized are initialized to zero.  */
183    ;
184  else if (TYPE_PTR_OR_PTRMEM_P (type))
185    init = fold (convert (type, nullptr_node));
186  else if (NULLPTR_TYPE_P (type))
187    init = build_int_cst (type, 0);
188  else if (SCALAR_TYPE_P (type))
189    init = build_zero_cst (type);
190  else if (RECORD_OR_UNION_CODE_P (TREE_CODE (type)))
191    {
192      tree field;
193      vec<constructor_elt, va_gc> *v = NULL;
194
195      /* Iterate over the fields, building initializations.  */
196      for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
197	{
198	  if (TREE_CODE (field) != FIELD_DECL)
199	    continue;
200
201	  if (TREE_TYPE (field) == error_mark_node)
202	    continue;
203
204	  /* Don't add virtual bases for base classes if they are beyond
205	     the size of the current field, that means it is present
206	     somewhere else in the object.  */
207	  if (field_size)
208	    {
209	      tree bitpos = bit_position (field);
210	      if (TREE_CODE (bitpos) == INTEGER_CST
211		  && !tree_int_cst_lt (bitpos, field_size))
212		continue;
213	    }
214
215	  /* Note that for class types there will be FIELD_DECLs
216	     corresponding to base classes as well.  Thus, iterating
217	     over TYPE_FIELDs will result in correct initialization of
218	     all of the subobjects.  */
219	  if (!static_storage_p || !zero_init_p (TREE_TYPE (field)))
220	    {
221	      tree new_field_size
222		= (DECL_FIELD_IS_BASE (field)
223		   && DECL_SIZE (field)
224		   && TREE_CODE (DECL_SIZE (field)) == INTEGER_CST)
225		  ? DECL_SIZE (field) : NULL_TREE;
226	      tree value = build_zero_init_1 (TREE_TYPE (field),
227					      /*nelts=*/NULL_TREE,
228					      static_storage_p,
229					      new_field_size);
230	      if (value)
231		CONSTRUCTOR_APPEND_ELT(v, field, value);
232	    }
233
234	  /* For unions, only the first field is initialized.  */
235	  if (TREE_CODE (type) == UNION_TYPE)
236	    break;
237	}
238
239      /* Build a constructor to contain the initializations.  */
240      init = build_constructor (type, v);
241    }
242  else if (TREE_CODE (type) == ARRAY_TYPE)
243    {
244      tree max_index;
245      vec<constructor_elt, va_gc> *v = NULL;
246
247      /* Iterate over the array elements, building initializations.  */
248      if (nelts)
249	max_index = fold_build2_loc (input_location, MINUS_EXPR,
250				     TREE_TYPE (nelts), nelts,
251				     build_one_cst (TREE_TYPE (nelts)));
252      /* Treat flexible array members like [0] arrays.  */
253      else if (TYPE_DOMAIN (type) == NULL_TREE)
254	return NULL_TREE;
255      else
256	max_index = array_type_nelts (type);
257
258      /* If we have an error_mark here, we should just return error mark
259	 as we don't know the size of the array yet.  */
260      if (max_index == error_mark_node)
261	return error_mark_node;
262      gcc_assert (TREE_CODE (max_index) == INTEGER_CST);
263
264      /* A zero-sized array, which is accepted as an extension, will
265	 have an upper bound of -1.  */
266      if (!integer_minus_onep (max_index))
267	{
268	  constructor_elt ce;
269
270	  /* If this is a one element array, we just use a regular init.  */
271	  if (integer_zerop (max_index))
272	    ce.index = size_zero_node;
273	  else
274	    ce.index = build2 (RANGE_EXPR, sizetype, size_zero_node,
275			       max_index);
276
277	  ce.value = build_zero_init_1 (TREE_TYPE (type), /*nelts=*/NULL_TREE,
278					static_storage_p, NULL_TREE);
279	  if (ce.value)
280	    {
281	      vec_alloc (v, 1);
282	      v->quick_push (ce);
283	    }
284	}
285
286      /* Build a constructor to contain the initializations.  */
287      init = build_constructor (type, v);
288    }
289  else if (VECTOR_TYPE_P (type))
290    init = build_zero_cst (type);
291  else
292    gcc_assert (TYPE_REF_P (type));
293
294  /* In all cases, the initializer is a constant.  */
295  if (init)
296    TREE_CONSTANT (init) = 1;
297
298  return init;
299}
300
301/* Return an expression for the zero-initialization of an object with
302   type T.  This expression will either be a constant (in the case
303   that T is a scalar), or a CONSTRUCTOR (in the case that T is an
304   aggregate), or NULL (in the case that T does not require
305   initialization).  In either case, the value can be used as
306   DECL_INITIAL for a decl of the indicated TYPE; it is a valid static
307   initializer. If NELTS is non-NULL, and TYPE is an ARRAY_TYPE, NELTS
308   is the number of elements in the array.  If STATIC_STORAGE_P is
309   TRUE, initializers are only generated for entities for which
310   zero-initialization does not simply mean filling the storage with
311   zero bytes.  */
312
313tree
314build_zero_init (tree type, tree nelts, bool static_storage_p)
315{
316  return build_zero_init_1 (type, nelts, static_storage_p, NULL_TREE);
317}
318
319/* Return a suitable initializer for value-initializing an object of type
320   TYPE, as described in [dcl.init].  */
321
322tree
323build_value_init (tree type, tsubst_flags_t complain)
324{
325  /* [dcl.init]
326
327     To value-initialize an object of type T means:
328
329     - if T is a class type (clause 9) with either no default constructor
330       (12.1) or a default constructor that is user-provided or deleted,
331       then the object is default-initialized;
332
333     - if T is a (possibly cv-qualified) class type without a user-provided
334       or deleted default constructor, then the object is zero-initialized
335       and the semantic constraints for default-initialization are checked,
336       and if T has a non-trivial default constructor, the object is
337       default-initialized;
338
339     - if T is an array type, then each element is value-initialized;
340
341     - otherwise, the object is zero-initialized.
342
343     A program that calls for default-initialization or
344     value-initialization of an entity of reference type is ill-formed.  */
345
346  if (CLASS_TYPE_P (type) && type_build_ctor_call (type))
347    {
348      tree ctor
349	= build_special_member_call (NULL_TREE, complete_ctor_identifier,
350				     NULL, type, LOOKUP_NORMAL, complain);
351      if (ctor == error_mark_node || TREE_CONSTANT (ctor))
352	return ctor;
353      if (processing_template_decl)
354	/* The AGGR_INIT_EXPR tweaking below breaks in templates.  */
355	return build_min (CAST_EXPR, type, NULL_TREE);
356      tree fn = NULL_TREE;
357      if (TREE_CODE (ctor) == CALL_EXPR)
358	fn = get_callee_fndecl (ctor);
359      ctor = build_aggr_init_expr (type, ctor);
360      if (fn && user_provided_p (fn))
361	return ctor;
362      else if (TYPE_HAS_COMPLEX_DFLT (type))
363	{
364	  /* This is a class that needs constructing, but doesn't have
365	     a user-provided constructor.  So we need to zero-initialize
366	     the object and then call the implicitly defined ctor.
367	     This will be handled in simplify_aggr_init_expr.  */
368	  AGGR_INIT_ZERO_FIRST (ctor) = 1;
369	  return ctor;
370	}
371    }
372
373  /* Discard any access checking during subobject initialization;
374     the checks are implied by the call to the ctor which we have
375     verified is OK (cpp0x/defaulted46.C).  */
376  push_deferring_access_checks (dk_deferred);
377  tree r = build_value_init_noctor (type, complain);
378  pop_deferring_access_checks ();
379  return r;
380}
381
382/* Like build_value_init, but don't call the constructor for TYPE.  Used
383   for base initializers.  */
384
385tree
386build_value_init_noctor (tree type, tsubst_flags_t complain)
387{
388  if (!COMPLETE_TYPE_P (type))
389    {
390      if (complain & tf_error)
391	error ("value-initialization of incomplete type %qT", type);
392      return error_mark_node;
393    }
394  /* FIXME the class and array cases should just use digest_init once it is
395     SFINAE-enabled.  */
396  if (CLASS_TYPE_P (type))
397    {
398      gcc_assert (!TYPE_HAS_COMPLEX_DFLT (type)
399		  || errorcount != 0);
400
401      if (TREE_CODE (type) != UNION_TYPE)
402	{
403	  tree field;
404	  vec<constructor_elt, va_gc> *v = NULL;
405
406	  /* Iterate over the fields, building initializations.  */
407	  for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
408	    {
409	      tree ftype, value;
410
411	      if (TREE_CODE (field) != FIELD_DECL)
412		continue;
413
414	      ftype = TREE_TYPE (field);
415
416	      if (ftype == error_mark_node)
417		continue;
418
419	      /* Ignore flexible array members for value initialization.  */
420	      if (TREE_CODE (ftype) == ARRAY_TYPE
421		  && !COMPLETE_TYPE_P (ftype)
422		  && !TYPE_DOMAIN (ftype)
423		  && COMPLETE_TYPE_P (TREE_TYPE (ftype))
424		  && (next_initializable_field (DECL_CHAIN (field))
425		      == NULL_TREE))
426		continue;
427
428	      /* Ignore unnamed zero-width bitfields.  */
429	      if (DECL_UNNAMED_BIT_FIELD (field)
430		  && integer_zerop (DECL_SIZE (field)))
431		continue;
432
433	      /* We could skip vfields and fields of types with
434		 user-defined constructors, but I think that won't improve
435		 performance at all; it should be simpler in general just
436		 to zero out the entire object than try to only zero the
437		 bits that actually need it.  */
438
439	      /* Note that for class types there will be FIELD_DECLs
440		 corresponding to base classes as well.  Thus, iterating
441		 over TYPE_FIELDs will result in correct initialization of
442		 all of the subobjects.  */
443	      value = build_value_init (ftype, complain);
444	      value = maybe_constant_init (value);
445
446	      if (value == error_mark_node)
447		return error_mark_node;
448
449	      CONSTRUCTOR_APPEND_ELT(v, field, value);
450
451	      /* We shouldn't have gotten here for anything that would need
452		 non-trivial initialization, and gimplify_init_ctor_preeval
453		 would need to be fixed to allow it.  */
454	      gcc_assert (TREE_CODE (value) != TARGET_EXPR
455			  && TREE_CODE (value) != AGGR_INIT_EXPR);
456	    }
457
458	  /* Build a constructor to contain the zero- initializations.  */
459	  return build_constructor (type, v);
460	}
461    }
462  else if (TREE_CODE (type) == ARRAY_TYPE)
463    {
464      vec<constructor_elt, va_gc> *v = NULL;
465
466      /* Iterate over the array elements, building initializations.  */
467      tree max_index = array_type_nelts (type);
468
469      /* If we have an error_mark here, we should just return error mark
470	 as we don't know the size of the array yet.  */
471      if (max_index == error_mark_node)
472	{
473	  if (complain & tf_error)
474	    error ("cannot value-initialize array of unknown bound %qT",
475		   type);
476	  return error_mark_node;
477	}
478      gcc_assert (TREE_CODE (max_index) == INTEGER_CST);
479
480      /* A zero-sized array, which is accepted as an extension, will
481	 have an upper bound of -1.  */
482      if (!tree_int_cst_equal (max_index, integer_minus_one_node))
483	{
484	  constructor_elt ce;
485
486	  /* If this is a one element array, we just use a regular init.  */
487	  if (tree_int_cst_equal (size_zero_node, max_index))
488	    ce.index = size_zero_node;
489	  else
490	    ce.index = build2 (RANGE_EXPR, sizetype, size_zero_node, max_index);
491
492	  ce.value = build_value_init (TREE_TYPE (type), complain);
493	  ce.value = maybe_constant_init (ce.value);
494	  if (ce.value == error_mark_node)
495	    return error_mark_node;
496
497	  vec_alloc (v, 1);
498	  v->quick_push (ce);
499
500	  /* We shouldn't have gotten here for anything that would need
501	     non-trivial initialization, and gimplify_init_ctor_preeval
502	     would need to be fixed to allow it.  */
503	  gcc_assert (TREE_CODE (ce.value) != TARGET_EXPR
504		      && TREE_CODE (ce.value) != AGGR_INIT_EXPR);
505	}
506
507      /* Build a constructor to contain the initializations.  */
508      return build_constructor (type, v);
509    }
510  else if (TREE_CODE (type) == FUNCTION_TYPE)
511    {
512      if (complain & tf_error)
513	error ("value-initialization of function type %qT", type);
514      return error_mark_node;
515    }
516  else if (TYPE_REF_P (type))
517    {
518      if (complain & tf_error)
519	error ("value-initialization of reference type %qT", type);
520      return error_mark_node;
521    }
522
523  return build_zero_init (type, NULL_TREE, /*static_storage_p=*/false);
524}
525
526/* Initialize current class with INIT, a TREE_LIST of arguments for
527   a target constructor.  If TREE_LIST is void_type_node, an empty
528   initializer list was given.  Return the target constructor.  */
529
530static tree
531perform_target_ctor (tree init)
532{
533  tree decl = current_class_ref;
534  tree type = current_class_type;
535
536  init = build_aggr_init (decl, init, LOOKUP_NORMAL|LOOKUP_DELEGATING_CONS,
537			  tf_warning_or_error);
538  finish_expr_stmt (init);
539  if (type_build_dtor_call (type))
540    {
541      tree expr = build_delete (input_location,
542				type, decl, sfk_complete_destructor,
543				LOOKUP_NORMAL
544				|LOOKUP_NONVIRTUAL
545				|LOOKUP_DESTRUCTOR,
546				0, tf_warning_or_error);
547      if (DECL_HAS_IN_CHARGE_PARM_P (current_function_decl))
548	{
549	  tree base = build_delete (input_location,
550				    type, decl, sfk_base_destructor,
551				    LOOKUP_NORMAL
552				    |LOOKUP_NONVIRTUAL
553				    |LOOKUP_DESTRUCTOR,
554				    0, tf_warning_or_error);
555	  expr = build_if_in_charge (expr, base);
556	}
557      if (expr != error_mark_node
558	  && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
559	finish_eh_cleanup (expr);
560    }
561  return init;
562}
563
564/* Instantiate the default member initializer of MEMBER, if needed.
565   Only get_nsdmi should use the return value of this function.  */
566
567static GTY((cache)) decl_tree_cache_map *nsdmi_inst;
568
569tree
570maybe_instantiate_nsdmi_init (tree member, tsubst_flags_t complain)
571{
572  tree init = DECL_INITIAL (member);
573  if (init && DECL_LANG_SPECIFIC (member) && DECL_TEMPLATE_INFO (member))
574    {
575      init = DECL_INITIAL (DECL_TI_TEMPLATE (member));
576      location_t expr_loc
577	= cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (member));
578      if (TREE_CODE (init) == DEFERRED_PARSE)
579	/* Unparsed.  */;
580      else if (tree *slot = hash_map_safe_get (nsdmi_inst, member))
581	init = *slot;
582      /* Check recursive instantiation.  */
583      else if (DECL_INSTANTIATING_NSDMI_P (member))
584	{
585	  if (complain & tf_error)
586	    error_at (expr_loc, "recursive instantiation of default member "
587		      "initializer for %qD", member);
588	  init = error_mark_node;
589	}
590      else
591	{
592	  cp_evaluated ev;
593
594	  location_t sloc = input_location;
595	  input_location = expr_loc;
596
597	  DECL_INSTANTIATING_NSDMI_P (member) = 1;
598
599	  bool pushed = false;
600	  tree ctx = DECL_CONTEXT (member);
601
602	  processing_template_decl_sentinel ptds (/*reset*/false);
603	  if (!currently_open_class (ctx))
604	    {
605	      if (!LOCAL_CLASS_P (ctx))
606		push_to_top_level ();
607	      else
608		/* push_to_top_level would lose the necessary function context,
609		   just reset processing_template_decl.  */
610		processing_template_decl = 0;
611	      push_nested_class (ctx);
612	      push_deferring_access_checks (dk_no_deferred);
613	      pushed = true;
614	    }
615
616	  inject_this_parameter (ctx, TYPE_UNQUALIFIED);
617
618	  start_lambda_scope (member);
619
620	  /* Do deferred instantiation of the NSDMI.  */
621	  init = (tsubst_copy_and_build
622		  (init, DECL_TI_ARGS (member),
623		   complain, member, /*function_p=*/false,
624		   /*integral_constant_expression_p=*/false));
625	  init = digest_nsdmi_init (member, init, complain);
626
627	  finish_lambda_scope ();
628
629	  DECL_INSTANTIATING_NSDMI_P (member) = 0;
630
631	  if (init != error_mark_node)
632	    hash_map_safe_put<hm_ggc> (nsdmi_inst, member, init);
633
634	  if (pushed)
635	    {
636	      pop_deferring_access_checks ();
637	      pop_nested_class ();
638	      if (!LOCAL_CLASS_P (ctx))
639		pop_from_top_level ();
640	    }
641
642	  input_location = sloc;
643	}
644    }
645
646  return init;
647}
648
649/* Return the non-static data initializer for FIELD_DECL MEMBER.  */
650
651tree
652get_nsdmi (tree member, bool in_ctor, tsubst_flags_t complain)
653{
654  tree save_ccp = current_class_ptr;
655  tree save_ccr = current_class_ref;
656
657  tree init = maybe_instantiate_nsdmi_init (member, complain);
658
659  if (init && TREE_CODE (init) == DEFERRED_PARSE)
660    {
661      if (complain & tf_error)
662	{
663	  error ("default member initializer for %qD required before the end "
664		 "of its enclosing class", member);
665	  inform (location_of (init), "defined here");
666	  DECL_INITIAL (member) = error_mark_node;
667	}
668      init = error_mark_node;
669    }
670
671  if (in_ctor)
672    {
673      current_class_ptr = save_ccp;
674      current_class_ref = save_ccr;
675    }
676  else
677    {
678      /* Use a PLACEHOLDER_EXPR when we don't have a 'this' parameter to
679	 refer to; constexpr evaluation knows what to do with it.  */
680      current_class_ref = build0 (PLACEHOLDER_EXPR, DECL_CONTEXT (member));
681      current_class_ptr = build_address (current_class_ref);
682    }
683
684  /* Clear processing_template_decl for sake of break_out_target_exprs;
685     INIT is always non-templated.  */
686  processing_template_decl_sentinel ptds;
687
688  /* Strip redundant TARGET_EXPR so we don't need to remap it, and
689     so the aggregate init code below will see a CONSTRUCTOR.  */
690  bool simple_target = (init && SIMPLE_TARGET_EXPR_P (init));
691  if (simple_target)
692    init = TARGET_EXPR_INITIAL (init);
693  init = break_out_target_exprs (init, /*loc*/true);
694  if (init && TREE_CODE (init) == TARGET_EXPR)
695    /* In a constructor, this expresses the full initialization, prevent
696       perform_member_init from calling another constructor (58162).  */
697    TARGET_EXPR_DIRECT_INIT_P (init) = in_ctor;
698  if (simple_target && TREE_CODE (init) != CONSTRUCTOR)
699    /* Now put it back so C++17 copy elision works.  */
700    init = get_target_expr (init);
701
702  current_class_ptr = save_ccp;
703  current_class_ref = save_ccr;
704  return init;
705}
706
707/* Diagnose the flexible array MEMBER if its INITializer is non-null
708   and return true if so.  Otherwise return false.  */
709
710bool
711maybe_reject_flexarray_init (tree member, tree init)
712{
713  tree type = TREE_TYPE (member);
714
715  if (!init
716      || TREE_CODE (type) != ARRAY_TYPE
717      || TYPE_DOMAIN (type))
718    return false;
719
720  /* Point at the flexible array member declaration if it's initialized
721     in-class, and at the ctor if it's initialized in a ctor member
722     initializer list.  */
723  location_t loc;
724  if (DECL_INITIAL (member) == init
725      || !current_function_decl
726      || DECL_DEFAULTED_FN (current_function_decl))
727    loc = DECL_SOURCE_LOCATION (member);
728  else
729    loc = DECL_SOURCE_LOCATION (current_function_decl);
730
731  error_at (loc, "initializer for flexible array member %q#D", member);
732  return true;
733}
734
735/* If INIT's value can come from a call to std::initializer_list<T>::begin,
736   return that function.  Otherwise, NULL_TREE.  */
737
738static tree
739find_list_begin (tree init)
740{
741  STRIP_NOPS (init);
742  while (TREE_CODE (init) == COMPOUND_EXPR)
743    init = TREE_OPERAND (init, 1);
744  STRIP_NOPS (init);
745  if (TREE_CODE (init) == COND_EXPR)
746    {
747      tree left = TREE_OPERAND (init, 1);
748      if (!left)
749	left = TREE_OPERAND (init, 0);
750      left = find_list_begin (left);
751      if (left)
752	return left;
753      return find_list_begin (TREE_OPERAND (init, 2));
754    }
755  if (TREE_CODE (init) == CALL_EXPR)
756    if (tree fn = get_callee_fndecl (init))
757      if (id_equal (DECL_NAME (fn), "begin")
758	  && is_std_init_list (DECL_CONTEXT (fn)))
759	return fn;
760  return NULL_TREE;
761}
762
763/* If INIT initializing MEMBER is copying the address of the underlying array
764   of an initializer_list, warn.  */
765
766static void
767maybe_warn_list_ctor (tree member, tree init)
768{
769  tree memtype = TREE_TYPE (member);
770  if (!init || !TYPE_PTR_P (memtype)
771      || !is_list_ctor (current_function_decl))
772    return;
773
774  tree parm = FUNCTION_FIRST_USER_PARMTYPE (current_function_decl);
775  parm = TREE_VALUE (parm);
776  tree initlist = non_reference (parm);
777
778  /* Do not warn if the parameter is an lvalue reference to non-const.  */
779  if (TYPE_REF_P (parm) && !TYPE_REF_IS_RVALUE (parm)
780      && !CP_TYPE_CONST_P (initlist))
781    return;
782
783  tree targs = CLASSTYPE_TI_ARGS (initlist);
784  tree elttype = TREE_VEC_ELT (targs, 0);
785
786  if (!same_type_ignoring_top_level_qualifiers_p
787      (TREE_TYPE (memtype), elttype))
788    return;
789
790  tree begin = find_list_begin (init);
791  if (!begin)
792    return;
793
794  location_t loc = cp_expr_loc_or_input_loc (init);
795  warning_at (loc, OPT_Winit_list_lifetime,
796	     "initializing %qD from %qE does not extend the lifetime "
797	     "of the underlying array", member, begin);
798}
799
800/* Data structure for find_uninit_fields_r, below.  */
801
802struct find_uninit_data {
803  /* The set tracking the yet-uninitialized members.  */
804  hash_set<tree> *uninitialized;
805  /* The data member we are currently initializing.  It can be either
806     a type (initializing a base class/delegating constructors), or
807     a COMPONENT_REF.  */
808  tree member;
809};
810
811/* walk_tree callback that warns about using uninitialized data in
812   a member-initializer-list.  */
813
814static tree
815find_uninit_fields_r (tree *tp, int *walk_subtrees, void *data)
816{
817  find_uninit_data *d = static_cast<find_uninit_data *>(data);
818  hash_set<tree> *uninitialized = d->uninitialized;
819  tree init = *tp;
820  const tree_code code = TREE_CODE (init);
821
822  /* No need to look into types or unevaluated operands.  */
823  if (TYPE_P (init) || unevaluated_p (code))
824    {
825      *walk_subtrees = false;
826      return NULL_TREE;
827    }
828
829  switch (code)
830    {
831    /* We'd need data flow info to avoid false positives.  */
832    case COND_EXPR:
833    case VEC_COND_EXPR:
834    case BIND_EXPR:
835    /* We might see a MODIFY_EXPR in cases like S() : a((b = 42)), c(b) { }
836       where the initializer for 'a' surreptitiously initializes 'b'.  Let's
837       not bother with these complicated scenarios in the front end.  */
838    case MODIFY_EXPR:
839    /* Don't attempt to handle statement-expressions, either.  */
840    case STATEMENT_LIST:
841      uninitialized->empty ();
842      gcc_fallthrough ();
843    /* If we're just taking the address of an object, it doesn't matter
844       whether it's been initialized.  */
845    case ADDR_EXPR:
846      *walk_subtrees = false;
847      return NULL_TREE;
848    default:
849      break;
850    }
851
852  /* We'd need data flow info to avoid false positives.  */
853  if (truth_value_p (code))
854    goto give_up;
855  /* Attempt to handle a simple a{b}, but no more.  */
856  else if (BRACE_ENCLOSED_INITIALIZER_P (init))
857    {
858      if (CONSTRUCTOR_NELTS (init) == 1
859	  && !BRACE_ENCLOSED_INITIALIZER_P (CONSTRUCTOR_ELT (init, 0)->value))
860	init = CONSTRUCTOR_ELT (init, 0)->value;
861      else
862	goto give_up;
863    }
864  /* Warn about uninitialized 'this'.  */
865  else if (code == CALL_EXPR)
866    {
867      tree fn = get_callee_fndecl (init);
868      if (fn && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
869	{
870	  tree op = CALL_EXPR_ARG (init, 0);
871	  if (TREE_CODE (op) == ADDR_EXPR)
872	    op = TREE_OPERAND (op, 0);
873	  temp_override<tree> ovr (d->member, DECL_ARGUMENTS (fn));
874	  cp_walk_tree_without_duplicates (&op, find_uninit_fields_r, data);
875	}
876      /* Functions (whether static or nonstatic member) may have side effects
877	 and initialize other members; it's not the front end's job to try to
878	 figure it out.  But don't give up for constructors: we still want to
879	 warn when initializing base classes:
880
881	   struct D : public B {
882	     int x;
883	     D() : B(x) {}
884	   };
885
886	 so carry on to detect that 'x' is used uninitialized.  */
887      if (!fn || !DECL_CONSTRUCTOR_P (fn))
888	goto give_up;
889    }
890
891  /* If we find FIELD in the uninitialized set, we warn.  */
892  if (code == COMPONENT_REF)
893    {
894      tree field = TREE_OPERAND (init, 1);
895      tree type = TYPE_P (d->member) ? d->member : TREE_TYPE (d->member);
896
897      /* We're initializing a reference member with itself.  */
898      if (TYPE_REF_P (type) && cp_tree_equal (d->member, init))
899	warning_at (EXPR_LOCATION (init), OPT_Winit_self,
900		    "%qD is initialized with itself", field);
901      else if (cp_tree_equal (TREE_OPERAND (init, 0), current_class_ref)
902	       && uninitialized->contains (field))
903	{
904	  if (TYPE_REF_P (TREE_TYPE (field)))
905	    warning_at (EXPR_LOCATION (init), OPT_Wuninitialized,
906			"reference %qD is not yet bound to a value when used "
907			"here", field);
908	  else if (!INDIRECT_TYPE_P (type) || is_this_parameter (d->member))
909	    warning_at (EXPR_LOCATION (init), OPT_Wuninitialized,
910			"member %qD is used uninitialized", field);
911	  *walk_subtrees = false;
912	}
913    }
914
915  return NULL_TREE;
916
917give_up:
918  *walk_subtrees = false;
919  uninitialized->empty ();
920  return integer_zero_node;
921}
922
923/* Wrapper around find_uninit_fields_r above.  */
924
925static void
926find_uninit_fields (tree *t, hash_set<tree> *uninitialized, tree member)
927{
928  if (!uninitialized->is_empty ())
929    {
930      find_uninit_data data = { uninitialized, member };
931      cp_walk_tree_without_duplicates (t, find_uninit_fields_r, &data);
932    }
933}
934
935/* Initialize MEMBER, a FIELD_DECL, with INIT, a TREE_LIST of
936   arguments.  If TREE_LIST is void_type_node, an empty initializer
937   list was given; if NULL_TREE no initializer was given.  UNINITIALIZED
938   is the hash set that tracks uninitialized fields.  */
939
940static void
941perform_member_init (tree member, tree init, hash_set<tree> &uninitialized)
942{
943  tree decl;
944  tree type = TREE_TYPE (member);
945
946  /* Use the non-static data member initializer if there was no
947     mem-initializer for this field.  */
948  if (init == NULL_TREE)
949    init = get_nsdmi (member, /*ctor*/true, tf_warning_or_error);
950
951  if (init == error_mark_node)
952    return;
953
954  /* Effective C++ rule 12 requires that all data members be
955     initialized.  */
956  if (warn_ecpp && init == NULL_TREE && TREE_CODE (type) != ARRAY_TYPE)
957    warning_at (DECL_SOURCE_LOCATION (current_function_decl), OPT_Weffc__,
958		"%qD should be initialized in the member initialization list",
959		member);
960
961  /* Get an lvalue for the data member.  */
962  decl = build_class_member_access_expr (current_class_ref, member,
963					 /*access_path=*/NULL_TREE,
964					 /*preserve_reference=*/true,
965					 tf_warning_or_error);
966  if (decl == error_mark_node)
967    return;
968
969  if ((warn_init_self || warn_uninitialized)
970      && init
971      && TREE_CODE (init) == TREE_LIST
972      && TREE_CHAIN (init) == NULL_TREE)
973    {
974      tree val = TREE_VALUE (init);
975      /* Handle references.  */
976      if (REFERENCE_REF_P (val))
977	val = TREE_OPERAND (val, 0);
978      if (TREE_CODE (val) == COMPONENT_REF && TREE_OPERAND (val, 1) == member
979	  && TREE_OPERAND (val, 0) == current_class_ref)
980	warning_at (DECL_SOURCE_LOCATION (current_function_decl),
981		    OPT_Winit_self, "%qD is initialized with itself",
982		    member);
983      else
984	find_uninit_fields (&val, &uninitialized, decl);
985    }
986
987  if (array_of_unknown_bound_p (type))
988    {
989      maybe_reject_flexarray_init (member, init);
990      return;
991    }
992
993  if (init && TREE_CODE (init) == TREE_LIST)
994    {
995      /* A(): a{e} */
996      if (DIRECT_LIST_INIT_P (TREE_VALUE (init)))
997	init = build_x_compound_expr_from_list (init, ELK_MEM_INIT,
998						tf_warning_or_error);
999      /* We are trying to initialize an array from a ()-list.  If we
1000	 should attempt to do so, conjure up a CONSTRUCTOR.  */
1001      else if (TREE_CODE (type) == ARRAY_TYPE
1002	       /* P0960 is a C++20 feature.  */
1003	       && cxx_dialect >= cxx20)
1004	init = do_aggregate_paren_init (init, type);
1005      else if (!CLASS_TYPE_P (type))
1006	init = build_x_compound_expr_from_list (init, ELK_MEM_INIT,
1007						tf_warning_or_error);
1008      /* If we're initializing a class from a ()-list, leave the TREE_LIST
1009	 alone: we might call an appropriate constructor, or (in C++20)
1010	 do aggregate-initialization.  */
1011    }
1012
1013  /* Assume we are initializing the member.  */
1014  bool member_initialized_p = true;
1015
1016  if (init == void_type_node)
1017    {
1018      /* mem() means value-initialization.  */
1019      if (TREE_CODE (type) == ARRAY_TYPE)
1020	{
1021	  init = build_vec_init_expr (type, init, tf_warning_or_error);
1022	  init = build2 (INIT_EXPR, type, decl, init);
1023	  finish_expr_stmt (init);
1024	}
1025      else
1026	{
1027	  tree value = build_value_init (type, tf_warning_or_error);
1028	  if (value == error_mark_node)
1029	    return;
1030	  init = build2 (INIT_EXPR, type, decl, value);
1031	  finish_expr_stmt (init);
1032	}
1033    }
1034  /* Deal with this here, as we will get confused if we try to call the
1035     assignment op for an anonymous union.  This can happen in a
1036     synthesized copy constructor.  */
1037  else if (ANON_AGGR_TYPE_P (type))
1038    {
1039      if (init)
1040	{
1041	  init = build2 (INIT_EXPR, type, decl, TREE_VALUE (init));
1042	  finish_expr_stmt (init);
1043	}
1044    }
1045  else if (init
1046	   && (TYPE_REF_P (type)
1047	       || (TREE_CODE (init) == CONSTRUCTOR
1048		   && (CP_AGGREGATE_TYPE_P (type)
1049		       || is_std_init_list (type)))))
1050    {
1051      /* With references and list-initialization, we need to deal with
1052	 extending temporary lifetimes.  12.2p5: "A temporary bound to a
1053	 reference member in a constructor���s ctor-initializer (12.6.2)
1054	 persists until the constructor exits."  */
1055      unsigned i; tree t;
1056      releasing_vec cleanups;
1057      if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (init), type))
1058	{
1059	  if (BRACE_ENCLOSED_INITIALIZER_P (init)
1060	      && CP_AGGREGATE_TYPE_P (type))
1061	    init = reshape_init (type, init, tf_warning_or_error);
1062	  init = digest_init (type, init, tf_warning_or_error);
1063	}
1064      if (init == error_mark_node)
1065	return;
1066      if (is_empty_field (member)
1067	  && !TREE_SIDE_EFFECTS (init))
1068	/* Don't add trivial initialization of an empty base/field, as they
1069	   might not be ordered the way the back-end expects.  */
1070	return;
1071      /* A FIELD_DECL doesn't really have a suitable lifetime, but
1072	 make_temporary_var_for_ref_to_temp will treat it as automatic and
1073	 set_up_extended_ref_temp wants to use the decl in a warning.  */
1074      init = extend_ref_init_temps (member, init, &cleanups);
1075      if (TREE_CODE (type) == ARRAY_TYPE
1076	  && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (type)))
1077	init = build_vec_init_expr (type, init, tf_warning_or_error);
1078      init = build2 (INIT_EXPR, type, decl, init);
1079      finish_expr_stmt (init);
1080      FOR_EACH_VEC_ELT (*cleanups, i, t)
1081	push_cleanup (NULL_TREE, t, false);
1082    }
1083  else if (type_build_ctor_call (type)
1084	   || (init && CLASS_TYPE_P (strip_array_types (type))))
1085    {
1086      if (TREE_CODE (type) == ARRAY_TYPE)
1087	{
1088	  if (init == NULL_TREE
1089	      || same_type_ignoring_top_level_qualifiers_p (type,
1090							    TREE_TYPE (init)))
1091	    {
1092	      if (TYPE_DOMAIN (type) && TYPE_MAX_VALUE (TYPE_DOMAIN (type)))
1093		{
1094		  /* Initialize the array only if it's not a flexible
1095		     array member (i.e., if it has an upper bound).  */
1096		  init = build_vec_init_expr (type, init, tf_warning_or_error);
1097		  init = build2 (INIT_EXPR, type, decl, init);
1098		  finish_expr_stmt (init);
1099		}
1100	    }
1101	  else
1102	    error ("invalid initializer for array member %q#D", member);
1103	}
1104      else
1105	{
1106	  int flags = LOOKUP_NORMAL;
1107	  if (DECL_DEFAULTED_FN (current_function_decl))
1108	    flags |= LOOKUP_DEFAULTED;
1109	  if (CP_TYPE_CONST_P (type)
1110	      && init == NULL_TREE
1111	      && default_init_uninitialized_part (type))
1112	    {
1113	      /* TYPE_NEEDS_CONSTRUCTING can be set just because we have a
1114		 vtable; still give this diagnostic.  */
1115	      auto_diagnostic_group d;
1116	      if (permerror (DECL_SOURCE_LOCATION (current_function_decl),
1117			     "uninitialized const member in %q#T", type))
1118		inform (DECL_SOURCE_LOCATION (member),
1119			"%q#D should be initialized", member );
1120	    }
1121	  finish_expr_stmt (build_aggr_init (decl, init, flags,
1122					     tf_warning_or_error));
1123	}
1124    }
1125  else
1126    {
1127      if (init == NULL_TREE)
1128	{
1129	  tree core_type;
1130	  /* member traversal: note it leaves init NULL */
1131	  if (TYPE_REF_P (type))
1132	    {
1133	      auto_diagnostic_group d;
1134	      if (permerror (DECL_SOURCE_LOCATION (current_function_decl),
1135			     "uninitialized reference member in %q#T", type))
1136		inform (DECL_SOURCE_LOCATION (member),
1137			"%q#D should be initialized", member);
1138	    }
1139	  else if (CP_TYPE_CONST_P (type))
1140	    {
1141	      auto_diagnostic_group d;
1142	      if (permerror (DECL_SOURCE_LOCATION (current_function_decl),
1143			     "uninitialized const member in %q#T", type))
1144		  inform (DECL_SOURCE_LOCATION (member),
1145			  "%q#D should be initialized", member );
1146	    }
1147
1148	  core_type = strip_array_types (type);
1149
1150	  if (CLASS_TYPE_P (core_type)
1151	      && (CLASSTYPE_READONLY_FIELDS_NEED_INIT (core_type)
1152		  || CLASSTYPE_REF_FIELDS_NEED_INIT (core_type)))
1153	    diagnose_uninitialized_cst_or_ref_member (core_type,
1154						      /*using_new=*/false,
1155						      /*complain=*/true);
1156
1157	  /* We left the member uninitialized.  */
1158	  member_initialized_p = false;
1159	}
1160
1161      maybe_warn_list_ctor (member, init);
1162
1163      if (init)
1164	finish_expr_stmt (cp_build_modify_expr (input_location, decl,
1165						INIT_EXPR, init,
1166						tf_warning_or_error));
1167    }
1168
1169  if (member_initialized_p && warn_uninitialized)
1170    /* This member is now initialized, remove it from the uninitialized
1171       set.  */
1172    uninitialized.remove (member);
1173
1174  if (type_build_dtor_call (type))
1175    {
1176      tree expr;
1177
1178      expr = build_class_member_access_expr (current_class_ref, member,
1179					     /*access_path=*/NULL_TREE,
1180					     /*preserve_reference=*/false,
1181					     tf_warning_or_error);
1182      expr = build_delete (input_location,
1183			   type, expr, sfk_complete_destructor,
1184			   LOOKUP_NONVIRTUAL|LOOKUP_DESTRUCTOR, 0,
1185			   tf_warning_or_error);
1186
1187      if (expr != error_mark_node
1188	  && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
1189	finish_eh_cleanup (expr);
1190    }
1191}
1192
1193/* Returns a TREE_LIST containing (as the TREE_PURPOSE of each node) all
1194   the FIELD_DECLs on the TYPE_FIELDS list for T, in reverse order.  */
1195
1196static tree
1197build_field_list (tree t, tree list, int *uses_unions_or_anon_p)
1198{
1199  tree fields;
1200
1201  /* Note whether or not T is a union.  */
1202  if (TREE_CODE (t) == UNION_TYPE)
1203    *uses_unions_or_anon_p = 1;
1204
1205  for (fields = TYPE_FIELDS (t); fields; fields = DECL_CHAIN (fields))
1206    {
1207      tree fieldtype;
1208
1209      /* Skip CONST_DECLs for enumeration constants and so forth.  */
1210      if (TREE_CODE (fields) != FIELD_DECL || DECL_ARTIFICIAL (fields))
1211	continue;
1212
1213      fieldtype = TREE_TYPE (fields);
1214
1215      /* For an anonymous struct or union, we must recursively
1216	 consider the fields of the anonymous type.  They can be
1217	 directly initialized from the constructor.  */
1218      if (ANON_AGGR_TYPE_P (fieldtype))
1219	{
1220	  /* Add this field itself.  Synthesized copy constructors
1221	     initialize the entire aggregate.  */
1222	  list = tree_cons (fields, NULL_TREE, list);
1223	  /* And now add the fields in the anonymous aggregate.  */
1224	  list = build_field_list (fieldtype, list, uses_unions_or_anon_p);
1225	  *uses_unions_or_anon_p = 1;
1226	}
1227      /* Add this field.  */
1228      else if (DECL_NAME (fields))
1229	list = tree_cons (fields, NULL_TREE, list);
1230    }
1231
1232  return list;
1233}
1234
1235/* Return the innermost aggregate scope for FIELD, whether that is
1236   the enclosing class or an anonymous aggregate within it.  */
1237
1238static tree
1239innermost_aggr_scope (tree field)
1240{
1241  if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
1242    return TREE_TYPE (field);
1243  else
1244    return DECL_CONTEXT (field);
1245}
1246
1247/* The MEM_INITS are a TREE_LIST.  The TREE_PURPOSE of each list gives
1248   a FIELD_DECL or BINFO in T that needs initialization.  The
1249   TREE_VALUE gives the initializer, or list of initializer arguments.
1250
1251   Return a TREE_LIST containing all of the initializations required
1252   for T, in the order in which they should be performed.  The output
1253   list has the same format as the input.  */
1254
1255static tree
1256sort_mem_initializers (tree t, tree mem_inits)
1257{
1258  tree init;
1259  tree base, binfo, base_binfo;
1260  tree sorted_inits;
1261  tree next_subobject;
1262  vec<tree, va_gc> *vbases;
1263  int i;
1264  int uses_unions_or_anon_p = 0;
1265
1266  /* Build up a list of initializations.  The TREE_PURPOSE of entry
1267     will be the subobject (a FIELD_DECL or BINFO) to initialize.  The
1268     TREE_VALUE will be the constructor arguments, or NULL if no
1269     explicit initialization was provided.  */
1270  sorted_inits = NULL_TREE;
1271
1272  /* Process the virtual bases.  */
1273  for (vbases = CLASSTYPE_VBASECLASSES (t), i = 0;
1274       vec_safe_iterate (vbases, i, &base); i++)
1275    sorted_inits = tree_cons (base, NULL_TREE, sorted_inits);
1276
1277  /* Process the direct bases.  */
1278  for (binfo = TYPE_BINFO (t), i = 0;
1279       BINFO_BASE_ITERATE (binfo, i, base_binfo); ++i)
1280    if (!BINFO_VIRTUAL_P (base_binfo))
1281      sorted_inits = tree_cons (base_binfo, NULL_TREE, sorted_inits);
1282
1283  /* Process the non-static data members.  */
1284  sorted_inits = build_field_list (t, sorted_inits, &uses_unions_or_anon_p);
1285  /* Reverse the entire list of initializations, so that they are in
1286     the order that they will actually be performed.  */
1287  sorted_inits = nreverse (sorted_inits);
1288
1289  /* If the user presented the initializers in an order different from
1290     that in which they will actually occur, we issue a warning.  Keep
1291     track of the next subobject which can be explicitly initialized
1292     without issuing a warning.  */
1293  next_subobject = sorted_inits;
1294
1295  /* Go through the explicit initializers, filling in TREE_PURPOSE in
1296     the SORTED_INITS.  */
1297  for (init = mem_inits; init; init = TREE_CHAIN (init))
1298    {
1299      tree subobject;
1300      tree subobject_init;
1301
1302      subobject = TREE_PURPOSE (init);
1303
1304      /* If the explicit initializers are in sorted order, then
1305	 SUBOBJECT will be NEXT_SUBOBJECT, or something following
1306	 it.  */
1307      for (subobject_init = next_subobject;
1308	   subobject_init;
1309	   subobject_init = TREE_CHAIN (subobject_init))
1310	if (TREE_PURPOSE (subobject_init) == subobject)
1311	  break;
1312
1313      /* Issue a warning if the explicit initializer order does not
1314	 match that which will actually occur.
1315	 ??? Are all these on the correct lines?  */
1316      if (warn_reorder && !subobject_init)
1317	{
1318	  if (TREE_CODE (TREE_PURPOSE (next_subobject)) == FIELD_DECL)
1319	    warning_at (DECL_SOURCE_LOCATION (TREE_PURPOSE (next_subobject)),
1320			OPT_Wreorder, "%qD will be initialized after",
1321			TREE_PURPOSE (next_subobject));
1322	  else
1323	    warning (OPT_Wreorder, "base %qT will be initialized after",
1324		     TREE_PURPOSE (next_subobject));
1325	  if (TREE_CODE (subobject) == FIELD_DECL)
1326	    warning_at (DECL_SOURCE_LOCATION (subobject),
1327			OPT_Wreorder, "  %q#D", subobject);
1328	  else
1329	    warning (OPT_Wreorder, "  base %qT", subobject);
1330	  warning_at (DECL_SOURCE_LOCATION (current_function_decl),
1331		      OPT_Wreorder, "  when initialized here");
1332	}
1333
1334      /* Look again, from the beginning of the list.  */
1335      if (!subobject_init)
1336	{
1337	  subobject_init = sorted_inits;
1338	  while (TREE_PURPOSE (subobject_init) != subobject)
1339	    subobject_init = TREE_CHAIN (subobject_init);
1340	}
1341
1342      /* It is invalid to initialize the same subobject more than
1343	 once.  */
1344      if (TREE_VALUE (subobject_init))
1345	{
1346	  if (TREE_CODE (subobject) == FIELD_DECL)
1347	    error_at (DECL_SOURCE_LOCATION (current_function_decl),
1348		      "multiple initializations given for %qD",
1349		      subobject);
1350	  else
1351	    error_at (DECL_SOURCE_LOCATION (current_function_decl),
1352		      "multiple initializations given for base %qT",
1353		      subobject);
1354	}
1355
1356      /* Record the initialization.  */
1357      TREE_VALUE (subobject_init) = TREE_VALUE (init);
1358      /* Carry over the dummy TREE_TYPE node containing the source location.  */
1359      TREE_TYPE (subobject_init) = TREE_TYPE (init);
1360      next_subobject = subobject_init;
1361    }
1362
1363  /* [class.base.init]
1364
1365     If a ctor-initializer specifies more than one mem-initializer for
1366     multiple members of the same union (including members of
1367     anonymous unions), the ctor-initializer is ill-formed.
1368
1369     Here we also splice out uninitialized union members.  */
1370  if (uses_unions_or_anon_p)
1371    {
1372      tree *last_p = NULL;
1373      tree *p;
1374      for (p = &sorted_inits; *p; )
1375	{
1376	  tree field;
1377	  tree ctx;
1378
1379	  init = *p;
1380
1381	  field = TREE_PURPOSE (init);
1382
1383	  /* Skip base classes.  */
1384	  if (TREE_CODE (field) != FIELD_DECL)
1385	    goto next;
1386
1387	  /* If this is an anonymous aggregate with no explicit initializer,
1388	     splice it out.  */
1389	  if (!TREE_VALUE (init) && ANON_AGGR_TYPE_P (TREE_TYPE (field)))
1390	    goto splice;
1391
1392	  /* See if this field is a member of a union, or a member of a
1393	     structure contained in a union, etc.  */
1394	  ctx = innermost_aggr_scope (field);
1395
1396	  /* If this field is not a member of a union, skip it.  */
1397	  if (TREE_CODE (ctx) != UNION_TYPE
1398	      && !ANON_AGGR_TYPE_P (ctx))
1399	    goto next;
1400
1401	  /* If this union member has no explicit initializer and no NSDMI,
1402	     splice it out.  */
1403	  if (TREE_VALUE (init) || DECL_INITIAL (field))
1404	    /* OK.  */;
1405	  else
1406	    goto splice;
1407
1408	  /* It's only an error if we have two initializers for the same
1409	     union type.  */
1410	  if (!last_p)
1411	    {
1412	      last_p = p;
1413	      goto next;
1414	    }
1415
1416	  /* See if LAST_FIELD and the field initialized by INIT are
1417	     members of the same union (or the union itself). If so, there's
1418	     a problem, unless they're actually members of the same structure
1419	     which is itself a member of a union.  For example, given:
1420
1421	       union { struct { int i; int j; }; };
1422
1423	     initializing both `i' and `j' makes sense.  */
1424	  ctx = common_enclosing_class
1425	    (innermost_aggr_scope (field),
1426	     innermost_aggr_scope (TREE_PURPOSE (*last_p)));
1427
1428	  if (ctx && (TREE_CODE (ctx) == UNION_TYPE
1429		      || ctx == TREE_TYPE (TREE_PURPOSE (*last_p))))
1430	    {
1431	      /* A mem-initializer hides an NSDMI.  */
1432	      if (TREE_VALUE (init) && !TREE_VALUE (*last_p))
1433		*last_p = TREE_CHAIN (*last_p);
1434	      else if (TREE_VALUE (*last_p) && !TREE_VALUE (init))
1435		goto splice;
1436	      else
1437		{
1438		  error_at (DECL_SOURCE_LOCATION (current_function_decl),
1439			    "initializations for multiple members of %qT",
1440			    ctx);
1441		  goto splice;
1442		}
1443	    }
1444
1445	  last_p = p;
1446
1447	next:
1448	  p = &TREE_CHAIN (*p);
1449	  continue;
1450	splice:
1451	  *p = TREE_CHAIN (*p);
1452	  continue;
1453	}
1454    }
1455
1456  return sorted_inits;
1457}
1458
1459/* Callback for cp_walk_tree to mark all PARM_DECLs in a tree as read.  */
1460
1461static tree
1462mark_exp_read_r (tree *tp, int *, void *)
1463{
1464  tree t = *tp;
1465  if (TREE_CODE (t) == PARM_DECL)
1466    mark_exp_read (t);
1467  return NULL_TREE;
1468}
1469
1470/* Initialize all bases and members of CURRENT_CLASS_TYPE.  MEM_INITS
1471   is a TREE_LIST giving the explicit mem-initializer-list for the
1472   constructor.  The TREE_PURPOSE of each entry is a subobject (a
1473   FIELD_DECL or a BINFO) of the CURRENT_CLASS_TYPE.  The TREE_VALUE
1474   is a TREE_LIST giving the arguments to the constructor or
1475   void_type_node for an empty list of arguments.  */
1476
1477void
1478emit_mem_initializers (tree mem_inits)
1479{
1480  int flags = LOOKUP_NORMAL;
1481
1482  /* We will already have issued an error message about the fact that
1483     the type is incomplete.  */
1484  if (!COMPLETE_TYPE_P (current_class_type))
1485    return;
1486
1487  /* Keep a set holding fields that are not initialized.  */
1488  hash_set<tree> uninitialized;
1489
1490  /* Initially that is all of them.  */
1491  if (warn_uninitialized)
1492    for (tree f = next_initializable_field (TYPE_FIELDS (current_class_type));
1493	 f != NULL_TREE;
1494	 f = next_initializable_field (DECL_CHAIN (f)))
1495      if (!DECL_ARTIFICIAL (f)
1496	  && !is_really_empty_class (TREE_TYPE (f), /*ignore_vptr*/false))
1497	uninitialized.add (f);
1498
1499  if (mem_inits
1500      && TYPE_P (TREE_PURPOSE (mem_inits))
1501      && same_type_p (TREE_PURPOSE (mem_inits), current_class_type))
1502    {
1503      /* Delegating constructor. */
1504      gcc_assert (TREE_CHAIN (mem_inits) == NULL_TREE);
1505      tree ctor = perform_target_ctor (TREE_VALUE (mem_inits));
1506      find_uninit_fields (&ctor, &uninitialized, current_class_type);
1507      return;
1508    }
1509
1510  if (DECL_DEFAULTED_FN (current_function_decl)
1511      && ! DECL_INHERITED_CTOR (current_function_decl))
1512    flags |= LOOKUP_DEFAULTED;
1513
1514  /* Sort the mem-initializers into the order in which the
1515     initializations should be performed.  */
1516  mem_inits = sort_mem_initializers (current_class_type, mem_inits);
1517
1518  in_base_initializer = 1;
1519
1520  /* Initialize base classes.  */
1521  for (; (mem_inits
1522	  && TREE_CODE (TREE_PURPOSE (mem_inits)) != FIELD_DECL);
1523       mem_inits = TREE_CHAIN (mem_inits))
1524    {
1525      tree subobject = TREE_PURPOSE (mem_inits);
1526      tree arguments = TREE_VALUE (mem_inits);
1527
1528      /* We already have issued an error message.  */
1529      if (arguments == error_mark_node)
1530	continue;
1531
1532      /* Suppress access control when calling the inherited ctor.  */
1533      bool inherited_base = (DECL_INHERITED_CTOR (current_function_decl)
1534			     && flag_new_inheriting_ctors
1535			     && arguments);
1536      if (inherited_base)
1537	push_deferring_access_checks (dk_deferred);
1538
1539      if (arguments == NULL_TREE)
1540	{
1541	  /* If these initializations are taking place in a copy constructor,
1542	     the base class should probably be explicitly initialized if there
1543	     is a user-defined constructor in the base class (other than the
1544	     default constructor, which will be called anyway).  */
1545	  if (extra_warnings
1546	      && DECL_COPY_CONSTRUCTOR_P (current_function_decl)
1547	      && type_has_user_nondefault_constructor (BINFO_TYPE (subobject)))
1548	    warning_at (DECL_SOURCE_LOCATION (current_function_decl),
1549			OPT_Wextra, "base class %q#T should be explicitly "
1550			"initialized in the copy constructor",
1551			BINFO_TYPE (subobject));
1552	}
1553
1554      /* Initialize the base.  */
1555      if (!BINFO_VIRTUAL_P (subobject))
1556	{
1557	  tree base_addr;
1558
1559	  base_addr = build_base_path (PLUS_EXPR, current_class_ptr,
1560				       subobject, 1, tf_warning_or_error);
1561	  expand_aggr_init_1 (subobject, NULL_TREE,
1562			      cp_build_fold_indirect_ref (base_addr),
1563			      arguments,
1564			      flags,
1565                              tf_warning_or_error);
1566	  expand_cleanup_for_base (subobject, NULL_TREE);
1567	  if (STATEMENT_LIST_TAIL (cur_stmt_list))
1568	    find_uninit_fields (&STATEMENT_LIST_TAIL (cur_stmt_list)->stmt,
1569				&uninitialized, BINFO_TYPE (subobject));
1570	}
1571      else if (!ABSTRACT_CLASS_TYPE_P (current_class_type))
1572	/* C++14 DR1658 Means we do not have to construct vbases of
1573	   abstract classes.  */
1574	construct_virtual_base (subobject, arguments);
1575      else
1576	/* When not constructing vbases of abstract classes, at least mark
1577	   the arguments expressions as read to avoid
1578	   -Wunused-but-set-parameter false positives.  */
1579	cp_walk_tree (&arguments, mark_exp_read_r, NULL, NULL);
1580
1581      if (inherited_base)
1582	pop_deferring_access_checks ();
1583    }
1584  in_base_initializer = 0;
1585
1586  /* Initialize the vptrs.  */
1587  initialize_vtbl_ptrs (current_class_ptr);
1588
1589  /* Initialize the data members.  */
1590  while (mem_inits)
1591    {
1592      /* If this initializer was explicitly provided, then the dummy TREE_TYPE
1593	 node contains the source location.  */
1594      iloc_sentinel ils (EXPR_LOCATION (TREE_TYPE (mem_inits)));
1595
1596      perform_member_init (TREE_PURPOSE (mem_inits),
1597			   TREE_VALUE (mem_inits),
1598			   uninitialized);
1599
1600      mem_inits = TREE_CHAIN (mem_inits);
1601    }
1602}
1603
1604/* Returns the address of the vtable (i.e., the value that should be
1605   assigned to the vptr) for BINFO.  */
1606
1607tree
1608build_vtbl_address (tree binfo)
1609{
1610  tree binfo_for = binfo;
1611  tree vtbl;
1612
1613  if (BINFO_VPTR_INDEX (binfo) && BINFO_VIRTUAL_P (binfo))
1614    /* If this is a virtual primary base, then the vtable we want to store
1615       is that for the base this is being used as the primary base of.  We
1616       can't simply skip the initialization, because we may be expanding the
1617       inits of a subobject constructor where the virtual base layout
1618       can be different.  */
1619    while (BINFO_PRIMARY_P (binfo_for))
1620      binfo_for = BINFO_INHERITANCE_CHAIN (binfo_for);
1621
1622  /* Figure out what vtable BINFO's vtable is based on, and mark it as
1623     used.  */
1624  vtbl = get_vtbl_decl_for_binfo (binfo_for);
1625  TREE_USED (vtbl) = true;
1626
1627  /* Now compute the address to use when initializing the vptr.  */
1628  vtbl = unshare_expr (BINFO_VTABLE (binfo_for));
1629  if (VAR_P (vtbl))
1630    vtbl = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (vtbl)), vtbl);
1631
1632  return vtbl;
1633}
1634
1635/* This code sets up the virtual function tables appropriate for
1636   the pointer DECL.  It is a one-ply initialization.
1637
1638   BINFO is the exact type that DECL is supposed to be.  In
1639   multiple inheritance, this might mean "C's A" if C : A, B.  */
1640
1641static void
1642expand_virtual_init (tree binfo, tree decl)
1643{
1644  tree vtbl, vtbl_ptr;
1645  tree vtt_index;
1646
1647  /* Compute the initializer for vptr.  */
1648  vtbl = build_vtbl_address (binfo);
1649
1650  /* We may get this vptr from a VTT, if this is a subobject
1651     constructor or subobject destructor.  */
1652  vtt_index = BINFO_VPTR_INDEX (binfo);
1653  if (vtt_index)
1654    {
1655      tree vtbl2;
1656      tree vtt_parm;
1657
1658      /* Compute the value to use, when there's a VTT.  */
1659      vtt_parm = current_vtt_parm;
1660      vtbl2 = fold_build_pointer_plus (vtt_parm, vtt_index);
1661      vtbl2 = cp_build_fold_indirect_ref (vtbl2);
1662      vtbl2 = convert (TREE_TYPE (vtbl), vtbl2);
1663
1664      /* The actual initializer is the VTT value only in the subobject
1665	 constructor.  In maybe_clone_body we'll substitute NULL for
1666	 the vtt_parm in the case of the non-subobject constructor.  */
1667      vtbl = build_if_in_charge (vtbl, vtbl2);
1668    }
1669
1670  /* Compute the location of the vtpr.  */
1671  vtbl_ptr = build_vfield_ref (cp_build_fold_indirect_ref (decl),
1672			       TREE_TYPE (binfo));
1673  gcc_assert (vtbl_ptr != error_mark_node);
1674
1675  /* Assign the vtable to the vptr.  */
1676  vtbl = convert_force (TREE_TYPE (vtbl_ptr), vtbl, 0, tf_warning_or_error);
1677  finish_expr_stmt (cp_build_modify_expr (input_location, vtbl_ptr, NOP_EXPR,
1678					  vtbl, tf_warning_or_error));
1679}
1680
1681/* If an exception is thrown in a constructor, those base classes already
1682   constructed must be destroyed.  This function creates the cleanup
1683   for BINFO, which has just been constructed.  If FLAG is non-NULL,
1684   it is a DECL which is nonzero when this base needs to be
1685   destroyed.  */
1686
1687static void
1688expand_cleanup_for_base (tree binfo, tree flag)
1689{
1690  tree expr;
1691
1692  if (!type_build_dtor_call (BINFO_TYPE (binfo)))
1693    return;
1694
1695  /* Call the destructor.  */
1696  expr = build_special_member_call (current_class_ref,
1697				    base_dtor_identifier,
1698				    NULL,
1699				    binfo,
1700				    LOOKUP_NORMAL | LOOKUP_NONVIRTUAL,
1701                                    tf_warning_or_error);
1702
1703  if (TYPE_HAS_TRIVIAL_DESTRUCTOR (BINFO_TYPE (binfo)))
1704    return;
1705
1706  if (flag)
1707    expr = fold_build3_loc (input_location,
1708			COND_EXPR, void_type_node,
1709			c_common_truthvalue_conversion (input_location, flag),
1710			expr, integer_zero_node);
1711
1712  finish_eh_cleanup (expr);
1713}
1714
1715/* Construct the virtual base-class VBASE passing the ARGUMENTS to its
1716   constructor.  */
1717
1718static void
1719construct_virtual_base (tree vbase, tree arguments)
1720{
1721  tree inner_if_stmt;
1722  tree exp;
1723  tree flag;
1724
1725  /* If there are virtual base classes with destructors, we need to
1726     emit cleanups to destroy them if an exception is thrown during
1727     the construction process.  These exception regions (i.e., the
1728     period during which the cleanups must occur) begin from the time
1729     the construction is complete to the end of the function.  If we
1730     create a conditional block in which to initialize the
1731     base-classes, then the cleanup region for the virtual base begins
1732     inside a block, and ends outside of that block.  This situation
1733     confuses the sjlj exception-handling code.  Therefore, we do not
1734     create a single conditional block, but one for each
1735     initialization.  (That way the cleanup regions always begin
1736     in the outer block.)  We trust the back end to figure out
1737     that the FLAG will not change across initializations, and
1738     avoid doing multiple tests.  */
1739  flag = DECL_CHAIN (DECL_ARGUMENTS (current_function_decl));
1740  inner_if_stmt = begin_if_stmt ();
1741  finish_if_stmt_cond (flag, inner_if_stmt);
1742
1743  /* Compute the location of the virtual base.  If we're
1744     constructing virtual bases, then we must be the most derived
1745     class.  Therefore, we don't have to look up the virtual base;
1746     we already know where it is.  */
1747  exp = convert_to_base_statically (current_class_ref, vbase);
1748
1749  expand_aggr_init_1 (vbase, current_class_ref, exp, arguments,
1750		      0, tf_warning_or_error);
1751  finish_then_clause (inner_if_stmt);
1752  finish_if_stmt (inner_if_stmt);
1753
1754  expand_cleanup_for_base (vbase, flag);
1755}
1756
1757/* Find the context in which this FIELD can be initialized.  */
1758
1759static tree
1760initializing_context (tree field)
1761{
1762  tree t = DECL_CONTEXT (field);
1763
1764  /* Anonymous union members can be initialized in the first enclosing
1765     non-anonymous union context.  */
1766  while (t && ANON_AGGR_TYPE_P (t))
1767    t = TYPE_CONTEXT (t);
1768  return t;
1769}
1770
1771/* Function to give error message if member initialization specification
1772   is erroneous.  FIELD is the member we decided to initialize.
1773   TYPE is the type for which the initialization is being performed.
1774   FIELD must be a member of TYPE.
1775
1776   MEMBER_NAME is the name of the member.  */
1777
1778static int
1779member_init_ok_or_else (tree field, tree type, tree member_name)
1780{
1781  if (field == error_mark_node)
1782    return 0;
1783  if (!field)
1784    {
1785      error ("class %qT does not have any field named %qD", type,
1786	     member_name);
1787      return 0;
1788    }
1789  if (VAR_P (field))
1790    {
1791      error ("%q#D is a static data member; it can only be "
1792	     "initialized at its definition",
1793	     field);
1794      return 0;
1795    }
1796  if (TREE_CODE (field) != FIELD_DECL)
1797    {
1798      error ("%q#D is not a non-static data member of %qT",
1799	     field, type);
1800      return 0;
1801    }
1802  if (initializing_context (field) != type)
1803    {
1804      error ("class %qT does not have any field named %qD", type,
1805		member_name);
1806      return 0;
1807    }
1808
1809  return 1;
1810}
1811
1812/* NAME is a FIELD_DECL, an IDENTIFIER_NODE which names a field, or it
1813   is a _TYPE node or TYPE_DECL which names a base for that type.
1814   Check the validity of NAME, and return either the base _TYPE, base
1815   binfo, or the FIELD_DECL of the member.  If NAME is invalid, return
1816   NULL_TREE and issue a diagnostic.
1817
1818   An old style unnamed direct single base construction is permitted,
1819   where NAME is NULL.  */
1820
1821tree
1822expand_member_init (tree name)
1823{
1824  tree basetype;
1825  tree field;
1826
1827  if (!current_class_ref)
1828    return NULL_TREE;
1829
1830  if (!name)
1831    {
1832      /* This is an obsolete unnamed base class initializer.  The
1833	 parser will already have warned about its use.  */
1834      switch (BINFO_N_BASE_BINFOS (TYPE_BINFO (current_class_type)))
1835	{
1836	case 0:
1837	  error ("unnamed initializer for %qT, which has no base classes",
1838		 current_class_type);
1839	  return NULL_TREE;
1840	case 1:
1841	  basetype = BINFO_TYPE
1842	    (BINFO_BASE_BINFO (TYPE_BINFO (current_class_type), 0));
1843	  break;
1844	default:
1845	  error ("unnamed initializer for %qT, which uses multiple inheritance",
1846		 current_class_type);
1847	  return NULL_TREE;
1848      }
1849    }
1850  else if (TYPE_P (name))
1851    {
1852      basetype = TYPE_MAIN_VARIANT (name);
1853      name = TYPE_NAME (name);
1854    }
1855  else if (TREE_CODE (name) == TYPE_DECL)
1856    basetype = TYPE_MAIN_VARIANT (TREE_TYPE (name));
1857  else
1858    basetype = NULL_TREE;
1859
1860  if (basetype)
1861    {
1862      tree class_binfo;
1863      tree direct_binfo;
1864      tree virtual_binfo;
1865      int i;
1866
1867      if (current_template_parms
1868	  || same_type_p (basetype, current_class_type))
1869	  return basetype;
1870
1871      class_binfo = TYPE_BINFO (current_class_type);
1872      direct_binfo = NULL_TREE;
1873      virtual_binfo = NULL_TREE;
1874
1875      /* Look for a direct base.  */
1876      for (i = 0; BINFO_BASE_ITERATE (class_binfo, i, direct_binfo); ++i)
1877	if (SAME_BINFO_TYPE_P (BINFO_TYPE (direct_binfo), basetype))
1878	  break;
1879
1880      /* Look for a virtual base -- unless the direct base is itself
1881	 virtual.  */
1882      if (!direct_binfo || !BINFO_VIRTUAL_P (direct_binfo))
1883	virtual_binfo = binfo_for_vbase (basetype, current_class_type);
1884
1885      /* [class.base.init]
1886
1887	 If a mem-initializer-id is ambiguous because it designates
1888	 both a direct non-virtual base class and an inherited virtual
1889	 base class, the mem-initializer is ill-formed.  */
1890      if (direct_binfo && virtual_binfo)
1891	{
1892	  error ("%qD is both a direct base and an indirect virtual base",
1893		 basetype);
1894	  return NULL_TREE;
1895	}
1896
1897      if (!direct_binfo && !virtual_binfo)
1898	{
1899	  if (CLASSTYPE_VBASECLASSES (current_class_type))
1900	    error ("type %qT is not a direct or virtual base of %qT",
1901		   basetype, current_class_type);
1902	  else
1903	    error ("type %qT is not a direct base of %qT",
1904		   basetype, current_class_type);
1905	  return NULL_TREE;
1906	}
1907
1908      return direct_binfo ? direct_binfo : virtual_binfo;
1909    }
1910  else
1911    {
1912      if (identifier_p (name))
1913	field = lookup_field (current_class_type, name, 1, false);
1914      else
1915	field = name;
1916
1917      if (member_init_ok_or_else (field, current_class_type, name))
1918	return field;
1919    }
1920
1921  return NULL_TREE;
1922}
1923
1924/* This is like `expand_member_init', only it stores one aggregate
1925   value into another.
1926
1927   INIT comes in two flavors: it is either a value which
1928   is to be stored in EXP, or it is a parameter list
1929   to go to a constructor, which will operate on EXP.
1930   If INIT is not a parameter list for a constructor, then set
1931   LOOKUP_ONLYCONVERTING.
1932   If FLAGS is LOOKUP_ONLYCONVERTING then it is the = init form of
1933   the initializer, if FLAGS is 0, then it is the (init) form.
1934   If `init' is a CONSTRUCTOR, then we emit a warning message,
1935   explaining that such initializations are invalid.
1936
1937   If INIT resolves to a CALL_EXPR which happens to return
1938   something of the type we are looking for, then we know
1939   that we can safely use that call to perform the
1940   initialization.
1941
1942   The virtual function table pointer cannot be set up here, because
1943   we do not really know its type.
1944
1945   This never calls operator=().
1946
1947   When initializing, nothing is CONST.
1948
1949   A default copy constructor may have to be used to perform the
1950   initialization.
1951
1952   A constructor or a conversion operator may have to be used to
1953   perform the initialization, but not both, as it would be ambiguous.  */
1954
1955tree
1956build_aggr_init (tree exp, tree init, int flags, tsubst_flags_t complain)
1957{
1958  tree stmt_expr;
1959  tree compound_stmt;
1960  int destroy_temps;
1961  tree type = TREE_TYPE (exp);
1962  int was_const = TREE_READONLY (exp);
1963  int was_volatile = TREE_THIS_VOLATILE (exp);
1964  int is_global;
1965
1966  if (init == error_mark_node)
1967    return error_mark_node;
1968
1969  location_t init_loc = (init
1970			 ? cp_expr_loc_or_input_loc (init)
1971			 : location_of (exp));
1972
1973  TREE_READONLY (exp) = 0;
1974  TREE_THIS_VOLATILE (exp) = 0;
1975
1976  if (TREE_CODE (type) == ARRAY_TYPE)
1977    {
1978      tree itype = init ? TREE_TYPE (init) : NULL_TREE;
1979      int from_array = 0;
1980
1981      if (VAR_P (exp) && DECL_DECOMPOSITION_P (exp))
1982	{
1983	  from_array = 1;
1984	  init = mark_rvalue_use (init);
1985	  if (init
1986	      && DECL_P (tree_strip_any_location_wrapper (init))
1987	      && !(flags & LOOKUP_ONLYCONVERTING))
1988	    {
1989	      /* Wrap the initializer in a CONSTRUCTOR so that build_vec_init
1990		 recognizes it as direct-initialization.  */
1991	      init = build_constructor_single (init_list_type_node,
1992					       NULL_TREE, init);
1993	      CONSTRUCTOR_IS_DIRECT_INIT (init) = true;
1994	    }
1995	}
1996      else
1997	{
1998	  /* Must arrange to initialize each element of EXP
1999	     from elements of INIT.  */
2000	  if (cv_qualified_p (type))
2001	    TREE_TYPE (exp) = cv_unqualified (type);
2002	  if (itype && cv_qualified_p (itype))
2003	    TREE_TYPE (init) = cv_unqualified (itype);
2004	  from_array = (itype && same_type_p (TREE_TYPE (init),
2005					      TREE_TYPE (exp)));
2006
2007	  if (init && !BRACE_ENCLOSED_INITIALIZER_P (init)
2008	      && (!from_array
2009		  || (TREE_CODE (init) != CONSTRUCTOR
2010		      /* Can happen, eg, handling the compound-literals
2011			 extension (ext/complit12.C).  */
2012		      && TREE_CODE (init) != TARGET_EXPR)))
2013	    {
2014	      if (complain & tf_error)
2015		error_at (init_loc, "array must be initialized "
2016			  "with a brace-enclosed initializer");
2017	      return error_mark_node;
2018	    }
2019	}
2020
2021      stmt_expr = build_vec_init (exp, NULL_TREE, init,
2022				  /*explicit_value_init_p=*/false,
2023				  from_array,
2024                                  complain);
2025      TREE_READONLY (exp) = was_const;
2026      TREE_THIS_VOLATILE (exp) = was_volatile;
2027      TREE_TYPE (exp) = type;
2028      /* Restore the type of init unless it was used directly.  */
2029      if (init && TREE_CODE (stmt_expr) != INIT_EXPR)
2030	TREE_TYPE (init) = itype;
2031      return stmt_expr;
2032    }
2033
2034  if (is_copy_initialization (init))
2035    flags |= LOOKUP_ONLYCONVERTING;
2036
2037  is_global = begin_init_stmts (&stmt_expr, &compound_stmt);
2038  destroy_temps = stmts_are_full_exprs_p ();
2039  current_stmt_tree ()->stmts_are_full_exprs_p = 0;
2040  bool ok = expand_aggr_init_1 (TYPE_BINFO (type), exp, exp,
2041				init, LOOKUP_NORMAL|flags, complain);
2042  stmt_expr = finish_init_stmts (is_global, stmt_expr, compound_stmt);
2043  current_stmt_tree ()->stmts_are_full_exprs_p = destroy_temps;
2044  TREE_READONLY (exp) = was_const;
2045  TREE_THIS_VOLATILE (exp) = was_volatile;
2046  if (!ok)
2047    return error_mark_node;
2048
2049  if ((VAR_P (exp) || TREE_CODE (exp) == PARM_DECL)
2050      && TREE_SIDE_EFFECTS (stmt_expr)
2051      && !lookup_attribute ("warn_unused", TYPE_ATTRIBUTES (type)))
2052    /* Just know that we've seen something for this node.  */
2053    TREE_USED (exp) = 1;
2054
2055  return stmt_expr;
2056}
2057
2058static bool
2059expand_default_init (tree binfo, tree true_exp, tree exp, tree init, int flags,
2060                     tsubst_flags_t complain)
2061{
2062  tree type = TREE_TYPE (exp);
2063
2064  /* It fails because there may not be a constructor which takes
2065     its own type as the first (or only parameter), but which does
2066     take other types via a conversion.  So, if the thing initializing
2067     the expression is a unit element of type X, first try X(X&),
2068     followed by initialization by X.  If neither of these work
2069     out, then look hard.  */
2070  tree rval;
2071  vec<tree, va_gc> *parms;
2072
2073  /* If we have direct-initialization from an initializer list, pull
2074     it out of the TREE_LIST so the code below can see it.  */
2075  if (init && TREE_CODE (init) == TREE_LIST
2076      && DIRECT_LIST_INIT_P (TREE_VALUE (init)))
2077    {
2078      gcc_checking_assert ((flags & LOOKUP_ONLYCONVERTING) == 0
2079			   && TREE_CHAIN (init) == NULL_TREE);
2080      init = TREE_VALUE (init);
2081      /* Only call reshape_init if it has not been called earlier
2082	 by the callers.  */
2083      if (BRACE_ENCLOSED_INITIALIZER_P (init) && CP_AGGREGATE_TYPE_P (type))
2084	init = reshape_init (type, init, complain);
2085    }
2086
2087  if (init && BRACE_ENCLOSED_INITIALIZER_P (init)
2088      && CP_AGGREGATE_TYPE_P (type))
2089    /* A brace-enclosed initializer for an aggregate.  In C++0x this can
2090       happen for direct-initialization, too.  */
2091    init = digest_init (type, init, complain);
2092
2093  if (init == error_mark_node)
2094    return false;
2095
2096  /* A CONSTRUCTOR of the target's type is a previously digested
2097     initializer, whether that happened just above or in
2098     cp_parser_late_parsing_nsdmi.
2099
2100     A TARGET_EXPR with TARGET_EXPR_DIRECT_INIT_P or TARGET_EXPR_LIST_INIT_P
2101     set represents the whole initialization, so we shouldn't build up
2102     another ctor call.  */
2103  if (init
2104      && (TREE_CODE (init) == CONSTRUCTOR
2105	  || (TREE_CODE (init) == TARGET_EXPR
2106	      && (TARGET_EXPR_DIRECT_INIT_P (init)
2107		  || TARGET_EXPR_LIST_INIT_P (init))))
2108      && same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (init), type))
2109    {
2110      /* Early initialization via a TARGET_EXPR only works for
2111	 complete objects.  */
2112      gcc_assert (TREE_CODE (init) == CONSTRUCTOR || true_exp == exp);
2113
2114      init = build2 (INIT_EXPR, TREE_TYPE (exp), exp, init);
2115      TREE_SIDE_EFFECTS (init) = 1;
2116      finish_expr_stmt (init);
2117      return true;
2118    }
2119
2120  if (init && TREE_CODE (init) != TREE_LIST
2121      && (flags & LOOKUP_ONLYCONVERTING)
2122      && !unsafe_return_slot_p (exp))
2123    {
2124      /* Base subobjects should only get direct-initialization.  */
2125      gcc_assert (true_exp == exp);
2126
2127      if (flags & DIRECT_BIND)
2128	/* Do nothing.  We hit this in two cases:  Reference initialization,
2129	   where we aren't initializing a real variable, so we don't want
2130	   to run a new constructor; and catching an exception, where we
2131	   have already built up the constructor call so we could wrap it
2132	   in an exception region.  */;
2133      else
2134	{
2135	  init = ocp_convert (type, init, CONV_IMPLICIT|CONV_FORCE_TEMP,
2136			      flags, complain | tf_no_cleanup);
2137	  if (init == error_mark_node)
2138	    return false;
2139	}
2140
2141      if (TREE_CODE (init) == MUST_NOT_THROW_EXPR)
2142	/* We need to protect the initialization of a catch parm with a
2143	   call to terminate(), which shows up as a MUST_NOT_THROW_EXPR
2144	   around the TARGET_EXPR for the copy constructor.  See
2145	   initialize_handler_parm.  */
2146	{
2147	  TREE_OPERAND (init, 0) = build2 (INIT_EXPR, TREE_TYPE (exp), exp,
2148					   TREE_OPERAND (init, 0));
2149	  TREE_TYPE (init) = void_type_node;
2150	}
2151      else
2152	init = build2 (INIT_EXPR, TREE_TYPE (exp), exp, init);
2153      TREE_SIDE_EFFECTS (init) = 1;
2154      finish_expr_stmt (init);
2155      return true;
2156    }
2157
2158  if (init == NULL_TREE)
2159    parms = NULL;
2160  else if (TREE_CODE (init) == TREE_LIST && !TREE_TYPE (init))
2161    {
2162      parms = make_tree_vector ();
2163      for (; init != NULL_TREE; init = TREE_CHAIN (init))
2164	vec_safe_push (parms, TREE_VALUE (init));
2165    }
2166  else
2167    parms = make_tree_vector_single (init);
2168
2169  if (exp == current_class_ref && current_function_decl
2170      && DECL_HAS_IN_CHARGE_PARM_P (current_function_decl))
2171    {
2172      /* Delegating constructor. */
2173      tree complete;
2174      tree base;
2175      tree elt; unsigned i;
2176
2177      /* Unshare the arguments for the second call.  */
2178      releasing_vec parms2;
2179      FOR_EACH_VEC_SAFE_ELT (parms, i, elt)
2180	{
2181	  elt = break_out_target_exprs (elt);
2182	  vec_safe_push (parms2, elt);
2183	}
2184      complete = build_special_member_call (exp, complete_ctor_identifier,
2185					    &parms2, binfo, flags,
2186					    complain);
2187      complete = fold_build_cleanup_point_expr (void_type_node, complete);
2188
2189      base = build_special_member_call (exp, base_ctor_identifier,
2190					&parms, binfo, flags,
2191					complain);
2192      base = fold_build_cleanup_point_expr (void_type_node, base);
2193      if (complete == error_mark_node || base == error_mark_node)
2194	return false;
2195      rval = build_if_in_charge (complete, base);
2196    }
2197   else
2198    {
2199      tree ctor_name = (true_exp == exp
2200			? complete_ctor_identifier : base_ctor_identifier);
2201
2202      rval = build_special_member_call (exp, ctor_name, &parms, binfo, flags,
2203					complain);
2204      if (rval == error_mark_node)
2205	return false;
2206    }
2207
2208  if (parms != NULL)
2209    release_tree_vector (parms);
2210
2211  if (exp == true_exp && TREE_CODE (rval) == CALL_EXPR)
2212    {
2213      tree fn = get_callee_fndecl (rval);
2214      if (fn && DECL_DECLARED_CONSTEXPR_P (fn))
2215	{
2216	  tree e = maybe_constant_init (rval, exp);
2217	  if (TREE_CONSTANT (e))
2218	    rval = build2 (INIT_EXPR, type, exp, e);
2219	}
2220    }
2221
2222  /* FIXME put back convert_to_void?  */
2223  if (TREE_SIDE_EFFECTS (rval))
2224    finish_expr_stmt (rval);
2225
2226  return true;
2227}
2228
2229/* This function is responsible for initializing EXP with INIT
2230   (if any).  Returns true on success, false on failure.
2231
2232   BINFO is the binfo of the type for who we are performing the
2233   initialization.  For example, if W is a virtual base class of A and B,
2234   and C : A, B.
2235   If we are initializing B, then W must contain B's W vtable, whereas
2236   were we initializing C, W must contain C's W vtable.
2237
2238   TRUE_EXP is nonzero if it is the true expression being initialized.
2239   In this case, it may be EXP, or may just contain EXP.  The reason we
2240   need this is because if EXP is a base element of TRUE_EXP, we
2241   don't necessarily know by looking at EXP where its virtual
2242   baseclass fields should really be pointing.  But we do know
2243   from TRUE_EXP.  In constructors, we don't know anything about
2244   the value being initialized.
2245
2246   FLAGS is just passed to `build_new_method_call'.  See that function
2247   for its description.  */
2248
2249static bool
2250expand_aggr_init_1 (tree binfo, tree true_exp, tree exp, tree init, int flags,
2251                    tsubst_flags_t complain)
2252{
2253  tree type = TREE_TYPE (exp);
2254
2255  gcc_assert (init != error_mark_node && type != error_mark_node);
2256  gcc_assert (building_stmt_list_p ());
2257
2258  /* Use a function returning the desired type to initialize EXP for us.
2259     If the function is a constructor, and its first argument is
2260     NULL_TREE, know that it was meant for us--just slide exp on
2261     in and expand the constructor.  Constructors now come
2262     as TARGET_EXPRs.  */
2263
2264  if (init && VAR_P (exp)
2265      && COMPOUND_LITERAL_P (init))
2266    {
2267      vec<tree, va_gc> *cleanups = NULL;
2268      /* If store_init_value returns NULL_TREE, the INIT has been
2269	 recorded as the DECL_INITIAL for EXP.  That means there's
2270	 nothing more we have to do.  */
2271      init = store_init_value (exp, init, &cleanups, flags);
2272      if (init)
2273	finish_expr_stmt (init);
2274      gcc_assert (!cleanups);
2275      return true;
2276    }
2277
2278  /* List-initialization from {} becomes value-initialization for non-aggregate
2279     classes with default constructors.  Handle this here when we're
2280     initializing a base, so protected access works.  */
2281  if (exp != true_exp && init && TREE_CODE (init) == TREE_LIST)
2282    {
2283      tree elt = TREE_VALUE (init);
2284      if (DIRECT_LIST_INIT_P (elt)
2285	  && CONSTRUCTOR_ELTS (elt) == 0
2286	  && CLASSTYPE_NON_AGGREGATE (type)
2287	  && TYPE_HAS_DEFAULT_CONSTRUCTOR (type))
2288	init = void_type_node;
2289    }
2290
2291  /* If an explicit -- but empty -- initializer list was present,
2292     that's value-initialization.  */
2293  if (init == void_type_node)
2294    {
2295      /* If the type has data but no user-provided default ctor, we need to zero
2296	 out the object.  */
2297      if (type_has_non_user_provided_default_constructor (type)
2298	  && !is_really_empty_class (type, /*ignore_vptr*/true))
2299	{
2300	  tree field_size = NULL_TREE;
2301	  if (exp != true_exp && CLASSTYPE_AS_BASE (type) != type)
2302	    /* Don't clobber already initialized virtual bases.  */
2303	    field_size = TYPE_SIZE (CLASSTYPE_AS_BASE (type));
2304	  init = build_zero_init_1 (type, NULL_TREE, /*static_storage_p=*/false,
2305				    field_size);
2306	  init = build2 (INIT_EXPR, type, exp, init);
2307	  finish_expr_stmt (init);
2308	}
2309
2310      /* If we don't need to mess with the constructor at all,
2311	 then we're done.  */
2312      if (! type_build_ctor_call (type))
2313	return true;
2314
2315      /* Otherwise fall through and call the constructor.  */
2316      init = NULL_TREE;
2317    }
2318
2319  /* We know that expand_default_init can handle everything we want
2320     at this point.  */
2321  return expand_default_init (binfo, true_exp, exp, init, flags, complain);
2322}
2323
2324/* Report an error if TYPE is not a user-defined, class type.  If
2325   OR_ELSE is nonzero, give an error message.  */
2326
2327int
2328is_class_type (tree type, int or_else)
2329{
2330  if (type == error_mark_node)
2331    return 0;
2332
2333  if (! CLASS_TYPE_P (type))
2334    {
2335      if (or_else)
2336	error ("%qT is not a class type", type);
2337      return 0;
2338    }
2339  return 1;
2340}
2341
2342/* Returns true iff the initializer INIT represents copy-initialization
2343   (and therefore we must set LOOKUP_ONLYCONVERTING when processing it).  */
2344
2345bool
2346is_copy_initialization (tree init)
2347{
2348  return (init && init != void_type_node
2349	  && TREE_CODE (init) != TREE_LIST
2350	  && !(TREE_CODE (init) == TARGET_EXPR
2351	       && TARGET_EXPR_DIRECT_INIT_P (init))
2352	  && !DIRECT_LIST_INIT_P (init));
2353}
2354
2355/* Build a reference to a member of an aggregate.  This is not a C++
2356   `&', but really something which can have its address taken, and
2357   then act as a pointer to member, for example TYPE :: FIELD can have
2358   its address taken by saying & TYPE :: FIELD.  ADDRESS_P is true if
2359   this expression is the operand of "&".
2360
2361   @@ Prints out lousy diagnostics for operator <typename>
2362   @@ fields.
2363
2364   @@ This function should be rewritten and placed in search.cc.  */
2365
2366tree
2367build_offset_ref (tree type, tree member, bool address_p,
2368		  tsubst_flags_t complain)
2369{
2370  tree decl;
2371  tree basebinfo = NULL_TREE;
2372
2373  /* class templates can come in as TEMPLATE_DECLs here.  */
2374  if (TREE_CODE (member) == TEMPLATE_DECL)
2375    return member;
2376
2377  if (dependent_scope_p (type) || type_dependent_expression_p (member))
2378    return build_qualified_name (NULL_TREE, type, member,
2379				  /*template_p=*/false);
2380
2381  gcc_assert (TYPE_P (type));
2382  if (! is_class_type (type, 1))
2383    return error_mark_node;
2384
2385  gcc_assert (DECL_P (member) || BASELINK_P (member));
2386  /* Callers should call mark_used before this point, except for functions.  */
2387  gcc_assert (!DECL_P (member) || TREE_USED (member)
2388	      || TREE_CODE (member) == FUNCTION_DECL);
2389
2390  type = TYPE_MAIN_VARIANT (type);
2391  if (!COMPLETE_OR_OPEN_TYPE_P (complete_type (type)))
2392    {
2393      if (complain & tf_error)
2394	error ("incomplete type %qT does not have member %qD", type, member);
2395      return error_mark_node;
2396    }
2397
2398  /* Entities other than non-static members need no further
2399     processing.  */
2400  if (TREE_CODE (member) == TYPE_DECL)
2401    return member;
2402  if (VAR_P (member) || TREE_CODE (member) == CONST_DECL)
2403    return convert_from_reference (member);
2404
2405  if (TREE_CODE (member) == FIELD_DECL && DECL_C_BIT_FIELD (member))
2406    {
2407      if (complain & tf_error)
2408	error ("invalid pointer to bit-field %qD", member);
2409      return error_mark_node;
2410    }
2411
2412  /* Set up BASEBINFO for member lookup.  */
2413  decl = maybe_dummy_object (type, &basebinfo);
2414
2415  /* A lot of this logic is now handled in lookup_member.  */
2416  if (BASELINK_P (member))
2417    {
2418      /* Go from the TREE_BASELINK to the member function info.  */
2419      tree t = BASELINK_FUNCTIONS (member);
2420
2421      if (TREE_CODE (t) != TEMPLATE_ID_EXPR && !really_overloaded_fn (t))
2422	{
2423	  /* Get rid of a potential OVERLOAD around it.  */
2424	  t = OVL_FIRST (t);
2425
2426	  /* Unique functions are handled easily.  */
2427
2428	  /* For non-static member of base class, we need a special rule
2429	     for access checking [class.protected]:
2430
2431	       If the access is to form a pointer to member, the
2432	       nested-name-specifier shall name the derived class
2433	       (or any class derived from that class).  */
2434	  bool ok;
2435	  if (address_p && DECL_P (t)
2436	      && DECL_NONSTATIC_MEMBER_P (t))
2437	    ok = perform_or_defer_access_check (TYPE_BINFO (type), t, t,
2438						complain);
2439	  else
2440	    ok = perform_or_defer_access_check (basebinfo, t, t,
2441						complain);
2442	  if (!ok)
2443	    return error_mark_node;
2444	  if (DECL_STATIC_FUNCTION_P (t))
2445	    return member;
2446	  member = t;
2447	}
2448      else
2449	TREE_TYPE (member) = unknown_type_node;
2450    }
2451  else if (address_p && TREE_CODE (member) == FIELD_DECL)
2452    {
2453      /* We need additional test besides the one in
2454	 check_accessibility_of_qualified_id in case it is
2455	 a pointer to non-static member.  */
2456      if (!perform_or_defer_access_check (TYPE_BINFO (type), member, member,
2457					  complain))
2458	return error_mark_node;
2459    }
2460
2461  if (!address_p)
2462    {
2463      /* If MEMBER is non-static, then the program has fallen afoul of
2464	 [expr.prim]:
2465
2466	   An id-expression that denotes a non-static data member or
2467	   non-static member function of a class can only be used:
2468
2469	   -- as part of a class member access (_expr.ref_) in which the
2470	   object-expression refers to the member's class or a class
2471	   derived from that class, or
2472
2473	   -- to form a pointer to member (_expr.unary.op_), or
2474
2475	   -- in the body of a non-static member function of that class or
2476	   of a class derived from that class (_class.mfct.non-static_), or
2477
2478	   -- in a mem-initializer for a constructor for that class or for
2479	   a class derived from that class (_class.base.init_).  */
2480      if (DECL_NONSTATIC_MEMBER_FUNCTION_P (member))
2481	{
2482	  /* Build a representation of the qualified name suitable
2483	     for use as the operand to "&" -- even though the "&" is
2484	     not actually present.  */
2485	  member = build2 (OFFSET_REF, TREE_TYPE (member), decl, member);
2486	  /* In Microsoft mode, treat a non-static member function as if
2487	     it were a pointer-to-member.  */
2488	  if (flag_ms_extensions)
2489	    {
2490	      PTRMEM_OK_P (member) = 1;
2491	      return cp_build_addr_expr (member, complain);
2492	    }
2493	  if (complain & tf_error)
2494	    error ("invalid use of non-static member function %qD",
2495		   TREE_OPERAND (member, 1));
2496	  return error_mark_node;
2497	}
2498      else if (TREE_CODE (member) == FIELD_DECL)
2499	{
2500	  if (complain & tf_error)
2501	    error ("invalid use of non-static data member %qD", member);
2502	  return error_mark_node;
2503	}
2504      return member;
2505    }
2506
2507  member = build2 (OFFSET_REF, TREE_TYPE (member), decl, member);
2508  PTRMEM_OK_P (member) = 1;
2509  return member;
2510}
2511
2512/* If DECL is a scalar enumeration constant or variable with a
2513   constant initializer, return the initializer (or, its initializers,
2514   recursively); otherwise, return DECL.  If STRICT_P, the
2515   initializer is only returned if DECL is a
2516   constant-expression.  If RETURN_AGGREGATE_CST_OK_P, it is ok to
2517   return an aggregate constant.  If UNSHARE_P, return an unshared
2518   copy of the initializer.  */
2519
2520static tree
2521constant_value_1 (tree decl, bool strict_p, bool return_aggregate_cst_ok_p,
2522		  bool unshare_p)
2523{
2524  while (TREE_CODE (decl) == CONST_DECL
2525	 || decl_constant_var_p (decl)
2526	 || (!strict_p && VAR_P (decl)
2527	     && CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (decl))))
2528    {
2529      tree init;
2530      /* If DECL is a static data member in a template
2531	 specialization, we must instantiate it here.  The
2532	 initializer for the static data member is not processed
2533	 until needed; we need it now.  */
2534      mark_used (decl, tf_none);
2535      init = DECL_INITIAL (decl);
2536      if (init == error_mark_node)
2537	{
2538	  if (TREE_CODE (decl) == CONST_DECL
2539	      || DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
2540	    /* Treat the error as a constant to avoid cascading errors on
2541	       excessively recursive template instantiation (c++/9335).  */
2542	    return init;
2543	  else
2544	    return decl;
2545	}
2546      /* Initializers in templates are generally expanded during
2547	 instantiation, so before that for const int i(2)
2548	 INIT is a TREE_LIST with the actual initializer as
2549	 TREE_VALUE.  */
2550      if (processing_template_decl
2551	  && init
2552	  && TREE_CODE (init) == TREE_LIST
2553	  && TREE_CHAIN (init) == NULL_TREE)
2554	init = TREE_VALUE (init);
2555      /* Instantiate a non-dependent initializer for user variables.  We
2556	 mustn't do this for the temporary for an array compound literal;
2557	 trying to instatiate the initializer will keep creating new
2558	 temporaries until we crash.  Probably it's not useful to do it for
2559	 other artificial variables, either.  */
2560      if (!DECL_ARTIFICIAL (decl))
2561	init = instantiate_non_dependent_or_null (init);
2562      if (!init
2563	  || !TREE_TYPE (init)
2564	  || !TREE_CONSTANT (init)
2565	  || (!return_aggregate_cst_ok_p
2566	      /* Unless RETURN_AGGREGATE_CST_OK_P is true, do not
2567		 return an aggregate constant (of which string
2568		 literals are a special case), as we do not want
2569		 to make inadvertent copies of such entities, and
2570		 we must be sure that their addresses are the
2571 		 same everywhere.  */
2572	      && (TREE_CODE (init) == CONSTRUCTOR
2573		  || TREE_CODE (init) == STRING_CST)))
2574	break;
2575      /* Don't return a CONSTRUCTOR for a variable with partial run-time
2576	 initialization, since it doesn't represent the entire value.
2577	 Similarly for VECTOR_CSTs created by cp_folding those
2578	 CONSTRUCTORs.  */
2579      if ((TREE_CODE (init) == CONSTRUCTOR
2580	   || TREE_CODE (init) == VECTOR_CST)
2581	  && !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
2582	break;
2583      /* If the variable has a dynamic initializer, don't use its
2584	 DECL_INITIAL which doesn't reflect the real value.  */
2585      if (VAR_P (decl)
2586	  && TREE_STATIC (decl)
2587	  && !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl)
2588	  && DECL_NONTRIVIALLY_INITIALIZED_P (decl))
2589	break;
2590      decl = init;
2591    }
2592  return unshare_p ? unshare_expr (decl) : decl;
2593}
2594
2595/* If DECL is a CONST_DECL, or a constant VAR_DECL initialized by constant
2596   of integral or enumeration type, or a constexpr variable of scalar type,
2597   then return that value.  These are those variables permitted in constant
2598   expressions by [5.19/1].  */
2599
2600tree
2601scalar_constant_value (tree decl)
2602{
2603  return constant_value_1 (decl, /*strict_p=*/true,
2604			   /*return_aggregate_cst_ok_p=*/false,
2605			   /*unshare_p=*/true);
2606}
2607
2608/* Like scalar_constant_value, but can also return aggregate initializers.
2609   If UNSHARE_P, return an unshared copy of the initializer.  */
2610
2611tree
2612decl_really_constant_value (tree decl, bool unshare_p /*= true*/)
2613{
2614  return constant_value_1 (decl, /*strict_p=*/true,
2615			   /*return_aggregate_cst_ok_p=*/true,
2616			   /*unshare_p=*/unshare_p);
2617}
2618
2619/* A more relaxed version of decl_really_constant_value, used by the
2620   common C/C++ code.  */
2621
2622tree
2623decl_constant_value (tree decl, bool unshare_p)
2624{
2625  return constant_value_1 (decl, /*strict_p=*/processing_template_decl,
2626			   /*return_aggregate_cst_ok_p=*/true,
2627			   /*unshare_p=*/unshare_p);
2628}
2629
2630tree
2631decl_constant_value (tree decl)
2632{
2633  return decl_constant_value (decl, /*unshare_p=*/true);
2634}
2635
2636/* Common subroutines of build_new and build_vec_delete.  */
2637
2638/* Build and return a NEW_EXPR.  If NELTS is non-NULL, TYPE[NELTS] is
2639   the type of the object being allocated; otherwise, it's just TYPE.
2640   INIT is the initializer, if any.  USE_GLOBAL_NEW is true if the
2641   user explicitly wrote "::operator new".  PLACEMENT, if non-NULL, is
2642   a vector of arguments to be provided as arguments to a placement
2643   new operator.  This routine performs no semantic checks; it just
2644   creates and returns a NEW_EXPR.  */
2645
2646static tree
2647build_raw_new_expr (location_t loc, vec<tree, va_gc> *placement, tree type,
2648		    tree nelts, vec<tree, va_gc> *init, int use_global_new)
2649{
2650  tree init_list;
2651  tree new_expr;
2652
2653  /* If INIT is NULL, the we want to store NULL_TREE in the NEW_EXPR.
2654     If INIT is not NULL, then we want to store VOID_ZERO_NODE.  This
2655     permits us to distinguish the case of a missing initializer "new
2656     int" from an empty initializer "new int()".  */
2657  if (init == NULL)
2658    init_list = NULL_TREE;
2659  else if (init->is_empty ())
2660    init_list = void_node;
2661  else
2662    init_list = build_tree_list_vec (init);
2663
2664  new_expr = build4_loc (loc, NEW_EXPR, build_pointer_type (type),
2665			 build_tree_list_vec (placement), type, nelts,
2666			 init_list);
2667  NEW_EXPR_USE_GLOBAL (new_expr) = use_global_new;
2668  TREE_SIDE_EFFECTS (new_expr) = 1;
2669
2670  return new_expr;
2671}
2672
2673/* Diagnose uninitialized const members or reference members of type
2674   TYPE. USING_NEW is used to disambiguate the diagnostic between a
2675   new expression without a new-initializer and a declaration. Returns
2676   the error count. */
2677
2678static int
2679diagnose_uninitialized_cst_or_ref_member_1 (tree type, tree origin,
2680					    bool using_new, bool complain)
2681{
2682  tree field;
2683  int error_count = 0;
2684
2685  if (type_has_user_provided_constructor (type))
2686    return 0;
2687
2688  for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
2689    {
2690      tree field_type;
2691
2692      if (TREE_CODE (field) != FIELD_DECL)
2693	continue;
2694
2695      field_type = strip_array_types (TREE_TYPE (field));
2696
2697      if (type_has_user_provided_constructor (field_type))
2698	continue;
2699
2700      if (TYPE_REF_P (field_type))
2701	{
2702	  ++ error_count;
2703	  if (complain)
2704	    {
2705	      if (DECL_CONTEXT (field) == origin)
2706		{
2707		  if (using_new)
2708		    error ("uninitialized reference member in %q#T "
2709			   "using %<new%> without new-initializer", origin);
2710		  else
2711		    error ("uninitialized reference member in %q#T", origin);
2712		}
2713	      else
2714		{
2715		  if (using_new)
2716		    error ("uninitialized reference member in base %q#T "
2717			   "of %q#T using %<new%> without new-initializer",
2718			   DECL_CONTEXT (field), origin);
2719		  else
2720		    error ("uninitialized reference member in base %q#T "
2721			   "of %q#T", DECL_CONTEXT (field), origin);
2722		}
2723	      inform (DECL_SOURCE_LOCATION (field),
2724		      "%q#D should be initialized", field);
2725	    }
2726	}
2727
2728      if (CP_TYPE_CONST_P (field_type))
2729	{
2730	  ++ error_count;
2731	  if (complain)
2732	    {
2733	      if (DECL_CONTEXT (field) == origin)
2734		{
2735		  if (using_new)
2736		    error ("uninitialized const member in %q#T "
2737			   "using %<new%> without new-initializer", origin);
2738		  else
2739		    error ("uninitialized const member in %q#T", origin);
2740		}
2741	      else
2742		{
2743		  if (using_new)
2744		    error ("uninitialized const member in base %q#T "
2745			   "of %q#T using %<new%> without new-initializer",
2746			   DECL_CONTEXT (field), origin);
2747		  else
2748		    error ("uninitialized const member in base %q#T "
2749			   "of %q#T", DECL_CONTEXT (field), origin);
2750		}
2751	      inform (DECL_SOURCE_LOCATION (field),
2752		      "%q#D should be initialized", field);
2753	    }
2754	}
2755
2756      if (CLASS_TYPE_P (field_type))
2757	error_count
2758	  += diagnose_uninitialized_cst_or_ref_member_1 (field_type, origin,
2759							 using_new, complain);
2760    }
2761  return error_count;
2762}
2763
2764int
2765diagnose_uninitialized_cst_or_ref_member (tree type, bool using_new, bool complain)
2766{
2767  return diagnose_uninitialized_cst_or_ref_member_1 (type, type, using_new, complain);
2768}
2769
2770/* Call __cxa_bad_array_new_length to indicate that the size calculation
2771   overflowed.  Pretend it returns sizetype so that it plays nicely in the
2772   COND_EXPR.  */
2773
2774tree
2775throw_bad_array_new_length (void)
2776{
2777  if (!fn)
2778    {
2779      tree name = get_identifier ("__cxa_throw_bad_array_new_length");
2780
2781      fn = get_global_binding (name);
2782      if (!fn)
2783	fn = push_throw_library_fn
2784	  (name, build_function_type_list (sizetype, NULL_TREE));
2785    }
2786
2787  return build_cxx_call (fn, 0, NULL, tf_warning_or_error);
2788}
2789
2790/* Attempt to verify that the argument, OPER, of a placement new expression
2791   refers to an object sufficiently large for an object of TYPE or an array
2792   of NELTS of such objects when NELTS is non-null, and issue a warning when
2793   it does not.  SIZE specifies the size needed to construct the object or
2794   array and captures the result of NELTS * sizeof (TYPE). (SIZE could be
2795   greater when the array under construction requires a cookie to store
2796   NELTS.  GCC's placement new expression stores the cookie when invoking
2797   a user-defined placement new operator function but not the default one.
2798   Placement new expressions with user-defined placement new operator are
2799   not diagnosed since we don't know how they use the buffer (this could
2800   be a future extension).  */
2801static void
2802warn_placement_new_too_small (tree type, tree nelts, tree size, tree oper)
2803{
2804  location_t loc = cp_expr_loc_or_input_loc (oper);
2805
2806  STRIP_NOPS (oper);
2807
2808  /* Using a function argument or a (non-array) variable as an argument
2809     to placement new is not checked since it's unknown what it might
2810     point to.  */
2811  if (TREE_CODE (oper) == PARM_DECL
2812      || VAR_P (oper)
2813      || TREE_CODE (oper) == COMPONENT_REF)
2814    return;
2815
2816  /* Evaluate any constant expressions.  */
2817  size = fold_non_dependent_expr (size);
2818
2819  access_ref ref;
2820  ref.eval = [](tree x){ return fold_non_dependent_expr (x); };
2821  ref.trail1special = warn_placement_new < 2;
2822  tree objsize =  compute_objsize (oper, 1, &ref);
2823  if (!objsize)
2824    return;
2825
2826  /* We can only draw conclusions if ref.deref == -1,
2827     i.e. oper is the address of the object.  */
2828  if (ref.deref != -1)
2829    return;
2830
2831  offset_int bytes_avail = wi::to_offset (objsize);
2832  offset_int bytes_need;
2833
2834  if (CONSTANT_CLASS_P (size))
2835    bytes_need = wi::to_offset (size);
2836  else if (nelts && CONSTANT_CLASS_P (nelts))
2837    bytes_need = (wi::to_offset (nelts)
2838		  * wi::to_offset (TYPE_SIZE_UNIT (type)));
2839  else if (tree_fits_uhwi_p (TYPE_SIZE_UNIT (type)))
2840    bytes_need = wi::to_offset (TYPE_SIZE_UNIT (type));
2841  else
2842    {
2843      /* The type is a VLA.  */
2844      return;
2845    }
2846
2847  if (bytes_avail >= bytes_need)
2848    return;
2849
2850  /* True when the size to mention in the warning is exact as opposed
2851     to "at least N".  */
2852  const bool exact_size = (ref.offrng[0] == ref.offrng[1]
2853			   || ref.sizrng[1] - ref.offrng[0] == 0);
2854
2855  tree opertype = ref.ref ? TREE_TYPE (ref.ref) : TREE_TYPE (oper);
2856  bool warned = false;
2857  if (nelts)
2858    nelts = fold_for_warn (nelts);
2859  if (nelts)
2860    if (CONSTANT_CLASS_P (nelts))
2861      warned = warning_at (loc, OPT_Wplacement_new_,
2862			   (exact_size
2863			    ? G_("placement new constructing an object "
2864				 "of type %<%T [%wu]%> and size %qwu "
2865				 "in a region of type %qT and size %qwi")
2866			    : G_("placement new constructing an object "
2867				 "of type %<%T [%wu]%> and size %qwu "
2868				 "in a region of type %qT and size "
2869				 "at most %qwu")),
2870			   type, tree_to_uhwi (nelts),
2871			   bytes_need.to_uhwi (),
2872			   opertype, bytes_avail.to_uhwi ());
2873    else
2874      warned = warning_at (loc, OPT_Wplacement_new_,
2875			   (exact_size
2876			    ? G_("placement new constructing an array "
2877				 "of objects of type %qT and size %qwu "
2878				 "in a region of type %qT and size %qwi")
2879			    : G_("placement new constructing an array "
2880				 "of objects of type %qT and size %qwu "
2881				 "in a region of type %qT and size "
2882				 "at most %qwu")),
2883			   type, bytes_need.to_uhwi (), opertype,
2884			   bytes_avail.to_uhwi ());
2885  else
2886    warned = warning_at (loc, OPT_Wplacement_new_,
2887			 (exact_size
2888			  ? G_("placement new constructing an object "
2889			       "of type %qT and size %qwu in a region "
2890			       "of type %qT and size %qwi")
2891			  : G_("placement new constructing an object "
2892			       "of type %qT "
2893			       "and size %qwu in a region of type %qT "
2894			       "and size at most %qwu")),
2895			       type, bytes_need.to_uhwi (), opertype,
2896			 bytes_avail.to_uhwi ());
2897
2898  if (!warned || !ref.ref)
2899    return;
2900
2901  if (ref.offrng[0] == 0 || !ref.offset_bounded ())
2902    /* Avoid mentioning the offset when its lower bound is zero
2903       or when it's impossibly large.  */
2904    inform (DECL_SOURCE_LOCATION (ref.ref),
2905	    "%qD declared here", ref.ref);
2906  else if (ref.offrng[0] == ref.offrng[1])
2907    inform (DECL_SOURCE_LOCATION (ref.ref),
2908	    "at offset %wi from %qD declared here",
2909	    ref.offrng[0].to_shwi (), ref.ref);
2910  else
2911    inform (DECL_SOURCE_LOCATION (ref.ref),
2912	    "at offset [%wi, %wi] from %qD declared here",
2913	    ref.offrng[0].to_shwi (), ref.offrng[1].to_shwi (), ref.ref);
2914}
2915
2916/* True if alignof(T) > __STDCPP_DEFAULT_NEW_ALIGNMENT__.  */
2917
2918bool
2919type_has_new_extended_alignment (tree t)
2920{
2921  return (aligned_new_threshold
2922	  && TYPE_ALIGN_UNIT (t) > (unsigned)aligned_new_threshold);
2923}
2924
2925/* Return the alignment we expect malloc to guarantee.  This should just be
2926   MALLOC_ABI_ALIGNMENT, but that macro defaults to only BITS_PER_WORD for some
2927   reason, so don't let the threshold be smaller than max_align_t_align.  */
2928
2929unsigned
2930malloc_alignment ()
2931{
2932  return MAX (max_align_t_align(), MALLOC_ABI_ALIGNMENT);
2933}
2934
2935/* Determine whether an allocation function is a namespace-scope
2936   non-replaceable placement new function. See DR 1748.  */
2937static bool
2938std_placement_new_fn_p (tree alloc_fn)
2939{
2940  if (DECL_NAMESPACE_SCOPE_P (alloc_fn))
2941    {
2942      tree first_arg = TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (alloc_fn)));
2943      if ((TREE_VALUE (first_arg) == ptr_type_node)
2944	  && TREE_CHAIN (first_arg) == void_list_node)
2945	return true;
2946    }
2947  return false;
2948}
2949
2950/* For element type ELT_TYPE, return the appropriate type of the heap object
2951   containing such element(s).  COOKIE_SIZE is the size of cookie in bytes.
2952   Return
2953   struct { size_t[COOKIE_SIZE/sizeof(size_t)]; ELT_TYPE[N]; }
2954   where N is nothing (flexible array member) if ITYPE2 is NULL, otherwise
2955   the array has ITYPE2 as its TYPE_DOMAIN.  */
2956
2957tree
2958build_new_constexpr_heap_type (tree elt_type, tree cookie_size, tree itype2)
2959{
2960  gcc_assert (tree_fits_uhwi_p (cookie_size));
2961  unsigned HOST_WIDE_INT csz = tree_to_uhwi (cookie_size);
2962  csz /= int_size_in_bytes (sizetype);
2963  tree itype1 = build_index_type (size_int (csz - 1));
2964  tree atype1 = build_cplus_array_type (sizetype, itype1);
2965  tree atype2 = build_cplus_array_type (elt_type, itype2);
2966  tree rtype = cxx_make_type (RECORD_TYPE);
2967  TYPE_NAME (rtype) = heap_identifier;
2968  tree fld1 = build_decl (UNKNOWN_LOCATION, FIELD_DECL, NULL_TREE, atype1);
2969  tree fld2 = build_decl (UNKNOWN_LOCATION, FIELD_DECL, NULL_TREE, atype2);
2970  DECL_FIELD_CONTEXT (fld1) = rtype;
2971  DECL_FIELD_CONTEXT (fld2) = rtype;
2972  DECL_ARTIFICIAL (fld1) = true;
2973  DECL_ARTIFICIAL (fld2) = true;
2974  TYPE_FIELDS (rtype) = fld1;
2975  DECL_CHAIN (fld1) = fld2;
2976  layout_type (rtype);
2977  return rtype;
2978}
2979
2980/* Help the constexpr code to find the right type for the heap variable
2981   by adding a NOP_EXPR around ALLOC_CALL if needed for cookie_size.
2982   Return ALLOC_CALL or ALLOC_CALL cast to a pointer to
2983   struct { size_t[cookie_size/sizeof(size_t)]; elt_type[]; }.  */
2984
2985static tree
2986maybe_wrap_new_for_constexpr (tree alloc_call, tree elt_type, tree cookie_size)
2987{
2988  if (cxx_dialect < cxx20)
2989    return alloc_call;
2990
2991  if (current_function_decl != NULL_TREE
2992      && !DECL_DECLARED_CONSTEXPR_P (current_function_decl))
2993    return alloc_call;
2994
2995  tree call_expr = extract_call_expr (alloc_call);
2996  if (call_expr == error_mark_node)
2997    return alloc_call;
2998
2999  tree alloc_call_fndecl = cp_get_callee_fndecl_nofold (call_expr);
3000  if (alloc_call_fndecl == NULL_TREE
3001      || !IDENTIFIER_NEW_OP_P (DECL_NAME (alloc_call_fndecl))
3002      || CP_DECL_CONTEXT (alloc_call_fndecl) != global_namespace)
3003    return alloc_call;
3004
3005  tree rtype = build_new_constexpr_heap_type (elt_type, cookie_size,
3006					      NULL_TREE);
3007  return build_nop (build_pointer_type (rtype), alloc_call);
3008}
3009
3010/* Generate code for a new-expression, including calling the "operator
3011   new" function, initializing the object, and, if an exception occurs
3012   during construction, cleaning up.  The arguments are as for
3013   build_raw_new_expr.  This may change PLACEMENT and INIT.
3014   TYPE is the type of the object being constructed, possibly an array
3015   of NELTS elements when NELTS is non-null (in "new T[NELTS]", T may
3016   be an array of the form U[inner], with the whole expression being
3017   "new U[NELTS][inner]").  */
3018
3019static tree
3020build_new_1 (vec<tree, va_gc> **placement, tree type, tree nelts,
3021	     vec<tree, va_gc> **init, bool globally_qualified_p,
3022	     tsubst_flags_t complain)
3023{
3024  tree size, rval;
3025  /* True iff this is a call to "operator new[]" instead of just
3026     "operator new".  */
3027  bool array_p = false;
3028  /* If ARRAY_P is true, the element type of the array.  This is never
3029     an ARRAY_TYPE; for something like "new int[3][4]", the
3030     ELT_TYPE is "int".  If ARRAY_P is false, this is the same type as
3031     TYPE.  */
3032  tree elt_type;
3033  /* The type of the new-expression.  (This type is always a pointer
3034     type.)  */
3035  tree pointer_type;
3036  tree non_const_pointer_type;
3037  /* The most significant array bound in int[OUTER_NELTS][inner].  */
3038  tree outer_nelts = NULL_TREE;
3039  /* For arrays with a non-constant number of elements, a bounds checks
3040     on the NELTS parameter to avoid integer overflow at runtime. */
3041  tree outer_nelts_check = NULL_TREE;
3042  bool outer_nelts_from_type = false;
3043  /* Number of the "inner" elements in "new T[OUTER_NELTS][inner]".  */
3044  offset_int inner_nelts_count = 1;
3045  tree alloc_call, alloc_expr;
3046  /* Size of the inner array elements (those with constant dimensions). */
3047  offset_int inner_size;
3048  /* The address returned by the call to "operator new".  This node is
3049     a VAR_DECL and is therefore reusable.  */
3050  tree alloc_node;
3051  tree alloc_fn;
3052  tree cookie_expr, init_expr;
3053  int nothrow, check_new;
3054  /* If non-NULL, the number of extra bytes to allocate at the
3055     beginning of the storage allocated for an array-new expression in
3056     order to store the number of elements.  */
3057  tree cookie_size = NULL_TREE;
3058  tree placement_first;
3059  tree placement_expr = NULL_TREE;
3060  /* True if the function we are calling is a placement allocation
3061     function.  */
3062  bool placement_allocation_fn_p;
3063  /* True if the storage must be initialized, either by a constructor
3064     or due to an explicit new-initializer.  */
3065  bool is_initialized;
3066  /* The address of the thing allocated, not including any cookie.  In
3067     particular, if an array cookie is in use, DATA_ADDR is the
3068     address of the first array element.  This node is a VAR_DECL, and
3069     is therefore reusable.  */
3070  tree data_addr;
3071  tree orig_type = type;
3072
3073  if (nelts)
3074    {
3075      outer_nelts = nelts;
3076      array_p = true;
3077    }
3078  else if (TREE_CODE (type) == ARRAY_TYPE)
3079    {
3080      /* Transforms new (T[N]) to new T[N].  The former is a GNU
3081	 extension for variable N.  (This also covers new T where T is
3082	 a VLA typedef.)  */
3083      array_p = true;
3084      nelts = array_type_nelts_top (type);
3085      outer_nelts = nelts;
3086      type = TREE_TYPE (type);
3087      outer_nelts_from_type = true;
3088    }
3089
3090  /* Lots of logic below depends on whether we have a constant number of
3091     elements, so go ahead and fold it now.  */
3092  const_tree cst_outer_nelts = fold_non_dependent_expr (outer_nelts, complain);
3093
3094  /* If our base type is an array, then make sure we know how many elements
3095     it has.  */
3096  for (elt_type = type;
3097       TREE_CODE (elt_type) == ARRAY_TYPE;
3098       elt_type = TREE_TYPE (elt_type))
3099    {
3100      tree inner_nelts = array_type_nelts_top (elt_type);
3101      tree inner_nelts_cst = maybe_constant_value (inner_nelts);
3102      if (TREE_CODE (inner_nelts_cst) == INTEGER_CST)
3103	{
3104	  wi::overflow_type overflow;
3105	  offset_int result = wi::mul (wi::to_offset (inner_nelts_cst),
3106				       inner_nelts_count, SIGNED, &overflow);
3107	  if (overflow)
3108	    {
3109	      if (complain & tf_error)
3110		error ("integer overflow in array size");
3111	      nelts = error_mark_node;
3112	    }
3113	  inner_nelts_count = result;
3114	}
3115      else
3116	{
3117	  if (complain & tf_error)
3118	    {
3119	      error_at (cp_expr_loc_or_input_loc (inner_nelts),
3120			"array size in new-expression must be constant");
3121	      cxx_constant_value(inner_nelts);
3122	    }
3123	  nelts = error_mark_node;
3124	}
3125      if (nelts != error_mark_node)
3126	nelts = cp_build_binary_op (input_location,
3127				    MULT_EXPR, nelts,
3128				    inner_nelts_cst,
3129				    complain);
3130    }
3131
3132  if (!verify_type_context (input_location, TCTX_ALLOCATION, elt_type,
3133			    !(complain & tf_error)))
3134    return error_mark_node;
3135
3136  if (variably_modified_type_p (elt_type, NULL_TREE) && (complain & tf_error))
3137    {
3138      error ("variably modified type not allowed in new-expression");
3139      return error_mark_node;
3140    }
3141
3142  if (nelts == error_mark_node)
3143    return error_mark_node;
3144
3145  /* Warn if we performed the (T[N]) to T[N] transformation and N is
3146     variable.  */
3147  if (outer_nelts_from_type
3148      && !TREE_CONSTANT (cst_outer_nelts))
3149    {
3150      if (complain & tf_warning_or_error)
3151	{
3152	  pedwarn (cp_expr_loc_or_input_loc (outer_nelts), OPT_Wvla,
3153		   typedef_variant_p (orig_type)
3154		   ? G_("non-constant array new length must be specified "
3155			"directly, not by %<typedef%>")
3156		   : G_("non-constant array new length must be specified "
3157			"without parentheses around the type-id"));
3158	}
3159      else
3160	return error_mark_node;
3161    }
3162
3163  if (VOID_TYPE_P (elt_type))
3164    {
3165      if (complain & tf_error)
3166	error ("invalid type %<void%> for %<new%>");
3167      return error_mark_node;
3168    }
3169
3170  if (is_std_init_list (elt_type) && !cp_unevaluated_operand)
3171    warning (OPT_Winit_list_lifetime,
3172	     "%<new%> of %<initializer_list%> does not "
3173	     "extend the lifetime of the underlying array");
3174
3175  if (abstract_virtuals_error_sfinae (ACU_NEW, elt_type, complain))
3176    return error_mark_node;
3177
3178  is_initialized = (type_build_ctor_call (elt_type) || *init != NULL);
3179
3180  if (*init == NULL && cxx_dialect < cxx11)
3181    {
3182      bool maybe_uninitialized_error = false;
3183      /* A program that calls for default-initialization [...] of an
3184	 entity of reference type is ill-formed. */
3185      if (CLASSTYPE_REF_FIELDS_NEED_INIT (elt_type))
3186	maybe_uninitialized_error = true;
3187
3188      /* A new-expression that creates an object of type T initializes
3189	 that object as follows:
3190      - If the new-initializer is omitted:
3191        -- If T is a (possibly cv-qualified) non-POD class type
3192	   (or array thereof), the object is default-initialized (8.5).
3193	   [...]
3194        -- Otherwise, the object created has indeterminate
3195	   value. If T is a const-qualified type, or a (possibly
3196	   cv-qualified) POD class type (or array thereof)
3197	   containing (directly or indirectly) a member of
3198	   const-qualified type, the program is ill-formed; */
3199
3200      if (CLASSTYPE_READONLY_FIELDS_NEED_INIT (elt_type))
3201	maybe_uninitialized_error = true;
3202
3203      if (maybe_uninitialized_error
3204	  && diagnose_uninitialized_cst_or_ref_member (elt_type,
3205						       /*using_new=*/true,
3206						       complain & tf_error))
3207	return error_mark_node;
3208    }
3209
3210  if (CP_TYPE_CONST_P (elt_type) && *init == NULL
3211      && default_init_uninitialized_part (elt_type))
3212    {
3213      if (complain & tf_error)
3214        error ("uninitialized const in %<new%> of %q#T", elt_type);
3215      return error_mark_node;
3216    }
3217
3218  size = size_in_bytes (elt_type);
3219  if (array_p)
3220    {
3221      /* Maximum available size in bytes.  Half of the address space
3222	 minus the cookie size.  */
3223      offset_int max_size
3224	= wi::set_bit_in_zero <offset_int> (TYPE_PRECISION (sizetype) - 1);
3225      /* Maximum number of outer elements which can be allocated. */
3226      offset_int max_outer_nelts;
3227      tree max_outer_nelts_tree;
3228
3229      gcc_assert (TREE_CODE (size) == INTEGER_CST);
3230      cookie_size = targetm.cxx.get_cookie_size (elt_type);
3231      gcc_assert (TREE_CODE (cookie_size) == INTEGER_CST);
3232      gcc_checking_assert (wi::ltu_p (wi::to_offset (cookie_size), max_size));
3233      /* Unconditionally subtract the cookie size.  This decreases the
3234	 maximum object size and is safe even if we choose not to use
3235	 a cookie after all.  */
3236      max_size -= wi::to_offset (cookie_size);
3237      wi::overflow_type overflow;
3238      inner_size = wi::mul (wi::to_offset (size), inner_nelts_count, SIGNED,
3239			    &overflow);
3240      if (overflow || wi::gtu_p (inner_size, max_size))
3241	{
3242	  if (complain & tf_error)
3243	    {
3244	      cst_size_error error;
3245	      if (overflow)
3246		error = cst_size_overflow;
3247	      else
3248		{
3249		  error = cst_size_too_big;
3250		  size = size_binop (MULT_EXPR, size,
3251				     wide_int_to_tree (sizetype,
3252						       inner_nelts_count));
3253		  size = cp_fully_fold (size);
3254		}
3255	      invalid_array_size_error (input_location, error, size,
3256					/*name=*/NULL_TREE);
3257	    }
3258	  return error_mark_node;
3259	}
3260
3261      max_outer_nelts = wi::udiv_trunc (max_size, inner_size);
3262      max_outer_nelts_tree = wide_int_to_tree (sizetype, max_outer_nelts);
3263
3264      size = size_binop (MULT_EXPR, size, fold_convert (sizetype, nelts));
3265
3266      if (TREE_CODE (cst_outer_nelts) == INTEGER_CST)
3267	{
3268	  if (tree_int_cst_lt (max_outer_nelts_tree, cst_outer_nelts))
3269	    {
3270	      /* When the array size is constant, check it at compile time
3271		 to make sure it doesn't exceed the implementation-defined
3272		 maximum, as required by C++ 14 (in C++ 11 this requirement
3273		 isn't explicitly stated but it's enforced anyway -- see
3274		 grokdeclarator in cp/decl.cc).  */
3275	      if (complain & tf_error)
3276		{
3277		  size = cp_fully_fold (size);
3278		  invalid_array_size_error (input_location, cst_size_too_big,
3279					    size, NULL_TREE);
3280		}
3281	      return error_mark_node;
3282	    }
3283	}
3284      else
3285 	{
3286	  /* When a runtime check is necessary because the array size
3287	     isn't constant, keep only the top-most seven bits (starting
3288	     with the most significant non-zero bit) of the maximum size
3289	     to compare the array size against, to simplify encoding the
3290	     constant maximum size in the instruction stream.  */
3291
3292	  unsigned shift = (max_outer_nelts.get_precision ()) - 7
3293	    - wi::clz (max_outer_nelts);
3294	  max_outer_nelts = (max_outer_nelts >> shift) << shift;
3295
3296          outer_nelts_check = fold_build2 (LE_EXPR, boolean_type_node,
3297					   outer_nelts,
3298					   max_outer_nelts_tree);
3299	}
3300    }
3301
3302  tree align_arg = NULL_TREE;
3303  if (type_has_new_extended_alignment (elt_type))
3304    {
3305      unsigned align = TYPE_ALIGN_UNIT (elt_type);
3306      /* Also consider the alignment of the cookie, if any.  */
3307      if (array_p && TYPE_VEC_NEW_USES_COOKIE (elt_type))
3308	align = MAX (align, TYPE_ALIGN_UNIT (size_type_node));
3309      align_arg = build_int_cst (align_type_node, align);
3310    }
3311
3312  alloc_fn = NULL_TREE;
3313
3314  /* If PLACEMENT is a single simple pointer type not passed by
3315     reference, prepare to capture it in a temporary variable.  Do
3316     this now, since PLACEMENT will change in the calls below.  */
3317  placement_first = NULL_TREE;
3318  if (vec_safe_length (*placement) == 1
3319      && (TYPE_PTR_P (TREE_TYPE ((**placement)[0]))))
3320    placement_first = (**placement)[0];
3321
3322  bool member_new_p = false;
3323
3324  /* Allocate the object.  */
3325  tree fnname;
3326  tree fns;
3327
3328  fnname = ovl_op_identifier (false, array_p ? VEC_NEW_EXPR : NEW_EXPR);
3329
3330  member_new_p = !globally_qualified_p
3331		 && CLASS_TYPE_P (elt_type)
3332		 && (array_p
3333		     ? TYPE_HAS_ARRAY_NEW_OPERATOR (elt_type)
3334		     : TYPE_HAS_NEW_OPERATOR (elt_type));
3335
3336  bool member_delete_p = (!globally_qualified_p
3337			  && CLASS_TYPE_P (elt_type)
3338			  && (array_p
3339			      ? TYPE_GETS_VEC_DELETE (elt_type)
3340			      : TYPE_GETS_REG_DELETE (elt_type)));
3341
3342  if (member_new_p)
3343    {
3344      /* Use a class-specific operator new.  */
3345      /* If a cookie is required, add some extra space.  */
3346      if (array_p && TYPE_VEC_NEW_USES_COOKIE (elt_type))
3347	size = size_binop (PLUS_EXPR, size, cookie_size);
3348      else
3349	{
3350	  cookie_size = NULL_TREE;
3351	  /* No size arithmetic necessary, so the size check is
3352	     not needed. */
3353	  if (outer_nelts_check != NULL && inner_size == 1)
3354	    outer_nelts_check = NULL_TREE;
3355	}
3356      /* Perform the overflow check.  */
3357      tree errval = TYPE_MAX_VALUE (sizetype);
3358      if (cxx_dialect >= cxx11 && flag_exceptions)
3359	errval = throw_bad_array_new_length ();
3360      if (outer_nelts_check != NULL_TREE)
3361	size = fold_build3 (COND_EXPR, sizetype, outer_nelts_check,
3362			    size, errval);
3363      /* Create the argument list.  */
3364      vec_safe_insert (*placement, 0, size);
3365      /* Do name-lookup to find the appropriate operator.  */
3366      fns = lookup_fnfields (elt_type, fnname, /*protect=*/2, complain);
3367      if (fns == NULL_TREE)
3368	{
3369	  if (complain & tf_error)
3370	    error ("no suitable %qD found in class %qT", fnname, elt_type);
3371	  return error_mark_node;
3372	}
3373      if (TREE_CODE (fns) == TREE_LIST)
3374	{
3375	  if (complain & tf_error)
3376	    {
3377	      error ("request for member %qD is ambiguous", fnname);
3378	      print_candidates (fns);
3379	    }
3380	  return error_mark_node;
3381	}
3382      tree dummy = build_dummy_object (elt_type);
3383      alloc_call = NULL_TREE;
3384      if (align_arg)
3385	{
3386	  vec<tree, va_gc> *align_args
3387	    = vec_copy_and_insert (*placement, align_arg, 1);
3388	  alloc_call
3389	    = build_new_method_call (dummy, fns, &align_args,
3390				     /*conversion_path=*/NULL_TREE,
3391				     LOOKUP_NORMAL, &alloc_fn, tf_none);
3392	  /* If no matching function is found and the allocated object type
3393	     has new-extended alignment, the alignment argument is removed
3394	     from the argument list, and overload resolution is performed
3395	     again.  */
3396	  if (alloc_call == error_mark_node)
3397	    alloc_call = NULL_TREE;
3398	}
3399      if (!alloc_call)
3400	alloc_call = build_new_method_call (dummy, fns, placement,
3401					    /*conversion_path=*/NULL_TREE,
3402					    LOOKUP_NORMAL,
3403					    &alloc_fn, complain);
3404    }
3405  else
3406    {
3407      /* Use a global operator new.  */
3408      /* See if a cookie might be required.  */
3409      if (!(array_p && TYPE_VEC_NEW_USES_COOKIE (elt_type)))
3410	{
3411	  cookie_size = NULL_TREE;
3412	  /* No size arithmetic necessary, so the size check is
3413	     not needed. */
3414	  if (outer_nelts_check != NULL && inner_size == 1)
3415	    outer_nelts_check = NULL_TREE;
3416	}
3417
3418      /* If size is zero e.g. due to type having zero size, try to
3419	 preserve outer_nelts for constant expression evaluation
3420	 purposes.  */
3421      if (integer_zerop (size) && outer_nelts)
3422	size = build2 (MULT_EXPR, TREE_TYPE (size), size, outer_nelts);
3423
3424      alloc_call = build_operator_new_call (fnname, placement,
3425					    &size, &cookie_size,
3426					    align_arg, outer_nelts_check,
3427					    &alloc_fn, complain);
3428    }
3429
3430  if (alloc_call == error_mark_node)
3431    return error_mark_node;
3432
3433  gcc_assert (alloc_fn != NULL_TREE);
3434
3435  /* Now, check to see if this function is actually a placement
3436     allocation function.  This can happen even when PLACEMENT is NULL
3437     because we might have something like:
3438
3439       struct S { void* operator new (size_t, int i = 0); };
3440
3441     A call to `new S' will get this allocation function, even though
3442     there is no explicit placement argument.  If there is more than
3443     one argument, or there are variable arguments, then this is a
3444     placement allocation function.  */
3445  placement_allocation_fn_p
3446    = (type_num_arguments (TREE_TYPE (alloc_fn)) > 1
3447       || varargs_function_p (alloc_fn));
3448
3449  if (complain & tf_warning_or_error
3450      && warn_aligned_new
3451      && !placement_allocation_fn_p
3452      && TYPE_ALIGN (elt_type) > malloc_alignment ()
3453      && (warn_aligned_new > 1
3454	  || CP_DECL_CONTEXT (alloc_fn) == global_namespace)
3455      && !aligned_allocation_fn_p (alloc_fn))
3456    {
3457      auto_diagnostic_group d;
3458      if (warning (OPT_Waligned_new_, "%<new%> of type %qT with extended "
3459		   "alignment %d", elt_type, TYPE_ALIGN_UNIT (elt_type)))
3460	{
3461	  inform (input_location, "uses %qD, which does not have an alignment "
3462		  "parameter", alloc_fn);
3463	  if (!aligned_new_threshold)
3464	    inform (input_location, "use %<-faligned-new%> to enable C++17 "
3465				    "over-aligned new support");
3466	}
3467    }
3468
3469  /* If we found a simple case of PLACEMENT_EXPR above, then copy it
3470     into a temporary variable.  */
3471  if (!processing_template_decl
3472      && TREE_CODE (alloc_call) == CALL_EXPR
3473      && call_expr_nargs (alloc_call) == 2
3474      && TREE_CODE (TREE_TYPE (CALL_EXPR_ARG (alloc_call, 0))) == INTEGER_TYPE
3475      && TYPE_PTR_P (TREE_TYPE (CALL_EXPR_ARG (alloc_call, 1))))
3476    {
3477      tree placement = CALL_EXPR_ARG (alloc_call, 1);
3478
3479      if (placement_first != NULL_TREE
3480	  && (INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (TREE_TYPE (placement)))
3481	      || VOID_TYPE_P (TREE_TYPE (TREE_TYPE (placement)))))
3482	{
3483	  placement_expr = get_target_expr (placement_first);
3484	  CALL_EXPR_ARG (alloc_call, 1)
3485	    = fold_convert (TREE_TYPE (placement), placement_expr);
3486	}
3487
3488      if (!member_new_p
3489	  && VOID_TYPE_P (TREE_TYPE (TREE_TYPE (CALL_EXPR_ARG (alloc_call, 1)))))
3490	{
3491	  /* Attempt to make the warning point at the operator new argument.  */
3492	  if (placement_first)
3493	    placement = placement_first;
3494
3495	  warn_placement_new_too_small (orig_type, nelts, size, placement);
3496	}
3497    }
3498
3499  alloc_expr = alloc_call;
3500  if (cookie_size)
3501    alloc_expr = maybe_wrap_new_for_constexpr (alloc_expr, type,
3502					       cookie_size);
3503
3504  /* In the simple case, we can stop now.  */
3505  pointer_type = build_pointer_type (type);
3506  if (!cookie_size && !is_initialized && !member_delete_p)
3507    return build_nop (pointer_type, alloc_expr);
3508
3509  /* Store the result of the allocation call in a variable so that we can
3510     use it more than once.  */
3511  alloc_expr = get_target_expr (alloc_expr);
3512  alloc_node = TARGET_EXPR_SLOT (alloc_expr);
3513
3514  /* Strip any COMPOUND_EXPRs from ALLOC_CALL.  */
3515  while (TREE_CODE (alloc_call) == COMPOUND_EXPR)
3516    alloc_call = TREE_OPERAND (alloc_call, 1);
3517
3518  /* Preevaluate the placement args so that we don't reevaluate them for a
3519     placement delete.  */
3520  if (placement_allocation_fn_p)
3521    {
3522      tree inits;
3523      stabilize_call (alloc_call, &inits);
3524      if (inits)
3525	alloc_expr = build2 (COMPOUND_EXPR, TREE_TYPE (alloc_expr), inits,
3526			     alloc_expr);
3527    }
3528
3529  /*        unless an allocation function is declared with an empty  excep-
3530     tion-specification  (_except.spec_),  throw(), it indicates failure to
3531     allocate storage by throwing a bad_alloc exception  (clause  _except_,
3532     _lib.bad.alloc_); it returns a non-null pointer otherwise If the allo-
3533     cation function is declared  with  an  empty  exception-specification,
3534     throw(), it returns null to indicate failure to allocate storage and a
3535     non-null pointer otherwise.
3536
3537     So check for a null exception spec on the op new we just called.  */
3538
3539  nothrow = TYPE_NOTHROW_P (TREE_TYPE (alloc_fn));
3540  check_new
3541    = flag_check_new || (nothrow && !std_placement_new_fn_p (alloc_fn));
3542
3543  if (cookie_size)
3544    {
3545      tree cookie;
3546      tree cookie_ptr;
3547      tree size_ptr_type;
3548
3549      /* Adjust so we're pointing to the start of the object.  */
3550      data_addr = fold_build_pointer_plus (alloc_node, cookie_size);
3551
3552      /* Store the number of bytes allocated so that we can know how
3553	 many elements to destroy later.  We use the last sizeof
3554	 (size_t) bytes to store the number of elements.  */
3555      cookie_ptr = size_binop (MINUS_EXPR, cookie_size, size_in_bytes (sizetype));
3556      cookie_ptr = fold_build_pointer_plus_loc (input_location,
3557						alloc_node, cookie_ptr);
3558      size_ptr_type = build_pointer_type (sizetype);
3559      cookie_ptr = fold_convert (size_ptr_type, cookie_ptr);
3560      cookie = cp_build_fold_indirect_ref (cookie_ptr);
3561
3562      cookie_expr = build2 (MODIFY_EXPR, sizetype, cookie, nelts);
3563
3564      if (targetm.cxx.cookie_has_size ())
3565	{
3566	  /* Also store the element size.  */
3567	  cookie_ptr = fold_build_pointer_plus (cookie_ptr,
3568			       fold_build1_loc (input_location,
3569						NEGATE_EXPR, sizetype,
3570						size_in_bytes (sizetype)));
3571
3572	  cookie = cp_build_fold_indirect_ref (cookie_ptr);
3573	  cookie = build2 (MODIFY_EXPR, sizetype, cookie,
3574			   size_in_bytes (elt_type));
3575	  cookie_expr = build2 (COMPOUND_EXPR, TREE_TYPE (cookie_expr),
3576				cookie, cookie_expr);
3577	}
3578    }
3579  else
3580    {
3581      cookie_expr = NULL_TREE;
3582      data_addr = alloc_node;
3583    }
3584
3585  /* Now use a pointer to the type we've actually allocated.  */
3586
3587  /* But we want to operate on a non-const version to start with,
3588     since we'll be modifying the elements.  */
3589  non_const_pointer_type = build_pointer_type
3590    (cp_build_qualified_type (type, cp_type_quals (type) & ~TYPE_QUAL_CONST));
3591
3592  data_addr = fold_convert (non_const_pointer_type, data_addr);
3593  /* Any further uses of alloc_node will want this type, too.  */
3594  alloc_node = fold_convert (non_const_pointer_type, alloc_node);
3595
3596  /* Now initialize the allocated object.  Note that we preevaluate the
3597     initialization expression, apart from the actual constructor call or
3598     assignment--we do this because we want to delay the allocation as long
3599     as possible in order to minimize the size of the exception region for
3600     placement delete.  */
3601  if (is_initialized)
3602    {
3603      bool explicit_value_init_p = false;
3604
3605      if (*init != NULL && (*init)->is_empty ())
3606	{
3607	  *init = NULL;
3608	  explicit_value_init_p = true;
3609	}
3610
3611      if (processing_template_decl)
3612	{
3613	  /* Avoid an ICE when converting to a base in build_simple_base_path.
3614	     We'll throw this all away anyway, and build_new will create
3615	     a NEW_EXPR.  */
3616	  tree t = fold_convert (build_pointer_type (elt_type), data_addr);
3617	  /* build_value_init doesn't work in templates, and we don't need
3618	     the initializer anyway since we're going to throw it away and
3619	     rebuild it at instantiation time, so just build up a single
3620	     constructor call to get any appropriate diagnostics.  */
3621	  init_expr = cp_build_fold_indirect_ref (t);
3622	  if (type_build_ctor_call (elt_type))
3623	    init_expr = build_special_member_call (init_expr,
3624						   complete_ctor_identifier,
3625						   init, elt_type,
3626						   LOOKUP_NORMAL,
3627						   complain);
3628	}
3629      else if (array_p)
3630	{
3631	  tree vecinit = NULL_TREE;
3632	  const size_t len = vec_safe_length (*init);
3633	  if (len == 1 && DIRECT_LIST_INIT_P ((**init)[0]))
3634	    {
3635	      vecinit = (**init)[0];
3636	      if (CONSTRUCTOR_NELTS (vecinit) == 0)
3637		/* List-value-initialization, leave it alone.  */;
3638	      else
3639		{
3640		  tree arraytype, domain;
3641		  if (TREE_CONSTANT (nelts))
3642		    domain = compute_array_index_type (NULL_TREE, nelts,
3643						       complain);
3644		  else
3645		    /* We'll check the length at runtime.  */
3646		    domain = NULL_TREE;
3647		  arraytype = build_cplus_array_type (type, domain);
3648		  /* If we have new char[4]{"foo"}, we have to reshape
3649		     so that the STRING_CST isn't wrapped in { }.  */
3650		  vecinit = reshape_init (arraytype, vecinit, complain);
3651		  /* The middle end doesn't cope with the location wrapper
3652		     around a STRING_CST.  */
3653		  STRIP_ANY_LOCATION_WRAPPER (vecinit);
3654		  vecinit = digest_init (arraytype, vecinit, complain);
3655		}
3656	    }
3657	  else if (*init)
3658            {
3659              if (complain & tf_error)
3660                error ("parenthesized initializer in array new");
3661	      return error_mark_node;
3662            }
3663	  init_expr
3664	    = build_vec_init (data_addr,
3665			      cp_build_binary_op (input_location,
3666						  MINUS_EXPR, outer_nelts,
3667						  integer_one_node,
3668						  complain),
3669			      vecinit,
3670			      explicit_value_init_p,
3671			      /*from_array=*/0,
3672                              complain);
3673	}
3674      else
3675	{
3676	  init_expr = cp_build_fold_indirect_ref (data_addr);
3677
3678	  if (type_build_ctor_call (type) && !explicit_value_init_p)
3679	    {
3680	      init_expr = build_special_member_call (init_expr,
3681						     complete_ctor_identifier,
3682						     init, elt_type,
3683						     LOOKUP_NORMAL,
3684						     complain|tf_no_cleanup);
3685	    }
3686	  else if (explicit_value_init_p)
3687	    {
3688	      /* Something like `new int()'.  NO_CLEANUP is needed so
3689		 we don't try and build a (possibly ill-formed)
3690		 destructor.  */
3691	      tree val = build_value_init (type, complain | tf_no_cleanup);
3692	      if (val == error_mark_node)
3693		return error_mark_node;
3694	      init_expr = build2 (INIT_EXPR, type, init_expr, val);
3695	    }
3696	  else
3697	    {
3698	      tree ie;
3699
3700	      /* We are processing something like `new int (10)', which
3701		 means allocate an int, and initialize it with 10.
3702
3703		 In C++20, also handle `new A(1, 2)'.  */
3704	      if (cxx_dialect >= cxx20
3705		  && AGGREGATE_TYPE_P (type)
3706		  && (*init)->length () > 1)
3707		{
3708		  ie = build_constructor_from_vec (init_list_type_node, *init);
3709		  CONSTRUCTOR_IS_DIRECT_INIT (ie) = true;
3710		  CONSTRUCTOR_IS_PAREN_INIT (ie) = true;
3711		  ie = digest_init (type, ie, complain);
3712		}
3713	      else
3714		ie = build_x_compound_expr_from_vec (*init, "new initializer",
3715						     complain);
3716	      init_expr = cp_build_modify_expr (input_location, init_expr,
3717						INIT_EXPR, ie, complain);
3718	    }
3719	  /* If the initializer uses C++14 aggregate NSDMI that refer to the
3720	     object being initialized, replace them now and don't try to
3721	     preevaluate.  */
3722	  bool had_placeholder = false;
3723	  if (!processing_template_decl
3724	      && TREE_CODE (init_expr) == INIT_EXPR)
3725	    TREE_OPERAND (init_expr, 1)
3726	      = replace_placeholders (TREE_OPERAND (init_expr, 1),
3727				      TREE_OPERAND (init_expr, 0),
3728				      &had_placeholder);
3729	}
3730
3731      if (init_expr == error_mark_node)
3732	return error_mark_node;
3733    }
3734  else
3735    init_expr = NULL_TREE;
3736
3737  /* If any part of the object initialization terminates by throwing an
3738     exception and a suitable deallocation function can be found, the
3739     deallocation function is called to free the memory in which the
3740     object was being constructed, after which the exception continues
3741     to propagate in the context of the new-expression. If no
3742     unambiguous matching deallocation function can be found,
3743     propagating the exception does not cause the object's memory to be
3744     freed.  */
3745  if (flag_exceptions && (init_expr || member_delete_p))
3746    {
3747      enum tree_code dcode = array_p ? VEC_DELETE_EXPR : DELETE_EXPR;
3748      tree cleanup;
3749
3750      /* The Standard is unclear here, but the right thing to do
3751	 is to use the same method for finding deallocation
3752	 functions that we use for finding allocation functions.  */
3753      cleanup = (build_op_delete_call
3754		 (dcode,
3755		  alloc_node,
3756		  size,
3757		  globally_qualified_p,
3758		  placement_allocation_fn_p ? alloc_call : NULL_TREE,
3759		  alloc_fn,
3760		  complain));
3761
3762      if (cleanup && init_expr && !processing_template_decl)
3763	/* Ack!  First we allocate the memory.  Then we set our sentry
3764	   variable to true, and expand a cleanup that deletes the
3765	   memory if sentry is true.  Then we run the constructor, and
3766	   finally clear the sentry.
3767
3768	   We need to do this because we allocate the space first, so
3769	   if there are any temporaries with cleanups in the
3770	   constructor args, we need this EH region to extend until
3771	   end of full-expression to preserve nesting.
3772
3773	   We used to try to evaluate the args first to avoid this, but
3774	   since C++17 [expr.new] says that "The invocation of the
3775	   allocation function is sequenced before the evaluations of
3776	   expressions in the new-initializer."  */
3777	{
3778	  tree end, sentry, begin;
3779
3780	  begin = get_target_expr (boolean_true_node);
3781	  CLEANUP_EH_ONLY (begin) = 1;
3782
3783	  sentry = TARGET_EXPR_SLOT (begin);
3784
3785	  /* CLEANUP is compiler-generated, so no diagnostics.  */
3786	  suppress_warning (cleanup);
3787
3788	  TARGET_EXPR_CLEANUP (begin)
3789	    = build3 (COND_EXPR, void_type_node, sentry,
3790		      cleanup, void_node);
3791
3792	  end = build2 (MODIFY_EXPR, TREE_TYPE (sentry),
3793			sentry, boolean_false_node);
3794
3795	  init_expr
3796	    = build2 (COMPOUND_EXPR, void_type_node, begin,
3797		      build2 (COMPOUND_EXPR, void_type_node, init_expr,
3798			      end));
3799	  /* Likewise, this is compiler-generated.  */
3800	  suppress_warning (init_expr);
3801	}
3802    }
3803
3804  /* Now build up the return value in reverse order.  */
3805
3806  rval = data_addr;
3807
3808  if (init_expr)
3809    rval = build2 (COMPOUND_EXPR, TREE_TYPE (rval), init_expr, rval);
3810  if (cookie_expr)
3811    rval = build2 (COMPOUND_EXPR, TREE_TYPE (rval), cookie_expr, rval);
3812
3813  if (rval == data_addr && TREE_CODE (alloc_expr) == TARGET_EXPR)
3814    /* If we don't have an initializer or a cookie, strip the TARGET_EXPR
3815       and return the call (which doesn't need to be adjusted).  */
3816    rval = TARGET_EXPR_INITIAL (alloc_expr);
3817  else
3818    {
3819      if (check_new)
3820	{
3821	  tree ifexp = cp_build_binary_op (input_location,
3822					   NE_EXPR, alloc_node,
3823					   nullptr_node,
3824					   complain);
3825	  rval = build_conditional_expr (input_location, ifexp, rval,
3826					 alloc_node, complain);
3827	}
3828
3829      /* Perform the allocation before anything else, so that ALLOC_NODE
3830	 has been initialized before we start using it.  */
3831      rval = build2 (COMPOUND_EXPR, TREE_TYPE (rval), alloc_expr, rval);
3832    }
3833
3834  /* A new-expression is never an lvalue.  */
3835  gcc_assert (!obvalue_p (rval));
3836
3837  return convert (pointer_type, rval);
3838}
3839
3840/* Generate a representation for a C++ "new" expression.  *PLACEMENT
3841   is a vector of placement-new arguments (or NULL if none).  If NELTS
3842   is NULL, TYPE is the type of the storage to be allocated.  If NELTS
3843   is not NULL, then this is an array-new allocation; TYPE is the type
3844   of the elements in the array and NELTS is the number of elements in
3845   the array.  *INIT, if non-NULL, is the initializer for the new
3846   object, or an empty vector to indicate an initializer of "()".  If
3847   USE_GLOBAL_NEW is true, then the user explicitly wrote "::new"
3848   rather than just "new".  This may change PLACEMENT and INIT.  */
3849
3850tree
3851build_new (location_t loc, vec<tree, va_gc> **placement, tree type,
3852	   tree nelts, vec<tree, va_gc> **init, int use_global_new,
3853	   tsubst_flags_t complain)
3854{
3855  tree rval;
3856  vec<tree, va_gc> *orig_placement = NULL;
3857  tree orig_nelts = NULL_TREE;
3858  vec<tree, va_gc> *orig_init = NULL;
3859
3860  if (type == error_mark_node)
3861    return error_mark_node;
3862
3863  if (nelts == NULL_TREE
3864      /* Don't do auto deduction where it might affect mangling.  */
3865      && (!processing_template_decl || at_function_scope_p ()))
3866    {
3867      tree auto_node = type_uses_auto (type);
3868      if (auto_node)
3869	{
3870	  tree d_init = NULL_TREE;
3871	  const size_t len = vec_safe_length (*init);
3872	  /* E.g. new auto(x) must have exactly one element, or
3873	     a {} initializer will have one element.  */
3874	  if (len == 1)
3875	    {
3876	      d_init = (**init)[0];
3877	      d_init = resolve_nondeduced_context (d_init, complain);
3878	    }
3879	  /* For the rest, e.g. new A(1, 2, 3), create a list.  */
3880	  else if (len > 1)
3881	    {
3882	      unsigned int n;
3883	      tree t;
3884	      tree *pp = &d_init;
3885	      FOR_EACH_VEC_ELT (**init, n, t)
3886		{
3887		  t = resolve_nondeduced_context (t, complain);
3888		  *pp = build_tree_list (NULL_TREE, t);
3889		  pp = &TREE_CHAIN (*pp);
3890		}
3891	    }
3892	  type = do_auto_deduction (type, d_init, auto_node, complain);
3893	}
3894    }
3895
3896  if (processing_template_decl)
3897    {
3898      if (dependent_type_p (type)
3899	  || any_type_dependent_arguments_p (*placement)
3900	  || (nelts && type_dependent_expression_p (nelts))
3901	  || (nelts && *init)
3902	  || any_type_dependent_arguments_p (*init))
3903	return build_raw_new_expr (loc, *placement, type, nelts, *init,
3904				   use_global_new);
3905
3906      orig_placement = make_tree_vector_copy (*placement);
3907      orig_nelts = nelts;
3908      if (*init)
3909	{
3910	  orig_init = make_tree_vector_copy (*init);
3911	  /* Also copy any CONSTRUCTORs in *init, since reshape_init and
3912	     digest_init clobber them in place.  */
3913	  for (unsigned i = 0; i < orig_init->length(); ++i)
3914	    {
3915	      tree e = (**init)[i];
3916	      if (TREE_CODE (e) == CONSTRUCTOR)
3917		(**init)[i] = copy_node (e);
3918	    }
3919	}
3920
3921      make_args_non_dependent (*placement);
3922      if (nelts)
3923	nelts = build_non_dependent_expr (nelts);
3924      make_args_non_dependent (*init);
3925    }
3926
3927  if (nelts)
3928    {
3929      location_t nelts_loc = cp_expr_loc_or_loc (nelts, loc);
3930      if (!build_expr_type_conversion (WANT_INT | WANT_ENUM, nelts, false))
3931        {
3932          if (complain & tf_error)
3933	    permerror (nelts_loc,
3934		       "size in array new must have integral type");
3935          else
3936            return error_mark_node;
3937        }
3938
3939      /* Try to determine the constant value only for the purposes
3940	 of the diagnostic below but continue to use the original
3941	 value and handle const folding later.  */
3942      const_tree cst_nelts = fold_non_dependent_expr (nelts, complain);
3943
3944      /* The expression in a noptr-new-declarator is erroneous if it's of
3945	 non-class type and its value before converting to std::size_t is
3946	 less than zero. ... If the expression is a constant expression,
3947	 the program is ill-fomed.  */
3948      if (TREE_CODE (cst_nelts) == INTEGER_CST
3949	  && !valid_array_size_p (nelts_loc, cst_nelts, NULL_TREE,
3950				  complain & tf_error))
3951	return error_mark_node;
3952
3953      nelts = mark_rvalue_use (nelts);
3954      nelts = cp_save_expr (cp_convert (sizetype, nelts, complain));
3955    }
3956
3957  /* ``A reference cannot be created by the new operator.  A reference
3958     is not an object (8.2.2, 8.4.3), so a pointer to it could not be
3959     returned by new.'' ARM 5.3.3 */
3960  if (TYPE_REF_P (type))
3961    {
3962      if (complain & tf_error)
3963        error_at (loc, "new cannot be applied to a reference type");
3964      else
3965        return error_mark_node;
3966      type = TREE_TYPE (type);
3967    }
3968
3969  if (TREE_CODE (type) == FUNCTION_TYPE)
3970    {
3971      if (complain & tf_error)
3972        error_at (loc, "new cannot be applied to a function type");
3973      return error_mark_node;
3974    }
3975
3976  /* P1009: Array size deduction in new-expressions.  */
3977  const bool array_p = TREE_CODE (type) == ARRAY_TYPE;
3978  if (*init
3979      /* If ARRAY_P, we have to deduce the array bound.  For C++20 paren-init,
3980	 we have to process the parenthesized-list.  But don't do it for (),
3981	 which is value-initialization, and INIT should stay empty.  */
3982      && (array_p || (cxx_dialect >= cxx20 && nelts && !(*init)->is_empty ())))
3983    {
3984      /* This means we have 'new T[]()'.  */
3985      if ((*init)->is_empty ())
3986	{
3987	  tree ctor = build_constructor (init_list_type_node, NULL);
3988	  CONSTRUCTOR_IS_DIRECT_INIT (ctor) = true;
3989	  vec_safe_push (*init, ctor);
3990	}
3991      tree &elt = (**init)[0];
3992      /* The C++20 'new T[](e_0, ..., e_k)' case allowed by P0960.  */
3993      if (!DIRECT_LIST_INIT_P (elt) && cxx_dialect >= cxx20)
3994	{
3995	  tree ctor = build_constructor_from_vec (init_list_type_node, *init);
3996	  CONSTRUCTOR_IS_DIRECT_INIT (ctor) = true;
3997	  CONSTRUCTOR_IS_PAREN_INIT (ctor) = true;
3998	  elt = ctor;
3999	  /* We've squashed all the vector elements into the first one;
4000	     truncate the rest.  */
4001	  (*init)->truncate (1);
4002	}
4003      /* Otherwise we should have 'new T[]{e_0, ..., e_k}'.  */
4004      if (array_p && !TYPE_DOMAIN (type))
4005	{
4006	  /* We need to reshape before deducing the bounds to handle code like
4007
4008	       struct S { int x, y; };
4009	       new S[]{1, 2, 3, 4};
4010
4011	     which should deduce S[2].	But don't change ELT itself: we want to
4012	     pass a list-initializer to build_new_1, even for STRING_CSTs.  */
4013	  tree e = elt;
4014	  if (BRACE_ENCLOSED_INITIALIZER_P (e))
4015	    e = reshape_init (type, e, complain);
4016	  cp_complete_array_type (&type, e, /*do_default*/false);
4017	}
4018    }
4019
4020  /* The type allocated must be complete.  If the new-type-id was
4021     "T[N]" then we are just checking that "T" is complete here, but
4022     that is equivalent, since the value of "N" doesn't matter.  */
4023  if (!complete_type_or_maybe_complain (type, NULL_TREE, complain))
4024    return error_mark_node;
4025
4026  rval = build_new_1 (placement, type, nelts, init, use_global_new, complain);
4027  if (rval == error_mark_node)
4028    return error_mark_node;
4029
4030  if (processing_template_decl)
4031    {
4032      tree ret = build_raw_new_expr (loc, orig_placement, type, orig_nelts,
4033				     orig_init, use_global_new);
4034      release_tree_vector (orig_placement);
4035      release_tree_vector (orig_init);
4036      return ret;
4037    }
4038
4039  /* Wrap it in a NOP_EXPR so warn_if_unused_value doesn't complain.  */
4040  rval = build1_loc (loc, NOP_EXPR, TREE_TYPE (rval), rval);
4041  suppress_warning (rval, OPT_Wunused_value);
4042
4043  return rval;
4044}
4045
4046static tree
4047build_vec_delete_1 (location_t loc, tree base, tree maxindex, tree type,
4048		    special_function_kind auto_delete_vec,
4049		    int use_global_delete, tsubst_flags_t complain,
4050		    bool in_cleanup = false)
4051{
4052  tree virtual_size;
4053  tree ptype = build_pointer_type (type = complete_type (type));
4054  tree size_exp;
4055
4056  /* Temporary variables used by the loop.  */
4057  tree tbase, tbase_init;
4058
4059  /* This is the body of the loop that implements the deletion of a
4060     single element, and moves temp variables to next elements.  */
4061  tree body;
4062
4063  /* This is the LOOP_EXPR that governs the deletion of the elements.  */
4064  tree loop = 0;
4065
4066  /* This is the thing that governs what to do after the loop has run.  */
4067  tree deallocate_expr = 0;
4068
4069  /* This is the BIND_EXPR which holds the outermost iterator of the
4070     loop.  It is convenient to set this variable up and test it before
4071     executing any other code in the loop.
4072     This is also the containing expression returned by this function.  */
4073  tree controller = NULL_TREE;
4074  tree tmp;
4075
4076  /* We should only have 1-D arrays here.  */
4077  gcc_assert (TREE_CODE (type) != ARRAY_TYPE);
4078
4079  if (base == error_mark_node || maxindex == error_mark_node)
4080    return error_mark_node;
4081
4082  if (!verify_type_context (loc, TCTX_DEALLOCATION, type,
4083			    !(complain & tf_error)))
4084    return error_mark_node;
4085
4086  if (!COMPLETE_TYPE_P (type))
4087    {
4088      if (complain & tf_warning)
4089	{
4090	  auto_diagnostic_group d;
4091	  if (warning_at (loc, OPT_Wdelete_incomplete,
4092			  "possible problem detected in invocation of "
4093			  "operator %<delete []%>"))
4094	    {
4095	      cxx_incomplete_type_diagnostic (base, type, DK_WARNING);
4096	      inform (loc, "neither the destructor nor the "
4097		      "class-specific operator %<delete []%> will be called, "
4098		      "even if they are declared when the class is defined");
4099	    }
4100	}
4101      /* This size won't actually be used.  */
4102      size_exp = size_one_node;
4103      goto no_destructor;
4104    }
4105
4106  size_exp = size_in_bytes (type);
4107
4108  if (! MAYBE_CLASS_TYPE_P (type))
4109    goto no_destructor;
4110  else if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
4111    {
4112      /* Make sure the destructor is callable.  */
4113      if (type_build_dtor_call (type))
4114	{
4115	  tmp = build_delete (loc, ptype, base, sfk_complete_destructor,
4116			      LOOKUP_NORMAL|LOOKUP_DESTRUCTOR, 1,
4117			      complain);
4118	  if (tmp == error_mark_node)
4119	    return error_mark_node;
4120	}
4121      goto no_destructor;
4122    }
4123
4124  /* The below is short by the cookie size.  */
4125  virtual_size = size_binop (MULT_EXPR, size_exp,
4126			     fold_convert (sizetype, maxindex));
4127
4128  tbase = create_temporary_var (ptype);
4129  DECL_INITIAL (tbase)
4130    = fold_build_pointer_plus_loc (loc, fold_convert (ptype, base),
4131				   virtual_size);
4132  tbase_init = build_stmt (loc, DECL_EXPR, tbase);
4133  controller = build3 (BIND_EXPR, void_type_node, tbase, NULL_TREE, NULL_TREE);
4134  TREE_SIDE_EFFECTS (controller) = 1;
4135  BIND_EXPR_VEC_DTOR (controller) = true;
4136
4137  body = build1 (EXIT_EXPR, void_type_node,
4138		 build2 (EQ_EXPR, boolean_type_node, tbase,
4139			 fold_convert (ptype, base)));
4140  tmp = fold_build1_loc (loc, NEGATE_EXPR, sizetype, size_exp);
4141  tmp = fold_build_pointer_plus (tbase, tmp);
4142  tmp = cp_build_modify_expr (loc, tbase, NOP_EXPR, tmp, complain);
4143  if (tmp == error_mark_node)
4144    return error_mark_node;
4145  body = build_compound_expr (loc, body, tmp);
4146  tmp = build_delete (loc, ptype, tbase, sfk_complete_destructor,
4147		      LOOKUP_NORMAL|LOOKUP_DESTRUCTOR, 1,
4148		      complain);
4149  if (tmp == error_mark_node)
4150    return error_mark_node;
4151  body = build_compound_expr (loc, body, tmp);
4152
4153  loop = build1 (LOOP_EXPR, void_type_node, body);
4154
4155  /* If one destructor throws, keep trying to clean up the rest, unless we're
4156     already in a build_vec_init cleanup.  */
4157  if (flag_exceptions && !in_cleanup && !expr_noexcept_p (tmp, tf_none))
4158    {
4159      loop = build2 (TRY_CATCH_EXPR, void_type_node, loop,
4160		     unshare_expr (loop));
4161      /* Tell honor_protect_cleanup_actions to discard this on the
4162	 exceptional path.  */
4163      TRY_CATCH_IS_CLEANUP (loop) = true;
4164    }
4165
4166  loop = build_compound_expr (loc, tbase_init, loop);
4167
4168 no_destructor:
4169  /* Delete the storage if appropriate.  */
4170  if (auto_delete_vec == sfk_deleting_destructor)
4171    {
4172      tree base_tbd;
4173
4174      /* The below is short by the cookie size.  */
4175      virtual_size = size_binop (MULT_EXPR, size_exp,
4176				 fold_convert (sizetype, maxindex));
4177
4178      if (! TYPE_VEC_NEW_USES_COOKIE (type))
4179	/* no header */
4180	base_tbd = base;
4181      else
4182	{
4183	  tree cookie_size;
4184
4185	  cookie_size = targetm.cxx.get_cookie_size (type);
4186	  base_tbd = cp_build_binary_op (loc,
4187					 MINUS_EXPR,
4188					 cp_convert (string_type_node,
4189						     base, complain),
4190					 cookie_size,
4191					 complain);
4192	  if (base_tbd == error_mark_node)
4193	    return error_mark_node;
4194	  base_tbd = cp_convert (ptype, base_tbd, complain);
4195	  /* True size with header.  */
4196	  virtual_size = size_binop (PLUS_EXPR, virtual_size, cookie_size);
4197	}
4198
4199      deallocate_expr = build_op_delete_call (VEC_DELETE_EXPR,
4200					      base_tbd, virtual_size,
4201					      use_global_delete & 1,
4202					      /*placement=*/NULL_TREE,
4203					      /*alloc_fn=*/NULL_TREE,
4204					      complain);
4205    }
4206
4207  body = loop;
4208  if (deallocate_expr == error_mark_node)
4209    return error_mark_node;
4210  else if (!deallocate_expr)
4211    ;
4212  else if (!body)
4213    body = deallocate_expr;
4214  else
4215    /* The delete operator must be called, even if a destructor
4216       throws.  */
4217    body = build2 (TRY_FINALLY_EXPR, void_type_node, body, deallocate_expr);
4218
4219  if (!body)
4220    body = integer_zero_node;
4221
4222  /* Outermost wrapper: If pointer is null, punt.  */
4223  tree cond = build2_loc (loc, NE_EXPR, boolean_type_node, base,
4224			  fold_convert (TREE_TYPE (base), nullptr_node));
4225  /* This is a compiler generated comparison, don't emit
4226     e.g. -Wnonnull-compare warning for it.  */
4227  suppress_warning (cond, OPT_Wnonnull_compare);
4228  body = build3_loc (loc, COND_EXPR, void_type_node,
4229		     cond, body, integer_zero_node);
4230  COND_EXPR_IS_VEC_DELETE (body) = true;
4231  body = build1 (NOP_EXPR, void_type_node, body);
4232
4233  if (controller)
4234    {
4235      TREE_OPERAND (controller, 1) = body;
4236      body = controller;
4237    }
4238
4239  if (TREE_CODE (base) == SAVE_EXPR)
4240    /* Pre-evaluate the SAVE_EXPR outside of the BIND_EXPR.  */
4241    body = build2 (COMPOUND_EXPR, void_type_node, base, body);
4242
4243  return convert_to_void (body, ICV_CAST, complain);
4244}
4245
4246/* Create an unnamed variable of the indicated TYPE.  */
4247
4248tree
4249create_temporary_var (tree type)
4250{
4251  tree decl;
4252
4253  decl = build_decl (input_location,
4254		     VAR_DECL, NULL_TREE, type);
4255  TREE_USED (decl) = 1;
4256  DECL_ARTIFICIAL (decl) = 1;
4257  DECL_IGNORED_P (decl) = 1;
4258  DECL_CONTEXT (decl) = current_function_decl;
4259
4260  return decl;
4261}
4262
4263/* Create a new temporary variable of the indicated TYPE, initialized
4264   to INIT.
4265
4266   It is not entered into current_binding_level, because that breaks
4267   things when it comes time to do final cleanups (which take place
4268   "outside" the binding contour of the function).  */
4269
4270tree
4271get_temp_regvar (tree type, tree init)
4272{
4273  tree decl;
4274
4275  decl = create_temporary_var (type);
4276  add_decl_expr (decl);
4277
4278  finish_expr_stmt (cp_build_modify_expr (input_location, decl, INIT_EXPR,
4279					  init, tf_warning_or_error));
4280
4281  return decl;
4282}
4283
4284/* Subroutine of build_vec_init.  Returns true if assigning to an array of
4285   INNER_ELT_TYPE from INIT is trivial.  */
4286
4287static bool
4288vec_copy_assign_is_trivial (tree inner_elt_type, tree init)
4289{
4290  tree fromtype = inner_elt_type;
4291  if (lvalue_p (init))
4292    fromtype = cp_build_reference_type (fromtype, /*rval*/false);
4293  return is_trivially_xible (MODIFY_EXPR, inner_elt_type, fromtype);
4294}
4295
4296/* Subroutine of build_vec_init: Check that the array has at least N
4297   elements.  Other parameters are local variables in build_vec_init.  */
4298
4299void
4300finish_length_check (tree atype, tree iterator, tree obase, unsigned n)
4301{
4302  tree nelts = build_int_cst (ptrdiff_type_node, n - 1);
4303  if (TREE_CODE (atype) != ARRAY_TYPE)
4304    {
4305      if (flag_exceptions)
4306	{
4307	  tree c = fold_build2 (LT_EXPR, boolean_type_node, iterator,
4308				nelts);
4309	  c = build3 (COND_EXPR, void_type_node, c,
4310		      throw_bad_array_new_length (), void_node);
4311	  finish_expr_stmt (c);
4312	}
4313      /* Don't check an array new when -fno-exceptions.  */
4314    }
4315  else if (sanitize_flags_p (SANITIZE_BOUNDS)
4316	   && current_function_decl != NULL_TREE)
4317    {
4318      /* Make sure the last element of the initializer is in bounds. */
4319      finish_expr_stmt
4320	(ubsan_instrument_bounds
4321	 (input_location, obase, &nelts, /*ignore_off_by_one*/false));
4322    }
4323}
4324
4325/* `build_vec_init' returns tree structure that performs
4326   initialization of a vector of aggregate types.
4327
4328   BASE is a reference to the vector, of ARRAY_TYPE, or a pointer
4329     to the first element, of POINTER_TYPE.
4330   MAXINDEX is the maximum index of the array (one less than the
4331     number of elements).  It is only used if BASE is a pointer or
4332     TYPE_DOMAIN (TREE_TYPE (BASE)) == NULL_TREE.
4333
4334   INIT is the (possibly NULL) initializer.
4335
4336   If EXPLICIT_VALUE_INIT_P is true, then INIT must be NULL.  All
4337   elements in the array are value-initialized.
4338
4339   FROM_ARRAY is 0 if we should init everything with INIT
4340   (i.e., every element initialized from INIT).
4341   FROM_ARRAY is 1 if we should index into INIT in parallel
4342   with initialization of DECL.
4343   FROM_ARRAY is 2 if we should index into INIT in parallel,
4344   but use assignment instead of initialization.  */
4345
4346tree
4347build_vec_init (tree base, tree maxindex, tree init,
4348		bool explicit_value_init_p,
4349		int from_array,
4350		tsubst_flags_t complain,
4351		vec<tree, va_gc>** flags /* = nullptr */)
4352{
4353  tree rval;
4354  tree base2 = NULL_TREE;
4355  tree itype = NULL_TREE;
4356  tree iterator;
4357  /* The type of BASE.  */
4358  tree atype = TREE_TYPE (base);
4359  /* The type of an element in the array.  */
4360  tree type = TREE_TYPE (atype);
4361  /* The element type reached after removing all outer array
4362     types.  */
4363  tree inner_elt_type;
4364  /* The type of a pointer to an element in the array.  */
4365  tree ptype;
4366  tree stmt_expr;
4367  tree compound_stmt;
4368  int destroy_temps;
4369  HOST_WIDE_INT num_initialized_elts = 0;
4370  bool is_global;
4371  tree obase = base;
4372  bool xvalue = false;
4373  bool errors = false;
4374  location_t loc = (init ? cp_expr_loc_or_input_loc (init)
4375		    : location_of (base));
4376
4377  if (TREE_CODE (atype) == ARRAY_TYPE && TYPE_DOMAIN (atype))
4378    maxindex = array_type_nelts (atype);
4379
4380  if (maxindex == NULL_TREE || maxindex == error_mark_node)
4381    return error_mark_node;
4382
4383  maxindex = maybe_constant_value (maxindex);
4384  if (explicit_value_init_p)
4385    gcc_assert (!init);
4386
4387  inner_elt_type = strip_array_types (type);
4388
4389  /* Look through the TARGET_EXPR around a compound literal.  */
4390  if (init && TREE_CODE (init) == TARGET_EXPR
4391      && TREE_CODE (TARGET_EXPR_INITIAL (init)) == CONSTRUCTOR
4392      && from_array != 2)
4393    init = TARGET_EXPR_INITIAL (init);
4394
4395  if (tree vi = get_vec_init_expr (init))
4396    init = VEC_INIT_EXPR_INIT (vi);
4397
4398  bool direct_init = false;
4399  if (from_array && init && BRACE_ENCLOSED_INITIALIZER_P (init)
4400      && CONSTRUCTOR_NELTS (init) == 1)
4401    {
4402      tree elt = CONSTRUCTOR_ELT (init, 0)->value;
4403      if (TREE_CODE (TREE_TYPE (elt)) == ARRAY_TYPE
4404	  && TREE_CODE (elt) != VEC_INIT_EXPR)
4405	{
4406	  direct_init = DIRECT_LIST_INIT_P (init);
4407	  init = elt;
4408	}
4409    }
4410
4411  /* If we have a braced-init-list or string constant, make sure that the array
4412     is big enough for all the initializers.  */
4413  bool length_check = (init
4414		       && (TREE_CODE (init) == STRING_CST
4415			   || (TREE_CODE (init) == CONSTRUCTOR
4416			       && CONSTRUCTOR_NELTS (init) > 0))
4417		       && !TREE_CONSTANT (maxindex));
4418
4419  if (init
4420      && TREE_CODE (atype) == ARRAY_TYPE
4421      && TREE_CONSTANT (maxindex)
4422      && !vla_type_p (type)
4423      && (from_array == 2
4424	  ? vec_copy_assign_is_trivial (inner_elt_type, init)
4425	  : !TYPE_NEEDS_CONSTRUCTING (type))
4426      && ((TREE_CODE (init) == CONSTRUCTOR
4427	   && (BRACE_ENCLOSED_INITIALIZER_P (init)
4428	       || (same_type_ignoring_top_level_qualifiers_p
4429		   (atype, TREE_TYPE (init))))
4430	   /* Don't do this if the CONSTRUCTOR might contain something
4431	      that might throw and require us to clean up.  */
4432	   && (vec_safe_is_empty (CONSTRUCTOR_ELTS (init))
4433	       || ! TYPE_HAS_NONTRIVIAL_DESTRUCTOR (inner_elt_type)))
4434	  || from_array))
4435    {
4436      /* Do non-default initialization of trivial arrays resulting from
4437	 brace-enclosed initializers.  In this case, digest_init and
4438	 store_constructor will handle the semantics for us.  */
4439
4440      if (BRACE_ENCLOSED_INITIALIZER_P (init))
4441	init = digest_init (atype, init, complain);
4442      stmt_expr = build2 (INIT_EXPR, atype, base, init);
4443      return stmt_expr;
4444    }
4445
4446  maxindex = cp_convert (ptrdiff_type_node, maxindex, complain);
4447  maxindex = fold_simple (maxindex);
4448
4449  if (TREE_CODE (atype) == ARRAY_TYPE)
4450    {
4451      ptype = build_pointer_type (type);
4452      base = decay_conversion (base, complain);
4453      if (base == error_mark_node)
4454	return error_mark_node;
4455      base = cp_convert (ptype, base, complain);
4456    }
4457  else
4458    ptype = atype;
4459
4460  if (integer_all_onesp (maxindex))
4461    {
4462      /* Shortcut zero element case to avoid unneeded constructor synthesis.  */
4463      if (init && TREE_SIDE_EFFECTS (init))
4464	base = build2 (COMPOUND_EXPR, ptype, init, base);
4465      return base;
4466    }
4467
4468  /* The code we are generating looks like:
4469     ({
4470       T* t1 = (T*) base;
4471       T* rval = t1;
4472       ptrdiff_t iterator = maxindex;
4473       try {
4474	 for (; iterator != -1; --iterator) {
4475	   ... initialize *t1 ...
4476	   ++t1;
4477	 }
4478       } catch (...) {
4479	 ... destroy elements that were constructed ...
4480       }
4481       rval;
4482     })
4483
4484     We can omit the try and catch blocks if we know that the
4485     initialization will never throw an exception, or if the array
4486     elements do not have destructors.  We can omit the loop completely if
4487     the elements of the array do not have constructors.
4488
4489     We actually wrap the entire body of the above in a STMT_EXPR, for
4490     tidiness.
4491
4492     When copying from array to another, when the array elements have
4493     only trivial copy constructors, we should use __builtin_memcpy
4494     rather than generating a loop.  That way, we could take advantage
4495     of whatever cleverness the back end has for dealing with copies
4496     of blocks of memory.  */
4497
4498  is_global = begin_init_stmts (&stmt_expr, &compound_stmt);
4499  destroy_temps = stmts_are_full_exprs_p ();
4500  current_stmt_tree ()->stmts_are_full_exprs_p = 0;
4501  rval = get_temp_regvar (ptype, base);
4502  base = get_temp_regvar (ptype, rval);
4503  tree iterator_targ = get_target_expr (maxindex);
4504  add_stmt (iterator_targ);
4505  iterator = TARGET_EXPR_SLOT (iterator_targ);
4506
4507  /* If initializing one array from another, initialize element by
4508     element.  We rely upon the below calls to do the argument
4509     checking.  Evaluate the initializer before entering the try block.  */
4510  if (from_array && init && TREE_CODE (init) != CONSTRUCTOR)
4511    {
4512      if (lvalue_kind (init) & clk_rvalueref)
4513	xvalue = true;
4514      base2 = decay_conversion (init, complain);
4515      if (base2 == error_mark_node)
4516	return error_mark_node;
4517      itype = TREE_TYPE (base2);
4518      base2 = get_temp_regvar (itype, base2);
4519      itype = TREE_TYPE (itype);
4520    }
4521
4522  /* Protect the entire array initialization so that we can destroy
4523     the partially constructed array if an exception is thrown.
4524     But don't do this if we're assigning.  */
4525  if (flag_exceptions && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
4526      && from_array != 2)
4527    {
4528      tree e;
4529      tree m = cp_build_binary_op (input_location,
4530				   MINUS_EXPR, maxindex, iterator,
4531				   complain);
4532
4533      /* Flatten multi-dimensional array since build_vec_delete only
4534	 expects one-dimensional array.  */
4535      if (TREE_CODE (type) == ARRAY_TYPE)
4536	m = cp_build_binary_op (input_location,
4537				MULT_EXPR, m,
4538				/* Avoid mixing signed and unsigned.  */
4539				convert (TREE_TYPE (m),
4540					 array_type_nelts_total (type)),
4541				complain);
4542
4543      e = build_vec_delete_1 (input_location, rval, m,
4544			      inner_elt_type, sfk_complete_destructor,
4545			      /*use_global_delete=*/0, complain,
4546			      /*in_cleanup*/true);
4547      if (e == error_mark_node)
4548	errors = true;
4549      TARGET_EXPR_CLEANUP (iterator_targ) = e;
4550      CLEANUP_EH_ONLY (iterator_targ) = true;
4551
4552      /* Since we push this cleanup before doing any initialization, cleanups
4553	 for any temporaries in the initialization are naturally within our
4554	 cleanup region, so we don't want wrap_temporary_cleanups to do
4555	 anything for arrays.  But if the array is a subobject, we need to
4556	 tell split_nonconstant_init how to turn off this cleanup in favor of
4557	 the cleanup for the complete object.  */
4558      if (flags)
4559	vec_safe_push (*flags, build_tree_list (iterator, maxindex));
4560    }
4561
4562  /* Should we try to create a constant initializer?  */
4563  bool try_const = (TREE_CODE (atype) == ARRAY_TYPE
4564		    && TREE_CONSTANT (maxindex)
4565		    && (init ? TREE_CODE (init) == CONSTRUCTOR
4566			: (type_has_constexpr_default_constructor
4567			   (inner_elt_type)))
4568		    && (literal_type_p (inner_elt_type)
4569			|| TYPE_HAS_CONSTEXPR_CTOR (inner_elt_type)));
4570  vec<constructor_elt, va_gc> *const_vec = NULL;
4571  bool saw_non_const = false;
4572  /* If we're initializing a static array, we want to do static
4573     initialization of any elements with constant initializers even if
4574     some are non-constant.  */
4575  bool do_static_init = (DECL_P (obase) && TREE_STATIC (obase));
4576
4577  bool empty_list = false;
4578  if (init && BRACE_ENCLOSED_INITIALIZER_P (init)
4579      && CONSTRUCTOR_NELTS (init) == 0)
4580    /* Skip over the handling of non-empty init lists.  */
4581    empty_list = true;
4582
4583  /* Maybe pull out constant value when from_array? */
4584
4585  else if (init != NULL_TREE && TREE_CODE (init) == CONSTRUCTOR)
4586    {
4587      /* Do non-default initialization of non-trivial arrays resulting from
4588	 brace-enclosed initializers.  */
4589      unsigned HOST_WIDE_INT idx;
4590      tree field, elt;
4591      /* If the constructor already has the array type, it's been through
4592	 digest_init, so we shouldn't try to do anything more.  */
4593      bool digested = same_type_p (atype, TREE_TYPE (init));
4594      from_array = 0;
4595
4596      if (length_check)
4597	finish_length_check (atype, iterator, obase, CONSTRUCTOR_NELTS (init));
4598
4599      if (try_const)
4600	vec_alloc (const_vec, CONSTRUCTOR_NELTS (init));
4601
4602      FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (init), idx, field, elt)
4603	{
4604	  tree baseref = build1 (INDIRECT_REF, type, base);
4605	  tree one_init;
4606
4607	  num_initialized_elts++;
4608
4609	  /* We need to see sub-array TARGET_EXPR before cp_fold_r so we can
4610	     handle cleanup flags properly.  */
4611	  gcc_checking_assert (!target_expr_needs_replace (elt));
4612
4613	  if (digested)
4614	    one_init = build2 (INIT_EXPR, type, baseref, elt);
4615	  else if (tree vi = get_vec_init_expr (elt))
4616	    one_init = expand_vec_init_expr (baseref, vi, complain, flags);
4617	  else if (MAYBE_CLASS_TYPE_P (type) || TREE_CODE (type) == ARRAY_TYPE)
4618	    one_init = build_aggr_init (baseref, elt, 0, complain);
4619	  else
4620	    one_init = cp_build_modify_expr (input_location, baseref,
4621					     NOP_EXPR, elt, complain);
4622	  if (one_init == error_mark_node)
4623	    errors = true;
4624	  if (try_const)
4625	    {
4626	      if (!field)
4627		field = size_int (idx);
4628	      tree e = maybe_constant_init (one_init);
4629	      if (reduced_constant_expression_p (e))
4630		{
4631		  CONSTRUCTOR_APPEND_ELT (const_vec, field, e);
4632		  if (do_static_init)
4633		    one_init = NULL_TREE;
4634		  else
4635		    one_init = build2 (INIT_EXPR, type, baseref, e);
4636		}
4637	      else
4638		{
4639		  if (do_static_init)
4640		    {
4641		      tree value = build_zero_init (TREE_TYPE (e), NULL_TREE,
4642						    true);
4643		      if (value)
4644			CONSTRUCTOR_APPEND_ELT (const_vec, field, value);
4645		    }
4646		  saw_non_const = true;
4647		}
4648	    }
4649
4650	  if (one_init)
4651	    finish_expr_stmt (one_init);
4652
4653	  one_init = cp_build_unary_op (PREINCREMENT_EXPR, base, false,
4654					complain);
4655	  if (one_init == error_mark_node)
4656	    errors = true;
4657	  else
4658	    finish_expr_stmt (one_init);
4659
4660	  one_init = cp_build_unary_op (PREDECREMENT_EXPR, iterator, false,
4661					complain);
4662	  if (one_init == error_mark_node)
4663	    errors = true;
4664	  else
4665	    finish_expr_stmt (one_init);
4666	}
4667
4668      /* Any elements without explicit initializers get T{}.  */
4669      empty_list = true;
4670    }
4671  else if (init && TREE_CODE (init) == STRING_CST)
4672    {
4673      /* Check that the array is at least as long as the string.  */
4674      if (length_check)
4675	finish_length_check (atype, iterator, obase,
4676			     TREE_STRING_LENGTH (init));
4677      tree length = build_int_cst (ptrdiff_type_node,
4678				   TREE_STRING_LENGTH (init));
4679
4680      /* Copy the string to the first part of the array.  */
4681      tree alias_set = build_int_cst (build_pointer_type (type), 0);
4682      tree lhs = build2 (MEM_REF, TREE_TYPE (init), base, alias_set);
4683      tree stmt = build2 (MODIFY_EXPR, void_type_node, lhs, init);
4684      finish_expr_stmt (stmt);
4685
4686      /* Adjust the counter and pointer.  */
4687      stmt = cp_build_binary_op (loc, MINUS_EXPR, iterator, length, complain);
4688      stmt = build2 (MODIFY_EXPR, void_type_node, iterator, stmt);
4689      finish_expr_stmt (stmt);
4690
4691      stmt = cp_build_binary_op (loc, PLUS_EXPR, base, length, complain);
4692      stmt = build2 (MODIFY_EXPR, void_type_node, base, stmt);
4693      finish_expr_stmt (stmt);
4694
4695      /* And set the rest of the array to NUL.  */
4696      from_array = 0;
4697      explicit_value_init_p = true;
4698    }
4699  else if (from_array)
4700    {
4701      if (init)
4702	/* OK, we set base2 above.  */;
4703      else if (CLASS_TYPE_P (type)
4704	       && ! TYPE_HAS_DEFAULT_CONSTRUCTOR (type))
4705	{
4706          if (complain & tf_error)
4707            error ("initializer ends prematurely");
4708	  errors = true;
4709	}
4710    }
4711
4712  /* Now, default-initialize any remaining elements.  We don't need to
4713     do that if a) the type does not need constructing, or b) we've
4714     already initialized all the elements.
4715
4716     We do need to keep going if we're copying an array.  */
4717
4718  if (try_const && !init
4719      && (cxx_dialect < cxx20
4720	  || !default_init_uninitialized_part (inner_elt_type)))
4721    /* With a constexpr default constructor, which we checked for when
4722       setting try_const above, default-initialization is equivalent to
4723       value-initialization, and build_value_init gives us something more
4724       friendly to maybe_constant_init.  Except in C++20 and up a constexpr
4725       constructor need not initialize all the members.  */
4726    explicit_value_init_p = true;
4727  if (from_array
4728      || ((type_build_ctor_call (type) || init || explicit_value_init_p)
4729	  && ! (tree_fits_shwi_p (maxindex)
4730		&& (num_initialized_elts
4731		    == tree_to_shwi (maxindex) + 1))))
4732    {
4733      /* If the ITERATOR is lesser or equal to -1, then we don't have to loop;
4734	 we've already initialized all the elements.  */
4735      tree for_stmt;
4736      tree elt_init;
4737      tree to;
4738
4739      for_stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
4740      finish_init_stmt (for_stmt);
4741      finish_for_cond (build2 (GT_EXPR, boolean_type_node, iterator,
4742			       build_int_cst (TREE_TYPE (iterator), -1)),
4743		       for_stmt, false, 0);
4744      /* We used to pass this decrement to finish_for_expr; now we add it to
4745	 elt_init below so it's part of the same full-expression as the
4746	 initialization, and thus happens before any potentially throwing
4747	 temporary cleanups.  */
4748      tree decr = cp_build_unary_op (PREDECREMENT_EXPR, iterator, false,
4749				     complain);
4750
4751
4752      to = build1 (INDIRECT_REF, type, base);
4753
4754      /* If the initializer is {}, then all elements are initialized from T{}.
4755	 But for non-classes, that's the same as value-initialization.  */
4756      if (empty_list)
4757	{
4758	  if (cxx_dialect >= cxx11 && AGGREGATE_TYPE_P (type))
4759	    {
4760	      init = build_constructor (init_list_type_node, NULL);
4761	    }
4762	  else
4763	    {
4764	      init = NULL_TREE;
4765	      explicit_value_init_p = true;
4766	    }
4767	}
4768
4769      if (from_array)
4770	{
4771	  tree from;
4772
4773	  if (base2)
4774	    {
4775	      from = build1 (INDIRECT_REF, itype, base2);
4776	      if (xvalue)
4777		from = move (from);
4778	      if (direct_init)
4779		from = build_tree_list (NULL_TREE, from);
4780	    }
4781	  else
4782	    from = NULL_TREE;
4783
4784	  if (TREE_CODE (type) == ARRAY_TYPE)
4785	    elt_init = build_vec_init (to, NULL_TREE, from, /*val_init*/false,
4786				       from_array, complain);
4787	  else if (from_array == 2)
4788	    elt_init = cp_build_modify_expr (input_location, to, NOP_EXPR,
4789					     from, complain);
4790	  else if (type_build_ctor_call (type))
4791	    elt_init = build_aggr_init (to, from, 0, complain);
4792	  else if (from)
4793	    elt_init = cp_build_modify_expr (input_location, to, NOP_EXPR, from,
4794					     complain);
4795	  else
4796	    gcc_unreachable ();
4797	}
4798      else if (TREE_CODE (type) == ARRAY_TYPE)
4799	{
4800	  if (init && !BRACE_ENCLOSED_INITIALIZER_P (init))
4801	    {
4802	      if ((complain & tf_error))
4803		error_at (loc, "array must be initialized "
4804			  "with a brace-enclosed initializer");
4805	      elt_init = error_mark_node;
4806	    }
4807	  else
4808	    elt_init = build_vec_init (build1 (INDIRECT_REF, type, base),
4809				       0, init,
4810				       explicit_value_init_p,
4811				       0, complain);
4812	}
4813      else if (explicit_value_init_p)
4814	{
4815	  elt_init = build_value_init (type, complain);
4816	  if (elt_init != error_mark_node)
4817	    elt_init = build2 (INIT_EXPR, type, to, elt_init);
4818	}
4819      else
4820	{
4821	  gcc_assert (type_build_ctor_call (type) || init);
4822	  if (CLASS_TYPE_P (type))
4823	    elt_init = build_aggr_init (to, init, 0, complain);
4824	  else
4825	    {
4826	      if (TREE_CODE (init) == TREE_LIST)
4827		init = build_x_compound_expr_from_list (init, ELK_INIT,
4828							complain);
4829	      elt_init = (init == error_mark_node
4830			  ? error_mark_node
4831			  : build2 (INIT_EXPR, type, to, init));
4832	    }
4833	}
4834
4835      if (elt_init == error_mark_node)
4836	errors = true;
4837
4838      if (try_const)
4839	{
4840	  /* FIXME refs to earlier elts */
4841	  tree e = maybe_constant_init (elt_init);
4842	  if (reduced_constant_expression_p (e))
4843	    {
4844	      if (initializer_zerop (e))
4845		/* Don't fill the CONSTRUCTOR with zeros.  */
4846		e = NULL_TREE;
4847	      if (do_static_init)
4848		elt_init = NULL_TREE;
4849	    }
4850	  else
4851	    {
4852	      saw_non_const = true;
4853	      if (do_static_init)
4854		e = build_zero_init (TREE_TYPE (e), NULL_TREE, true);
4855	      else
4856		e = NULL_TREE;
4857	    }
4858
4859	  if (e)
4860	    {
4861	      HOST_WIDE_INT last = tree_to_shwi (maxindex);
4862	      if (num_initialized_elts <= last)
4863		{
4864		  tree field = size_int (num_initialized_elts);
4865		  if (num_initialized_elts != last)
4866		    field = build2 (RANGE_EXPR, sizetype, field,
4867				    size_int (last));
4868		  CONSTRUCTOR_APPEND_ELT (const_vec, field, e);
4869		}
4870	    }
4871	}
4872
4873      /* [class.temporary]: "There are three contexts in which temporaries are
4874	 destroyed at a different point than the end of the full-
4875	 expression. The first context is when a default constructor is called
4876	 to initialize an element of an array with no corresponding
4877	 initializer. The second context is when a copy constructor is called
4878	 to copy an element of an array while the entire array is copied. In
4879	 either case, if the constructor has one or more default arguments, the
4880	 destruction of every temporary created in a default argument is
4881	 sequenced before the construction of the next array element, if any."
4882
4883	 So, for this loop, statements are full-expressions.  */
4884      current_stmt_tree ()->stmts_are_full_exprs_p = 1;
4885      if (elt_init && !errors)
4886	elt_init = build2 (COMPOUND_EXPR, void_type_node, elt_init, decr);
4887      else
4888	elt_init = decr;
4889      finish_expr_stmt (elt_init);
4890      current_stmt_tree ()->stmts_are_full_exprs_p = 0;
4891
4892      finish_expr_stmt (cp_build_unary_op (PREINCREMENT_EXPR, base, false,
4893                                           complain));
4894      if (base2)
4895	finish_expr_stmt (cp_build_unary_op (PREINCREMENT_EXPR, base2, false,
4896                                             complain));
4897
4898      finish_for_stmt (for_stmt);
4899    }
4900
4901  /* The value of the array initialization is the array itself, RVAL
4902     is a pointer to the first element.  */
4903  finish_stmt_expr_expr (rval, stmt_expr);
4904
4905  stmt_expr = finish_init_stmts (is_global, stmt_expr, compound_stmt);
4906
4907  current_stmt_tree ()->stmts_are_full_exprs_p = destroy_temps;
4908
4909  if (errors)
4910    return error_mark_node;
4911
4912  if (try_const)
4913    {
4914      if (!saw_non_const)
4915	{
4916	  tree const_init = build_constructor (atype, const_vec);
4917	  return build2 (INIT_EXPR, atype, obase, const_init);
4918	}
4919      else if (do_static_init && !vec_safe_is_empty (const_vec))
4920	DECL_INITIAL (obase) = build_constructor (atype, const_vec);
4921      else
4922	vec_free (const_vec);
4923    }
4924
4925  /* Now make the result have the correct type.  */
4926  if (TREE_CODE (atype) == ARRAY_TYPE)
4927    {
4928      atype = build_reference_type (atype);
4929      stmt_expr = build1 (NOP_EXPR, atype, stmt_expr);
4930      stmt_expr = convert_from_reference (stmt_expr);
4931    }
4932
4933  return stmt_expr;
4934}
4935
4936/* Call the DTOR_KIND destructor for EXP.  FLAGS are as for
4937   build_delete.  */
4938
4939static tree
4940build_dtor_call (tree exp, special_function_kind dtor_kind, int flags,
4941		 tsubst_flags_t complain)
4942{
4943  tree name;
4944  switch (dtor_kind)
4945    {
4946    case sfk_complete_destructor:
4947      name = complete_dtor_identifier;
4948      break;
4949
4950    case sfk_base_destructor:
4951      name = base_dtor_identifier;
4952      break;
4953
4954    case sfk_deleting_destructor:
4955      name = deleting_dtor_identifier;
4956      break;
4957
4958    default:
4959      gcc_unreachable ();
4960    }
4961
4962  return build_special_member_call (exp, name,
4963				    /*args=*/NULL,
4964				    /*binfo=*/TREE_TYPE (exp),
4965				    flags,
4966				    complain);
4967}
4968
4969/* Generate a call to a destructor. TYPE is the type to cast ADDR to.
4970   ADDR is an expression which yields the store to be destroyed.
4971   AUTO_DELETE is the name of the destructor to call, i.e., either
4972   sfk_complete_destructor, sfk_base_destructor, or
4973   sfk_deleting_destructor.
4974
4975   FLAGS is the logical disjunction of zero or more LOOKUP_
4976   flags.  See cp-tree.h for more info.  */
4977
4978tree
4979build_delete (location_t loc, tree otype, tree addr,
4980	      special_function_kind auto_delete,
4981	      int flags, int use_global_delete, tsubst_flags_t complain)
4982{
4983  tree expr;
4984
4985  if (addr == error_mark_node)
4986    return error_mark_node;
4987
4988  tree type = TYPE_MAIN_VARIANT (otype);
4989
4990  /* Can happen when CURRENT_EXCEPTION_OBJECT gets its type
4991     set to `error_mark_node' before it gets properly cleaned up.  */
4992  if (type == error_mark_node)
4993    return error_mark_node;
4994
4995  if (TYPE_PTR_P (type))
4996    type = TYPE_MAIN_VARIANT (TREE_TYPE (type));
4997
4998  if (TREE_CODE (type) == ARRAY_TYPE)
4999    {
5000      if (TYPE_DOMAIN (type) == NULL_TREE)
5001	{
5002	  if (complain & tf_error)
5003	    error_at (loc, "unknown array size in delete");
5004	  return error_mark_node;
5005	}
5006      return build_vec_delete (loc, addr, array_type_nelts (type),
5007			       auto_delete, use_global_delete, complain);
5008    }
5009
5010  bool deleting = (auto_delete == sfk_deleting_destructor);
5011  gcc_assert (deleting == !(flags & LOOKUP_DESTRUCTOR));
5012
5013  if (TYPE_PTR_P (otype))
5014    {
5015      addr = mark_rvalue_use (addr);
5016
5017      /* We don't want to warn about delete of void*, only other
5018	  incomplete types.  Deleting other incomplete types
5019	  invokes undefined behavior, but it is not ill-formed, so
5020	  compile to something that would even do The Right Thing
5021	  (TM) should the type have a trivial dtor and no delete
5022	  operator.  */
5023      if (!VOID_TYPE_P (type))
5024	{
5025	  complete_type (type);
5026	  if (deleting
5027	      && !verify_type_context (loc, TCTX_DEALLOCATION, type,
5028				       !(complain & tf_error)))
5029	    return error_mark_node;
5030
5031	  if (!COMPLETE_TYPE_P (type))
5032	    {
5033	      if (complain & tf_warning)
5034		{
5035		  auto_diagnostic_group d;
5036		  if (warning_at (loc, OPT_Wdelete_incomplete,
5037				  "possible problem detected in invocation of "
5038				  "%<operator delete%>"))
5039		    {
5040		      cxx_incomplete_type_diagnostic (addr, type, DK_WARNING);
5041		      inform (loc,
5042			      "neither the destructor nor the class-specific "
5043			      "%<operator delete%> will be called, even if "
5044			      "they are declared when the class is defined");
5045		    }
5046		}
5047	    }
5048	  else if (deleting && warn_delnonvdtor
5049	           && MAYBE_CLASS_TYPE_P (type) && !CLASSTYPE_FINAL (type)
5050		   && TYPE_POLYMORPHIC_P (type))
5051	    {
5052	      tree dtor = CLASSTYPE_DESTRUCTOR (type);
5053	      if (!dtor || !DECL_VINDEX (dtor))
5054		{
5055		  if (CLASSTYPE_PURE_VIRTUALS (type))
5056		    warning_at (loc, OPT_Wdelete_non_virtual_dtor,
5057				"deleting object of abstract class type %qT"
5058				" which has non-virtual destructor"
5059				" will cause undefined behavior", type);
5060		  else
5061		    warning_at (loc, OPT_Wdelete_non_virtual_dtor,
5062				"deleting object of polymorphic class type %qT"
5063				" which has non-virtual destructor"
5064				" might cause undefined behavior", type);
5065		}
5066	    }
5067	}
5068
5069      /* Throw away const and volatile on target type of addr.  */
5070      addr = convert_force (build_pointer_type (type), addr, 0, complain);
5071    }
5072  else
5073    {
5074      /* Don't check PROTECT here; leave that decision to the
5075	 destructor.  If the destructor is accessible, call it,
5076	 else report error.  */
5077      addr = cp_build_addr_expr (addr, complain);
5078      if (addr == error_mark_node)
5079	return error_mark_node;
5080
5081      addr = convert_force (build_pointer_type (type), addr, 0, complain);
5082    }
5083
5084  if (deleting)
5085    /* We will use ADDR multiple times so we must save it.  */
5086    addr = save_expr (addr);
5087
5088  bool virtual_p = false;
5089  if (type_build_dtor_call (type))
5090    {
5091      if (CLASSTYPE_LAZY_DESTRUCTOR (type))
5092	lazily_declare_fn (sfk_destructor, type);
5093      virtual_p = DECL_VIRTUAL_P (CLASSTYPE_DESTRUCTOR (type));
5094    }
5095
5096  tree head = NULL_TREE;
5097  tree do_delete = NULL_TREE;
5098  bool destroying_delete = false;
5099
5100  if (!deleting)
5101    {
5102      /* Leave do_delete null.  */
5103    }
5104  /* For `::delete x', we must not use the deleting destructor
5105     since then we would not be sure to get the global `operator
5106     delete'.  */
5107  else if (use_global_delete)
5108    {
5109      head = get_target_expr (build_headof (addr));
5110      /* Delete the object.  */
5111      do_delete = build_op_delete_call (DELETE_EXPR,
5112					head,
5113					cxx_sizeof_nowarn (type),
5114					/*global_p=*/true,
5115					/*placement=*/NULL_TREE,
5116					/*alloc_fn=*/NULL_TREE,
5117					complain);
5118      /* Otherwise, treat this like a complete object destructor
5119	 call.  */
5120      auto_delete = sfk_complete_destructor;
5121    }
5122  /* If the destructor is non-virtual, there is no deleting
5123     variant.  Instead, we must explicitly call the appropriate
5124     `operator delete' here.  */
5125  else if (!virtual_p)
5126    {
5127      /* Build the call.  */
5128      do_delete = build_op_delete_call (DELETE_EXPR,
5129					addr,
5130					cxx_sizeof_nowarn (type),
5131					/*global_p=*/false,
5132					/*placement=*/NULL_TREE,
5133					/*alloc_fn=*/NULL_TREE,
5134					complain);
5135      /* Call the complete object destructor.  */
5136      auto_delete = sfk_complete_destructor;
5137      if (do_delete != error_mark_node)
5138	{
5139	  tree fn = get_callee_fndecl (do_delete);
5140	  destroying_delete = destroying_delete_p (fn);
5141	}
5142    }
5143  else if (TYPE_GETS_REG_DELETE (type))
5144    {
5145      /* Make sure we have access to the member op delete, even though
5146	 we'll actually be calling it from the destructor.  */
5147      build_op_delete_call (DELETE_EXPR, addr, cxx_sizeof_nowarn (type),
5148			    /*global_p=*/false,
5149			    /*placement=*/NULL_TREE,
5150			    /*alloc_fn=*/NULL_TREE,
5151			    complain);
5152    }
5153
5154  if (destroying_delete)
5155    /* The operator delete will call the destructor.  */
5156    expr = addr;
5157  else if (type_build_dtor_call (type))
5158    expr = build_dtor_call (cp_build_fold_indirect_ref (addr),
5159			    auto_delete, flags, complain);
5160  else
5161    expr = build_trivial_dtor_call (addr);
5162  if (expr == error_mark_node)
5163    return error_mark_node;
5164
5165  if (!deleting)
5166    {
5167      protected_set_expr_location (expr, loc);
5168      return expr;
5169    }
5170
5171  if (do_delete == error_mark_node)
5172    return error_mark_node;
5173
5174  if (do_delete && !TREE_SIDE_EFFECTS (expr))
5175    expr = do_delete;
5176  else if (do_delete)
5177    /* The delete operator must be called, regardless of whether
5178       the destructor throws.
5179
5180       [expr.delete]/7 The deallocation function is called
5181       regardless of whether the destructor for the object or some
5182       element of the array throws an exception.  */
5183    expr = build2 (TRY_FINALLY_EXPR, void_type_node, expr, do_delete);
5184
5185  /* We need to calculate this before the dtor changes the vptr.  */
5186  if (head)
5187    expr = build2 (COMPOUND_EXPR, void_type_node, head, expr);
5188
5189  /* Handle deleting a null pointer.  */
5190  warning_sentinel s (warn_address);
5191  tree ifexp = cp_build_binary_op (loc, NE_EXPR, addr,
5192				   nullptr_node, complain);
5193  ifexp = cp_fully_fold (ifexp);
5194
5195  if (ifexp == error_mark_node)
5196    return error_mark_node;
5197  /* This is a compiler generated comparison, don't emit
5198     e.g. -Wnonnull-compare warning for it.  */
5199  else if (TREE_CODE (ifexp) == NE_EXPR)
5200    suppress_warning (ifexp, OPT_Wnonnull_compare);
5201
5202  if (!integer_nonzerop (ifexp))
5203    expr = build3 (COND_EXPR, void_type_node, ifexp, expr, void_node);
5204
5205  protected_set_expr_location (expr, loc);
5206  return expr;
5207}
5208
5209/* At the beginning of a destructor, push cleanups that will call the
5210   destructors for our base classes and members.
5211
5212   Called from begin_destructor_body.  */
5213
5214void
5215push_base_cleanups (void)
5216{
5217  tree binfo, base_binfo;
5218  int i;
5219  tree member;
5220  tree expr;
5221  vec<tree, va_gc> *vbases;
5222
5223  /* Run destructors for all virtual baseclasses.  */
5224  if (!ABSTRACT_CLASS_TYPE_P (current_class_type)
5225      && CLASSTYPE_VBASECLASSES (current_class_type))
5226    {
5227      tree cond = (condition_conversion
5228		   (build2 (BIT_AND_EXPR, integer_type_node,
5229			    current_in_charge_parm,
5230			    integer_two_node)));
5231
5232      /* The CLASSTYPE_VBASECLASSES vector is in initialization
5233	 order, which is also the right order for pushing cleanups.  */
5234      for (vbases = CLASSTYPE_VBASECLASSES (current_class_type), i = 0;
5235	   vec_safe_iterate (vbases, i, &base_binfo); i++)
5236	{
5237	  if (type_build_dtor_call (BINFO_TYPE (base_binfo)))
5238	    {
5239	      expr = build_special_member_call (current_class_ref,
5240						base_dtor_identifier,
5241						NULL,
5242						base_binfo,
5243						(LOOKUP_NORMAL
5244						 | LOOKUP_NONVIRTUAL),
5245						tf_warning_or_error);
5246	      if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (BINFO_TYPE (base_binfo)))
5247		{
5248		  expr = build3 (COND_EXPR, void_type_node, cond,
5249				 expr, void_node);
5250		  finish_decl_cleanup (NULL_TREE, expr);
5251		}
5252	    }
5253	}
5254    }
5255
5256  /* Take care of the remaining baseclasses.  */
5257  for (binfo = TYPE_BINFO (current_class_type), i = 0;
5258       BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
5259    {
5260      if (BINFO_VIRTUAL_P (base_binfo)
5261	  || !type_build_dtor_call (BINFO_TYPE (base_binfo)))
5262	continue;
5263
5264      expr = build_special_member_call (current_class_ref,
5265					base_dtor_identifier,
5266					NULL, base_binfo,
5267					LOOKUP_NORMAL | LOOKUP_NONVIRTUAL,
5268                                        tf_warning_or_error);
5269      if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (BINFO_TYPE (base_binfo)))
5270	finish_decl_cleanup (NULL_TREE, expr);
5271    }
5272
5273  /* Don't automatically destroy union members.  */
5274  if (TREE_CODE (current_class_type) == UNION_TYPE)
5275    return;
5276
5277  for (member = TYPE_FIELDS (current_class_type); member;
5278       member = DECL_CHAIN (member))
5279    {
5280      tree this_type = TREE_TYPE (member);
5281      if (this_type == error_mark_node
5282	  || TREE_CODE (member) != FIELD_DECL
5283	  || DECL_ARTIFICIAL (member))
5284	continue;
5285      if (ANON_AGGR_TYPE_P (this_type))
5286	continue;
5287      if (type_build_dtor_call (this_type))
5288	{
5289	  tree this_member = (build_class_member_access_expr
5290			      (current_class_ref, member,
5291			       /*access_path=*/NULL_TREE,
5292			       /*preserve_reference=*/false,
5293			       tf_warning_or_error));
5294	  expr = build_delete (input_location, this_type, this_member,
5295			       sfk_complete_destructor,
5296			       LOOKUP_NONVIRTUAL|LOOKUP_DESTRUCTOR|LOOKUP_NORMAL,
5297			       0, tf_warning_or_error);
5298	  if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (this_type))
5299	    finish_decl_cleanup (NULL_TREE, expr);
5300	}
5301    }
5302}
5303
5304/* Build a C++ vector delete expression.
5305   MAXINDEX is the number of elements to be deleted.
5306   ELT_SIZE is the nominal size of each element in the vector.
5307   BASE is the expression that should yield the store to be deleted.
5308   This function expands (or synthesizes) these calls itself.
5309   AUTO_DELETE_VEC says whether the container (vector) should be deallocated.
5310
5311   This also calls delete for virtual baseclasses of elements of the vector.
5312
5313   Update: MAXINDEX is no longer needed.  The size can be extracted from the
5314   start of the vector for pointers, and from the type for arrays.  We still
5315   use MAXINDEX for arrays because it happens to already have one of the
5316   values we'd have to extract.  (We could use MAXINDEX with pointers to
5317   confirm the size, and trap if the numbers differ; not clear that it'd
5318   be worth bothering.)  */
5319
5320tree
5321build_vec_delete (location_t loc, tree base, tree maxindex,
5322		  special_function_kind auto_delete_vec,
5323		  int use_global_delete, tsubst_flags_t complain)
5324{
5325  tree type;
5326  tree rval;
5327  tree base_init = NULL_TREE;
5328
5329  type = TREE_TYPE (base);
5330
5331  if (TYPE_PTR_P (type))
5332    {
5333      /* Step back one from start of vector, and read dimension.  */
5334      tree cookie_addr;
5335      tree size_ptr_type = build_pointer_type (sizetype);
5336
5337      base = mark_rvalue_use (base);
5338      if (TREE_SIDE_EFFECTS (base))
5339	{
5340	  base_init = get_target_expr (base);
5341	  base = TARGET_EXPR_SLOT (base_init);
5342	}
5343      type = strip_array_types (TREE_TYPE (type));
5344      cookie_addr = fold_build1_loc (loc, NEGATE_EXPR,
5345				 sizetype, TYPE_SIZE_UNIT (sizetype));
5346      cookie_addr = fold_build_pointer_plus (fold_convert (size_ptr_type, base),
5347					     cookie_addr);
5348      maxindex = cp_build_fold_indirect_ref (cookie_addr);
5349    }
5350  else if (TREE_CODE (type) == ARRAY_TYPE)
5351    {
5352      /* Get the total number of things in the array, maxindex is a
5353	 bad name.  */
5354      maxindex = array_type_nelts_total (type);
5355      type = strip_array_types (type);
5356      base = decay_conversion (base, complain);
5357      if (base == error_mark_node)
5358	return error_mark_node;
5359      if (TREE_SIDE_EFFECTS (base))
5360	{
5361	  base_init = get_target_expr (base);
5362	  base = TARGET_EXPR_SLOT (base_init);
5363	}
5364    }
5365  else
5366    {
5367      if (base != error_mark_node && !(complain & tf_error))
5368	error_at (loc,
5369		  "type to vector delete is neither pointer or array type");
5370      return error_mark_node;
5371    }
5372
5373  rval = build_vec_delete_1 (loc, base, maxindex, type, auto_delete_vec,
5374			     use_global_delete, complain);
5375  if (base_init && rval != error_mark_node)
5376    rval = build2 (COMPOUND_EXPR, TREE_TYPE (rval), base_init, rval);
5377
5378  protected_set_expr_location (rval, loc);
5379  return rval;
5380}
5381
5382#include "gt-cp-init.h"
5383