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