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