2018-07-12 Richard Biener <rguenther@suse.de>
[official-gcc.git] / gcc / cp / init.c
blob94f8fdd7bd98891faa3bb9d0eb6eca8ea4825128
1 /* Handle initialization things in C++.
2 Copyright (C) 1987-2018 Free Software Foundation, Inc.
3 Contributed by Michael Tiemann (tiemann@cygnus.com)
5 This file is part of GCC.
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.
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.
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/>. */
21 /* High-level class interface. */
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"
37 static bool begin_init_stmts (tree *, tree *);
38 static tree finish_init_stmts (bool, tree, tree);
39 static void construct_virtual_base (tree, tree);
40 static void expand_aggr_init_1 (tree, tree, tree, tree, int, tsubst_flags_t);
41 static void expand_default_init (tree, tree, tree, tree, int, tsubst_flags_t);
42 static void perform_member_init (tree, tree);
43 static int member_init_ok_or_else (tree, tree, tree);
44 static void expand_virtual_init (tree, tree);
45 static tree sort_mem_initializers (tree, tree);
46 static tree initializing_context (tree);
47 static void expand_cleanup_for_base (tree, tree);
48 static tree dfs_initialize_vtbl_ptrs (tree, void *);
49 static tree build_field_list (tree, tree, int *);
50 static int diagnose_uninitialized_cst_or_ref_member_1 (tree, tree, bool, bool);
52 static GTY(()) tree fn;
54 /* We are about to generate some complex initialization code.
55 Conceptually, it is all a single expression. However, we may want
56 to include conditionals, loops, and other such statement-level
57 constructs. Therefore, we build the initialization code inside a
58 statement-expression. This function starts such an expression.
59 STMT_EXPR_P and COMPOUND_STMT_P are filled in by this function;
60 pass them back to finish_init_stmts when the expression is
61 complete. */
63 static bool
64 begin_init_stmts (tree *stmt_expr_p, tree *compound_stmt_p)
66 bool is_global = !building_stmt_list_p ();
68 *stmt_expr_p = begin_stmt_expr ();
69 *compound_stmt_p = begin_compound_stmt (BCS_NO_SCOPE);
71 return is_global;
74 /* Finish out the statement-expression begun by the previous call to
75 begin_init_stmts. Returns the statement-expression itself. */
77 static tree
78 finish_init_stmts (bool is_global, tree stmt_expr, tree compound_stmt)
80 finish_compound_stmt (compound_stmt);
82 stmt_expr = finish_stmt_expr (stmt_expr, true);
84 gcc_assert (!building_stmt_list_p () == is_global);
86 return stmt_expr;
89 /* Constructors */
91 /* Called from initialize_vtbl_ptrs via dfs_walk. BINFO is the base
92 which we want to initialize the vtable pointer for, DATA is
93 TREE_LIST whose TREE_VALUE is the this ptr expression. */
95 static tree
96 dfs_initialize_vtbl_ptrs (tree binfo, void *data)
98 if (!TYPE_CONTAINS_VPTR_P (BINFO_TYPE (binfo)))
99 return dfs_skip_bases;
101 if (!BINFO_PRIMARY_P (binfo) || BINFO_VIRTUAL_P (binfo))
103 tree base_ptr = TREE_VALUE ((tree) data);
105 base_ptr = build_base_path (PLUS_EXPR, base_ptr, binfo, /*nonnull=*/1,
106 tf_warning_or_error);
108 expand_virtual_init (binfo, base_ptr);
111 return NULL_TREE;
114 /* Initialize all the vtable pointers in the object pointed to by
115 ADDR. */
117 void
118 initialize_vtbl_ptrs (tree addr)
120 tree list;
121 tree type;
123 type = TREE_TYPE (TREE_TYPE (addr));
124 list = build_tree_list (type, addr);
126 /* Walk through the hierarchy, initializing the vptr in each base
127 class. We do these in pre-order because we can't find the virtual
128 bases for a class until we've initialized the vtbl for that
129 class. */
130 dfs_walk_once (TYPE_BINFO (type), dfs_initialize_vtbl_ptrs, NULL, list);
133 /* Return an expression for the zero-initialization of an object with
134 type T. This expression will either be a constant (in the case
135 that T is a scalar), or a CONSTRUCTOR (in the case that T is an
136 aggregate), or NULL (in the case that T does not require
137 initialization). In either case, the value can be used as
138 DECL_INITIAL for a decl of the indicated TYPE; it is a valid static
139 initializer. If NELTS is non-NULL, and TYPE is an ARRAY_TYPE, NELTS
140 is the number of elements in the array. If STATIC_STORAGE_P is
141 TRUE, initializers are only generated for entities for which
142 zero-initialization does not simply mean filling the storage with
143 zero bytes. FIELD_SIZE, if non-NULL, is the bit size of the field,
144 subfields with bit positions at or above that bit size shouldn't
145 be added. Note that this only works when the result is assigned
146 to a base COMPONENT_REF; if we only have a pointer to the base subobject,
147 expand_assignment will end up clearing the full size of TYPE. */
149 static tree
150 build_zero_init_1 (tree type, tree nelts, bool static_storage_p,
151 tree field_size)
153 tree init = NULL_TREE;
155 /* [dcl.init]
157 To zero-initialize an object of type T means:
159 -- if T is a scalar type, the storage is set to the value of zero
160 converted to T.
162 -- if T is a non-union class type, the storage for each nonstatic
163 data member and each base-class subobject is zero-initialized.
165 -- if T is a union type, the storage for its first data member is
166 zero-initialized.
168 -- if T is an array type, the storage for each element is
169 zero-initialized.
171 -- if T is a reference type, no initialization is performed. */
173 gcc_assert (nelts == NULL_TREE || TREE_CODE (nelts) == INTEGER_CST);
175 if (type == error_mark_node)
177 else if (static_storage_p && zero_init_p (type))
178 /* In order to save space, we do not explicitly build initializers
179 for items that do not need them. GCC's semantics are that
180 items with static storage duration that are not otherwise
181 initialized are initialized to zero. */
183 else if (TYPE_PTR_OR_PTRMEM_P (type))
184 init = fold (convert (type, nullptr_node));
185 else if (NULLPTR_TYPE_P (type))
186 init = build_int_cst (type, 0);
187 else if (SCALAR_TYPE_P (type))
188 init = fold (convert (type, integer_zero_node));
189 else if (RECORD_OR_UNION_CODE_P (TREE_CODE (type)))
191 tree field;
192 vec<constructor_elt, va_gc> *v = NULL;
194 /* Iterate over the fields, building initializations. */
195 for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
197 if (TREE_CODE (field) != FIELD_DECL)
198 continue;
200 if (TREE_TYPE (field) == error_mark_node)
201 continue;
203 /* Don't add virtual bases for base classes if they are beyond
204 the size of the current field, that means it is present
205 somewhere else in the object. */
206 if (field_size)
208 tree bitpos = bit_position (field);
209 if (TREE_CODE (bitpos) == INTEGER_CST
210 && !tree_int_cst_lt (bitpos, field_size))
211 continue;
214 /* Note that for class types there will be FIELD_DECLs
215 corresponding to base classes as well. Thus, iterating
216 over TYPE_FIELDs will result in correct initialization of
217 all of the subobjects. */
218 if (!static_storage_p || !zero_init_p (TREE_TYPE (field)))
220 tree new_field_size
221 = (DECL_FIELD_IS_BASE (field)
222 && DECL_SIZE (field)
223 && TREE_CODE (DECL_SIZE (field)) == INTEGER_CST)
224 ? DECL_SIZE (field) : NULL_TREE;
225 tree value = build_zero_init_1 (TREE_TYPE (field),
226 /*nelts=*/NULL_TREE,
227 static_storage_p,
228 new_field_size);
229 if (value)
230 CONSTRUCTOR_APPEND_ELT(v, field, value);
233 /* For unions, only the first field is initialized. */
234 if (TREE_CODE (type) == UNION_TYPE)
235 break;
238 /* Build a constructor to contain the initializations. */
239 init = build_constructor (type, v);
241 else if (TREE_CODE (type) == ARRAY_TYPE)
243 tree max_index;
244 vec<constructor_elt, va_gc> *v = NULL;
246 /* Iterate over the array elements, building initializations. */
247 if (nelts)
248 max_index = fold_build2_loc (input_location,
249 MINUS_EXPR, TREE_TYPE (nelts),
250 nelts, integer_one_node);
251 else
252 max_index = array_type_nelts (type);
254 /* If we have an error_mark here, we should just return error mark
255 as we don't know the size of the array yet. */
256 if (max_index == error_mark_node)
257 return error_mark_node;
258 gcc_assert (TREE_CODE (max_index) == INTEGER_CST);
260 /* A zero-sized array, which is accepted as an extension, will
261 have an upper bound of -1. */
262 if (!tree_int_cst_equal (max_index, integer_minus_one_node))
264 constructor_elt ce;
266 /* If this is a one element array, we just use a regular init. */
267 if (tree_int_cst_equal (size_zero_node, max_index))
268 ce.index = size_zero_node;
269 else
270 ce.index = build2 (RANGE_EXPR, sizetype, size_zero_node,
271 max_index);
273 ce.value = build_zero_init_1 (TREE_TYPE (type),
274 /*nelts=*/NULL_TREE,
275 static_storage_p, NULL_TREE);
276 if (ce.value)
278 vec_alloc (v, 1);
279 v->quick_push (ce);
283 /* Build a constructor to contain the initializations. */
284 init = build_constructor (type, v);
286 else if (VECTOR_TYPE_P (type))
287 init = build_zero_cst (type);
288 else
290 gcc_assert (TYPE_REF_P (type));
291 init = build_zero_cst (type);
294 /* In all cases, the initializer is a constant. */
295 if (init)
296 TREE_CONSTANT (init) = 1;
298 return init;
301 /* Return an expression for the zero-initialization of an object with
302 type T. This expression will either be a constant (in the case
303 that T is a scalar), or a CONSTRUCTOR (in the case that T is an
304 aggregate), or NULL (in the case that T does not require
305 initialization). In either case, the value can be used as
306 DECL_INITIAL for a decl of the indicated TYPE; it is a valid static
307 initializer. If NELTS is non-NULL, and TYPE is an ARRAY_TYPE, NELTS
308 is the number of elements in the array. If STATIC_STORAGE_P is
309 TRUE, initializers are only generated for entities for which
310 zero-initialization does not simply mean filling the storage with
311 zero bytes. */
313 tree
314 build_zero_init (tree type, tree nelts, bool static_storage_p)
316 return build_zero_init_1 (type, nelts, static_storage_p, NULL_TREE);
319 /* Return a suitable initializer for value-initializing an object of type
320 TYPE, as described in [dcl.init]. */
322 tree
323 build_value_init (tree type, tsubst_flags_t complain)
325 /* [dcl.init]
327 To value-initialize an object of type T means:
329 - if T is a class type (clause 9) with either no default constructor
330 (12.1) or a default constructor that is user-provided or deleted,
331 then the object is default-initialized;
333 - if T is a (possibly cv-qualified) class type without a user-provided
334 or deleted default constructor, then the object is zero-initialized
335 and the semantic constraints for default-initialization are checked,
336 and if T has a non-trivial default constructor, the object is
337 default-initialized;
339 - if T is an array type, then each element is value-initialized;
341 - otherwise, the object is zero-initialized.
343 A program that calls for default-initialization or
344 value-initialization of an entity of reference type is ill-formed. */
346 /* The AGGR_INIT_EXPR tweaking below breaks in templates. */
347 gcc_assert (!processing_template_decl
348 || (SCALAR_TYPE_P (type) || TREE_CODE (type) == ARRAY_TYPE));
350 if (CLASS_TYPE_P (type)
351 && type_build_ctor_call (type))
353 tree ctor =
354 build_special_member_call (NULL_TREE, complete_ctor_identifier,
355 NULL, type, LOOKUP_NORMAL,
356 complain);
357 if (ctor == error_mark_node)
358 return ctor;
359 tree fn = NULL_TREE;
360 if (TREE_CODE (ctor) == CALL_EXPR)
361 fn = get_callee_fndecl (ctor);
362 ctor = build_aggr_init_expr (type, ctor);
363 if (fn && user_provided_p (fn))
364 return ctor;
365 else if (TYPE_HAS_COMPLEX_DFLT (type))
367 /* This is a class that needs constructing, but doesn't have
368 a user-provided constructor. So we need to zero-initialize
369 the object and then call the implicitly defined ctor.
370 This will be handled in simplify_aggr_init_expr. */
371 AGGR_INIT_ZERO_FIRST (ctor) = 1;
372 return ctor;
376 /* Discard any access checking during subobject initialization;
377 the checks are implied by the call to the ctor which we have
378 verified is OK (cpp0x/defaulted46.C). */
379 push_deferring_access_checks (dk_deferred);
380 tree r = build_value_init_noctor (type, complain);
381 pop_deferring_access_checks ();
382 return r;
385 /* Like build_value_init, but don't call the constructor for TYPE. Used
386 for base initializers. */
388 tree
389 build_value_init_noctor (tree type, tsubst_flags_t complain)
391 if (!COMPLETE_TYPE_P (type))
393 if (complain & tf_error)
394 error ("value-initialization of incomplete type %qT", type);
395 return error_mark_node;
397 /* FIXME the class and array cases should just use digest_init once it is
398 SFINAE-enabled. */
399 if (CLASS_TYPE_P (type))
401 gcc_assert (!TYPE_HAS_COMPLEX_DFLT (type)
402 || errorcount != 0);
404 if (TREE_CODE (type) != UNION_TYPE)
406 tree field;
407 vec<constructor_elt, va_gc> *v = NULL;
409 /* Iterate over the fields, building initializations. */
410 for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
412 tree ftype, value;
414 if (TREE_CODE (field) != FIELD_DECL)
415 continue;
417 ftype = TREE_TYPE (field);
419 if (ftype == error_mark_node)
420 continue;
422 /* We could skip vfields and fields of types with
423 user-defined constructors, but I think that won't improve
424 performance at all; it should be simpler in general just
425 to zero out the entire object than try to only zero the
426 bits that actually need it. */
428 /* Note that for class types there will be FIELD_DECLs
429 corresponding to base classes as well. Thus, iterating
430 over TYPE_FIELDs will result in correct initialization of
431 all of the subobjects. */
432 value = build_value_init (ftype, complain);
433 value = maybe_constant_init (value);
435 if (value == error_mark_node)
436 return error_mark_node;
438 CONSTRUCTOR_APPEND_ELT(v, field, value);
440 /* We shouldn't have gotten here for anything that would need
441 non-trivial initialization, and gimplify_init_ctor_preeval
442 would need to be fixed to allow it. */
443 gcc_assert (TREE_CODE (value) != TARGET_EXPR
444 && TREE_CODE (value) != AGGR_INIT_EXPR);
447 /* Build a constructor to contain the zero- initializations. */
448 return build_constructor (type, v);
451 else if (TREE_CODE (type) == ARRAY_TYPE)
453 vec<constructor_elt, va_gc> *v = NULL;
455 /* Iterate over the array elements, building initializations. */
456 tree max_index = array_type_nelts (type);
458 /* If we have an error_mark here, we should just return error mark
459 as we don't know the size of the array yet. */
460 if (max_index == error_mark_node)
462 if (complain & tf_error)
463 error ("cannot value-initialize array of unknown bound %qT",
464 type);
465 return error_mark_node;
467 gcc_assert (TREE_CODE (max_index) == INTEGER_CST);
469 /* A zero-sized array, which is accepted as an extension, will
470 have an upper bound of -1. */
471 if (!tree_int_cst_equal (max_index, integer_minus_one_node))
473 constructor_elt ce;
475 /* If this is a one element array, we just use a regular init. */
476 if (tree_int_cst_equal (size_zero_node, max_index))
477 ce.index = size_zero_node;
478 else
479 ce.index = build2 (RANGE_EXPR, sizetype, size_zero_node, max_index);
481 ce.value = build_value_init (TREE_TYPE (type), complain);
482 ce.value = maybe_constant_init (ce.value);
483 if (ce.value == error_mark_node)
484 return error_mark_node;
486 vec_alloc (v, 1);
487 v->quick_push (ce);
489 /* We shouldn't have gotten here for anything that would need
490 non-trivial initialization, and gimplify_init_ctor_preeval
491 would need to be fixed to allow it. */
492 gcc_assert (TREE_CODE (ce.value) != TARGET_EXPR
493 && TREE_CODE (ce.value) != AGGR_INIT_EXPR);
496 /* Build a constructor to contain the initializations. */
497 return build_constructor (type, v);
499 else if (TREE_CODE (type) == FUNCTION_TYPE)
501 if (complain & tf_error)
502 error ("value-initialization of function type %qT", type);
503 return error_mark_node;
505 else if (TYPE_REF_P (type))
507 if (complain & tf_error)
508 error ("value-initialization of reference type %qT", type);
509 return error_mark_node;
512 return build_zero_init (type, NULL_TREE, /*static_storage_p=*/false);
515 /* Initialize current class with INIT, a TREE_LIST of
516 arguments for a target constructor. If TREE_LIST is void_type_node,
517 an empty initializer list was given. */
519 static void
520 perform_target_ctor (tree init)
522 tree decl = current_class_ref;
523 tree type = current_class_type;
525 finish_expr_stmt (build_aggr_init (decl, init,
526 LOOKUP_NORMAL|LOOKUP_DELEGATING_CONS,
527 tf_warning_or_error));
528 if (type_build_dtor_call (type))
530 tree expr = build_delete (type, decl, sfk_complete_destructor,
531 LOOKUP_NORMAL
532 |LOOKUP_NONVIRTUAL
533 |LOOKUP_DESTRUCTOR,
534 0, tf_warning_or_error);
535 if (expr != error_mark_node
536 && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
537 finish_eh_cleanup (expr);
541 /* Return the non-static data initializer for FIELD_DECL MEMBER. */
543 static GTY((cache)) tree_cache_map *nsdmi_inst;
545 tree
546 get_nsdmi (tree member, bool in_ctor, tsubst_flags_t complain)
548 tree init;
549 tree save_ccp = current_class_ptr;
550 tree save_ccr = current_class_ref;
552 if (DECL_LANG_SPECIFIC (member) && DECL_TEMPLATE_INFO (member))
554 init = DECL_INITIAL (DECL_TI_TEMPLATE (member));
555 location_t expr_loc
556 = cp_expr_loc_or_loc (init, DECL_SOURCE_LOCATION (member));
557 tree *slot;
558 if (TREE_CODE (init) == DEFAULT_ARG)
559 /* Unparsed. */;
560 else if (nsdmi_inst && (slot = nsdmi_inst->get (member)))
561 init = *slot;
562 /* Check recursive instantiation. */
563 else if (DECL_INSTANTIATING_NSDMI_P (member))
565 if (complain & tf_error)
566 error_at (expr_loc, "recursive instantiation of default member "
567 "initializer for %qD", member);
568 init = error_mark_node;
570 else
572 int un = cp_unevaluated_operand;
573 cp_unevaluated_operand = 0;
575 location_t sloc = input_location;
576 input_location = expr_loc;
578 DECL_INSTANTIATING_NSDMI_P (member) = 1;
580 bool pushed = false;
581 if (!currently_open_class (DECL_CONTEXT (member)))
583 push_to_top_level ();
584 push_nested_class (DECL_CONTEXT (member));
585 pushed = true;
588 gcc_checking_assert (!processing_template_decl);
590 inject_this_parameter (DECL_CONTEXT (member), TYPE_UNQUALIFIED);
592 start_lambda_scope (member);
594 /* Do deferred instantiation of the NSDMI. */
595 init = (tsubst_copy_and_build
596 (init, DECL_TI_ARGS (member),
597 complain, member, /*function_p=*/false,
598 /*integral_constant_expression_p=*/false));
599 init = digest_nsdmi_init (member, init, complain);
601 finish_lambda_scope ();
603 DECL_INSTANTIATING_NSDMI_P (member) = 0;
605 if (init != error_mark_node)
607 if (!nsdmi_inst)
608 nsdmi_inst = tree_cache_map::create_ggc (37);
609 nsdmi_inst->put (member, init);
612 if (pushed)
614 pop_nested_class ();
615 pop_from_top_level ();
618 input_location = sloc;
619 cp_unevaluated_operand = un;
622 else
623 init = DECL_INITIAL (member);
625 if (init && TREE_CODE (init) == DEFAULT_ARG)
627 if (complain & tf_error)
629 error ("default member initializer for %qD required before the end "
630 "of its enclosing class", member);
631 inform (location_of (init), "defined here");
632 DECL_INITIAL (member) = error_mark_node;
634 init = error_mark_node;
637 if (in_ctor)
639 current_class_ptr = save_ccp;
640 current_class_ref = save_ccr;
642 else
644 /* Use a PLACEHOLDER_EXPR when we don't have a 'this' parameter to
645 refer to; constexpr evaluation knows what to do with it. */
646 current_class_ref = build0 (PLACEHOLDER_EXPR, DECL_CONTEXT (member));
647 current_class_ptr = build_address (current_class_ref);
650 /* Strip redundant TARGET_EXPR so we don't need to remap it, and
651 so the aggregate init code below will see a CONSTRUCTOR. */
652 bool simple_target = (init && SIMPLE_TARGET_EXPR_P (init));
653 if (simple_target)
654 init = TARGET_EXPR_INITIAL (init);
655 init = break_out_target_exprs (init, /*loc*/true);
656 if (simple_target && TREE_CODE (init) != CONSTRUCTOR)
657 /* Now put it back so C++17 copy elision works. */
658 init = get_target_expr (init);
660 current_class_ptr = save_ccp;
661 current_class_ref = save_ccr;
662 return init;
665 /* Diagnose the flexible array MEMBER if its INITializer is non-null
666 and return true if so. Otherwise return false. */
668 bool
669 maybe_reject_flexarray_init (tree member, tree init)
671 tree type = TREE_TYPE (member);
673 if (!init
674 || TREE_CODE (type) != ARRAY_TYPE
675 || TYPE_DOMAIN (type))
676 return false;
678 /* Point at the flexible array member declaration if it's initialized
679 in-class, and at the ctor if it's initialized in a ctor member
680 initializer list. */
681 location_t loc;
682 if (DECL_INITIAL (member) == init
683 || !current_function_decl
684 || DECL_DEFAULTED_FN (current_function_decl))
685 loc = DECL_SOURCE_LOCATION (member);
686 else
687 loc = DECL_SOURCE_LOCATION (current_function_decl);
689 error_at (loc, "initializer for flexible array member %q#D", member);
690 return true;
693 /* If INIT's value can come from a call to std::initializer_list<T>::begin,
694 return that function. Otherwise, NULL_TREE. */
696 static tree
697 find_list_begin (tree init)
699 STRIP_NOPS (init);
700 while (TREE_CODE (init) == COMPOUND_EXPR)
701 init = TREE_OPERAND (init, 1);
702 STRIP_NOPS (init);
703 if (TREE_CODE (init) == COND_EXPR)
705 tree left = TREE_OPERAND (init, 1);
706 if (!left)
707 left = TREE_OPERAND (init, 0);
708 left = find_list_begin (left);
709 if (left)
710 return left;
711 return find_list_begin (TREE_OPERAND (init, 2));
713 if (TREE_CODE (init) == CALL_EXPR)
714 if (tree fn = get_callee_fndecl (init))
715 if (id_equal (DECL_NAME (fn), "begin")
716 && is_std_init_list (DECL_CONTEXT (fn)))
717 return fn;
718 return NULL_TREE;
721 /* If INIT initializing MEMBER is copying the address of the underlying array
722 of an initializer_list, warn. */
724 static void
725 maybe_warn_list_ctor (tree member, tree init)
727 tree memtype = TREE_TYPE (member);
728 if (!init || !TYPE_PTR_P (memtype)
729 || !is_list_ctor (current_function_decl))
730 return;
732 tree parms = FUNCTION_FIRST_USER_PARMTYPE (current_function_decl);
733 tree initlist = non_reference (TREE_VALUE (parms));
734 tree targs = CLASSTYPE_TI_ARGS (initlist);
735 tree elttype = TREE_VEC_ELT (targs, 0);
737 if (!same_type_ignoring_top_level_qualifiers_p
738 (TREE_TYPE (memtype), elttype))
739 return;
741 tree begin = find_list_begin (init);
742 if (!begin)
743 return;
745 location_t loc = cp_expr_loc_or_loc (init, input_location);
746 warning_at (loc, OPT_Winit_list_lifetime,
747 "initializing %qD from %qE does not extend the lifetime "
748 "of the underlying array", member, begin);
751 /* Initialize MEMBER, a FIELD_DECL, with INIT, a TREE_LIST of
752 arguments. If TREE_LIST is void_type_node, an empty initializer
753 list was given; if NULL_TREE no initializer was given. */
755 static void
756 perform_member_init (tree member, tree init)
758 tree decl;
759 tree type = TREE_TYPE (member);
761 /* Use the non-static data member initializer if there was no
762 mem-initializer for this field. */
763 if (init == NULL_TREE)
764 init = get_nsdmi (member, /*ctor*/true, tf_warning_or_error);
766 if (init == error_mark_node)
767 return;
769 /* Effective C++ rule 12 requires that all data members be
770 initialized. */
771 if (warn_ecpp && init == NULL_TREE && TREE_CODE (type) != ARRAY_TYPE)
772 warning_at (DECL_SOURCE_LOCATION (current_function_decl), OPT_Weffc__,
773 "%qD should be initialized in the member initialization list",
774 member);
776 /* Get an lvalue for the data member. */
777 decl = build_class_member_access_expr (current_class_ref, member,
778 /*access_path=*/NULL_TREE,
779 /*preserve_reference=*/true,
780 tf_warning_or_error);
781 if (decl == error_mark_node)
782 return;
784 if (warn_init_self && init && TREE_CODE (init) == TREE_LIST
785 && TREE_CHAIN (init) == NULL_TREE)
787 tree val = TREE_VALUE (init);
788 /* Handle references. */
789 if (REFERENCE_REF_P (val))
790 val = TREE_OPERAND (val, 0);
791 if (TREE_CODE (val) == COMPONENT_REF && TREE_OPERAND (val, 1) == member
792 && TREE_OPERAND (val, 0) == current_class_ref)
793 warning_at (DECL_SOURCE_LOCATION (current_function_decl),
794 OPT_Winit_self, "%qD is initialized with itself",
795 member);
798 if (init == void_type_node)
800 /* mem() means value-initialization. */
801 if (TREE_CODE (type) == ARRAY_TYPE)
803 init = build_vec_init_expr (type, init, tf_warning_or_error);
804 init = build2 (INIT_EXPR, type, decl, init);
805 finish_expr_stmt (init);
807 else
809 tree value = build_value_init (type, tf_warning_or_error);
810 if (value == error_mark_node)
811 return;
812 init = build2 (INIT_EXPR, type, decl, value);
813 finish_expr_stmt (init);
816 /* Deal with this here, as we will get confused if we try to call the
817 assignment op for an anonymous union. This can happen in a
818 synthesized copy constructor. */
819 else if (ANON_AGGR_TYPE_P (type))
821 if (init)
823 init = build2 (INIT_EXPR, type, decl, TREE_VALUE (init));
824 finish_expr_stmt (init);
827 else if (init
828 && (TYPE_REF_P (type)
829 /* Pre-digested NSDMI. */
830 || (((TREE_CODE (init) == CONSTRUCTOR
831 && TREE_TYPE (init) == type)
832 /* { } mem-initializer. */
833 || (TREE_CODE (init) == TREE_LIST
834 && DIRECT_LIST_INIT_P (TREE_VALUE (init))))
835 && (CP_AGGREGATE_TYPE_P (type)
836 || is_std_init_list (type)))))
838 /* With references and list-initialization, we need to deal with
839 extending temporary lifetimes. 12.2p5: "A temporary bound to a
840 reference member in a constructor’s ctor-initializer (12.6.2)
841 persists until the constructor exits." */
842 unsigned i; tree t;
843 vec<tree, va_gc> *cleanups = make_tree_vector ();
844 if (TREE_CODE (init) == TREE_LIST)
845 init = build_x_compound_expr_from_list (init, ELK_MEM_INIT,
846 tf_warning_or_error);
847 if (TREE_TYPE (init) != type)
849 if (BRACE_ENCLOSED_INITIALIZER_P (init)
850 && CP_AGGREGATE_TYPE_P (type))
851 init = reshape_init (type, init, tf_warning_or_error);
852 init = digest_init (type, init, tf_warning_or_error);
854 if (init == error_mark_node)
855 return;
856 /* A FIELD_DECL doesn't really have a suitable lifetime, but
857 make_temporary_var_for_ref_to_temp will treat it as automatic and
858 set_up_extended_ref_temp wants to use the decl in a warning. */
859 init = extend_ref_init_temps (member, init, &cleanups);
860 if (TREE_CODE (type) == ARRAY_TYPE
861 && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (type)))
862 init = build_vec_init_expr (type, init, tf_warning_or_error);
863 init = build2 (INIT_EXPR, type, decl, init);
864 finish_expr_stmt (init);
865 FOR_EACH_VEC_ELT (*cleanups, i, t)
866 push_cleanup (decl, t, false);
867 release_tree_vector (cleanups);
869 else if (type_build_ctor_call (type)
870 || (init && CLASS_TYPE_P (strip_array_types (type))))
872 if (TREE_CODE (type) == ARRAY_TYPE)
874 if (init)
876 /* Check to make sure the member initializer is valid and
877 something like a CONSTRUCTOR in: T a[] = { 1, 2 } and
878 if it isn't, return early to avoid triggering another
879 error below. */
880 if (maybe_reject_flexarray_init (member, init))
881 return;
883 if (TREE_CODE (init) != TREE_LIST || TREE_CHAIN (init))
884 init = error_mark_node;
885 else
886 init = TREE_VALUE (init);
888 if (BRACE_ENCLOSED_INITIALIZER_P (init))
889 init = digest_init (type, init, tf_warning_or_error);
891 if (init == NULL_TREE
892 || same_type_ignoring_top_level_qualifiers_p (type,
893 TREE_TYPE (init)))
895 if (TYPE_DOMAIN (type) && TYPE_MAX_VALUE (TYPE_DOMAIN (type)))
897 /* Initialize the array only if it's not a flexible
898 array member (i.e., if it has an upper bound). */
899 init = build_vec_init_expr (type, init, tf_warning_or_error);
900 init = build2 (INIT_EXPR, type, decl, init);
901 finish_expr_stmt (init);
904 else
905 error ("invalid initializer for array member %q#D", member);
907 else
909 int flags = LOOKUP_NORMAL;
910 if (DECL_DEFAULTED_FN (current_function_decl))
911 flags |= LOOKUP_DEFAULTED;
912 if (CP_TYPE_CONST_P (type)
913 && init == NULL_TREE
914 && default_init_uninitialized_part (type))
916 /* TYPE_NEEDS_CONSTRUCTING can be set just because we have a
917 vtable; still give this diagnostic. */
918 if (permerror (DECL_SOURCE_LOCATION (current_function_decl),
919 "uninitialized const member in %q#T", type))
920 inform (DECL_SOURCE_LOCATION (member),
921 "%q#D should be initialized", member );
923 finish_expr_stmt (build_aggr_init (decl, init, flags,
924 tf_warning_or_error));
927 else
929 if (init == NULL_TREE)
931 tree core_type;
932 /* member traversal: note it leaves init NULL */
933 if (TYPE_REF_P (type))
935 if (permerror (DECL_SOURCE_LOCATION (current_function_decl),
936 "uninitialized reference member in %q#T", type))
937 inform (DECL_SOURCE_LOCATION (member),
938 "%q#D should be initialized", member);
940 else if (CP_TYPE_CONST_P (type))
942 if (permerror (DECL_SOURCE_LOCATION (current_function_decl),
943 "uninitialized const member in %q#T", type))
944 inform (DECL_SOURCE_LOCATION (member),
945 "%q#D should be initialized", member );
948 core_type = strip_array_types (type);
950 if (CLASS_TYPE_P (core_type)
951 && (CLASSTYPE_READONLY_FIELDS_NEED_INIT (core_type)
952 || CLASSTYPE_REF_FIELDS_NEED_INIT (core_type)))
953 diagnose_uninitialized_cst_or_ref_member (core_type,
954 /*using_new=*/false,
955 /*complain=*/true);
957 else if (TREE_CODE (init) == TREE_LIST)
958 /* There was an explicit member initialization. Do some work
959 in that case. */
960 init = build_x_compound_expr_from_list (init, ELK_MEM_INIT,
961 tf_warning_or_error);
963 maybe_warn_list_ctor (member, init);
965 /* Reject a member initializer for a flexible array member. */
966 if (init && !maybe_reject_flexarray_init (member, init))
967 finish_expr_stmt (cp_build_modify_expr (input_location, decl,
968 INIT_EXPR, init,
969 tf_warning_or_error));
972 if (type_build_dtor_call (type))
974 tree expr;
976 expr = build_class_member_access_expr (current_class_ref, member,
977 /*access_path=*/NULL_TREE,
978 /*preserve_reference=*/false,
979 tf_warning_or_error);
980 expr = build_delete (type, expr, sfk_complete_destructor,
981 LOOKUP_NONVIRTUAL|LOOKUP_DESTRUCTOR, 0,
982 tf_warning_or_error);
984 if (expr != error_mark_node
985 && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
986 finish_eh_cleanup (expr);
990 /* Returns a TREE_LIST containing (as the TREE_PURPOSE of each node) all
991 the FIELD_DECLs on the TYPE_FIELDS list for T, in reverse order. */
993 static tree
994 build_field_list (tree t, tree list, int *uses_unions_or_anon_p)
996 tree fields;
998 /* Note whether or not T is a union. */
999 if (TREE_CODE (t) == UNION_TYPE)
1000 *uses_unions_or_anon_p = 1;
1002 for (fields = TYPE_FIELDS (t); fields; fields = DECL_CHAIN (fields))
1004 tree fieldtype;
1006 /* Skip CONST_DECLs for enumeration constants and so forth. */
1007 if (TREE_CODE (fields) != FIELD_DECL || DECL_ARTIFICIAL (fields))
1008 continue;
1010 fieldtype = TREE_TYPE (fields);
1012 /* For an anonymous struct or union, we must recursively
1013 consider the fields of the anonymous type. They can be
1014 directly initialized from the constructor. */
1015 if (ANON_AGGR_TYPE_P (fieldtype))
1017 /* Add this field itself. Synthesized copy constructors
1018 initialize the entire aggregate. */
1019 list = tree_cons (fields, NULL_TREE, list);
1020 /* And now add the fields in the anonymous aggregate. */
1021 list = build_field_list (fieldtype, list, uses_unions_or_anon_p);
1022 *uses_unions_or_anon_p = 1;
1024 /* Add this field. */
1025 else if (DECL_NAME (fields))
1026 list = tree_cons (fields, NULL_TREE, list);
1029 return list;
1032 /* Return the innermost aggregate scope for FIELD, whether that is
1033 the enclosing class or an anonymous aggregate within it. */
1035 static tree
1036 innermost_aggr_scope (tree field)
1038 if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
1039 return TREE_TYPE (field);
1040 else
1041 return DECL_CONTEXT (field);
1044 /* The MEM_INITS are a TREE_LIST. The TREE_PURPOSE of each list gives
1045 a FIELD_DECL or BINFO in T that needs initialization. The
1046 TREE_VALUE gives the initializer, or list of initializer arguments.
1048 Return a TREE_LIST containing all of the initializations required
1049 for T, in the order in which they should be performed. The output
1050 list has the same format as the input. */
1052 static tree
1053 sort_mem_initializers (tree t, tree mem_inits)
1055 tree init;
1056 tree base, binfo, base_binfo;
1057 tree sorted_inits;
1058 tree next_subobject;
1059 vec<tree, va_gc> *vbases;
1060 int i;
1061 int uses_unions_or_anon_p = 0;
1063 /* Build up a list of initializations. The TREE_PURPOSE of entry
1064 will be the subobject (a FIELD_DECL or BINFO) to initialize. The
1065 TREE_VALUE will be the constructor arguments, or NULL if no
1066 explicit initialization was provided. */
1067 sorted_inits = NULL_TREE;
1069 /* Process the virtual bases. */
1070 for (vbases = CLASSTYPE_VBASECLASSES (t), i = 0;
1071 vec_safe_iterate (vbases, i, &base); i++)
1072 sorted_inits = tree_cons (base, NULL_TREE, sorted_inits);
1074 /* Process the direct bases. */
1075 for (binfo = TYPE_BINFO (t), i = 0;
1076 BINFO_BASE_ITERATE (binfo, i, base_binfo); ++i)
1077 if (!BINFO_VIRTUAL_P (base_binfo))
1078 sorted_inits = tree_cons (base_binfo, NULL_TREE, sorted_inits);
1080 /* Process the non-static data members. */
1081 sorted_inits = build_field_list (t, sorted_inits, &uses_unions_or_anon_p);
1082 /* Reverse the entire list of initializations, so that they are in
1083 the order that they will actually be performed. */
1084 sorted_inits = nreverse (sorted_inits);
1086 /* If the user presented the initializers in an order different from
1087 that in which they will actually occur, we issue a warning. Keep
1088 track of the next subobject which can be explicitly initialized
1089 without issuing a warning. */
1090 next_subobject = sorted_inits;
1092 /* Go through the explicit initializers, filling in TREE_PURPOSE in
1093 the SORTED_INITS. */
1094 for (init = mem_inits; init; init = TREE_CHAIN (init))
1096 tree subobject;
1097 tree subobject_init;
1099 subobject = TREE_PURPOSE (init);
1101 /* If the explicit initializers are in sorted order, then
1102 SUBOBJECT will be NEXT_SUBOBJECT, or something following
1103 it. */
1104 for (subobject_init = next_subobject;
1105 subobject_init;
1106 subobject_init = TREE_CHAIN (subobject_init))
1107 if (TREE_PURPOSE (subobject_init) == subobject)
1108 break;
1110 /* Issue a warning if the explicit initializer order does not
1111 match that which will actually occur.
1112 ??? Are all these on the correct lines? */
1113 if (warn_reorder && !subobject_init)
1115 if (TREE_CODE (TREE_PURPOSE (next_subobject)) == FIELD_DECL)
1116 warning_at (DECL_SOURCE_LOCATION (TREE_PURPOSE (next_subobject)),
1117 OPT_Wreorder, "%qD will be initialized after",
1118 TREE_PURPOSE (next_subobject));
1119 else
1120 warning (OPT_Wreorder, "base %qT will be initialized after",
1121 TREE_PURPOSE (next_subobject));
1122 if (TREE_CODE (subobject) == FIELD_DECL)
1123 warning_at (DECL_SOURCE_LOCATION (subobject),
1124 OPT_Wreorder, " %q#D", subobject);
1125 else
1126 warning (OPT_Wreorder, " base %qT", subobject);
1127 warning_at (DECL_SOURCE_LOCATION (current_function_decl),
1128 OPT_Wreorder, " when initialized here");
1131 /* Look again, from the beginning of the list. */
1132 if (!subobject_init)
1134 subobject_init = sorted_inits;
1135 while (TREE_PURPOSE (subobject_init) != subobject)
1136 subobject_init = TREE_CHAIN (subobject_init);
1139 /* It is invalid to initialize the same subobject more than
1140 once. */
1141 if (TREE_VALUE (subobject_init))
1143 if (TREE_CODE (subobject) == FIELD_DECL)
1144 error_at (DECL_SOURCE_LOCATION (current_function_decl),
1145 "multiple initializations given for %qD",
1146 subobject);
1147 else
1148 error_at (DECL_SOURCE_LOCATION (current_function_decl),
1149 "multiple initializations given for base %qT",
1150 subobject);
1153 /* Record the initialization. */
1154 TREE_VALUE (subobject_init) = TREE_VALUE (init);
1155 next_subobject = subobject_init;
1158 /* [class.base.init]
1160 If a ctor-initializer specifies more than one mem-initializer for
1161 multiple members of the same union (including members of
1162 anonymous unions), the ctor-initializer is ill-formed.
1164 Here we also splice out uninitialized union members. */
1165 if (uses_unions_or_anon_p)
1167 tree *last_p = NULL;
1168 tree *p;
1169 for (p = &sorted_inits; *p; )
1171 tree field;
1172 tree ctx;
1174 init = *p;
1176 field = TREE_PURPOSE (init);
1178 /* Skip base classes. */
1179 if (TREE_CODE (field) != FIELD_DECL)
1180 goto next;
1182 /* If this is an anonymous aggregate with no explicit initializer,
1183 splice it out. */
1184 if (!TREE_VALUE (init) && ANON_AGGR_TYPE_P (TREE_TYPE (field)))
1185 goto splice;
1187 /* See if this field is a member of a union, or a member of a
1188 structure contained in a union, etc. */
1189 ctx = innermost_aggr_scope (field);
1191 /* If this field is not a member of a union, skip it. */
1192 if (TREE_CODE (ctx) != UNION_TYPE
1193 && !ANON_AGGR_TYPE_P (ctx))
1194 goto next;
1196 /* If this union member has no explicit initializer and no NSDMI,
1197 splice it out. */
1198 if (TREE_VALUE (init) || DECL_INITIAL (field))
1199 /* OK. */;
1200 else
1201 goto splice;
1203 /* It's only an error if we have two initializers for the same
1204 union type. */
1205 if (!last_p)
1207 last_p = p;
1208 goto next;
1211 /* See if LAST_FIELD and the field initialized by INIT are
1212 members of the same union (or the union itself). If so, there's
1213 a problem, unless they're actually members of the same structure
1214 which is itself a member of a union. For example, given:
1216 union { struct { int i; int j; }; };
1218 initializing both `i' and `j' makes sense. */
1219 ctx = common_enclosing_class
1220 (innermost_aggr_scope (field),
1221 innermost_aggr_scope (TREE_PURPOSE (*last_p)));
1223 if (ctx && (TREE_CODE (ctx) == UNION_TYPE
1224 || ctx == TREE_TYPE (TREE_PURPOSE (*last_p))))
1226 /* A mem-initializer hides an NSDMI. */
1227 if (TREE_VALUE (init) && !TREE_VALUE (*last_p))
1228 *last_p = TREE_CHAIN (*last_p);
1229 else if (TREE_VALUE (*last_p) && !TREE_VALUE (init))
1230 goto splice;
1231 else
1233 error_at (DECL_SOURCE_LOCATION (current_function_decl),
1234 "initializations for multiple members of %qT",
1235 ctx);
1236 goto splice;
1240 last_p = p;
1242 next:
1243 p = &TREE_CHAIN (*p);
1244 continue;
1245 splice:
1246 *p = TREE_CHAIN (*p);
1247 continue;
1251 return sorted_inits;
1254 /* Callback for cp_walk_tree to mark all PARM_DECLs in a tree as read. */
1256 static tree
1257 mark_exp_read_r (tree *tp, int *, void *)
1259 tree t = *tp;
1260 if (TREE_CODE (t) == PARM_DECL)
1261 mark_exp_read (t);
1262 return NULL_TREE;
1265 /* Initialize all bases and members of CURRENT_CLASS_TYPE. MEM_INITS
1266 is a TREE_LIST giving the explicit mem-initializer-list for the
1267 constructor. The TREE_PURPOSE of each entry is a subobject (a
1268 FIELD_DECL or a BINFO) of the CURRENT_CLASS_TYPE. The TREE_VALUE
1269 is a TREE_LIST giving the arguments to the constructor or
1270 void_type_node for an empty list of arguments. */
1272 void
1273 emit_mem_initializers (tree mem_inits)
1275 int flags = LOOKUP_NORMAL;
1277 /* We will already have issued an error message about the fact that
1278 the type is incomplete. */
1279 if (!COMPLETE_TYPE_P (current_class_type))
1280 return;
1282 if (mem_inits
1283 && TYPE_P (TREE_PURPOSE (mem_inits))
1284 && same_type_p (TREE_PURPOSE (mem_inits), current_class_type))
1286 /* Delegating constructor. */
1287 gcc_assert (TREE_CHAIN (mem_inits) == NULL_TREE);
1288 perform_target_ctor (TREE_VALUE (mem_inits));
1289 return;
1292 if (DECL_DEFAULTED_FN (current_function_decl)
1293 && ! DECL_INHERITED_CTOR (current_function_decl))
1294 flags |= LOOKUP_DEFAULTED;
1296 /* Sort the mem-initializers into the order in which the
1297 initializations should be performed. */
1298 mem_inits = sort_mem_initializers (current_class_type, mem_inits);
1300 in_base_initializer = 1;
1302 /* Initialize base classes. */
1303 for (; (mem_inits
1304 && TREE_CODE (TREE_PURPOSE (mem_inits)) != FIELD_DECL);
1305 mem_inits = TREE_CHAIN (mem_inits))
1307 tree subobject = TREE_PURPOSE (mem_inits);
1308 tree arguments = TREE_VALUE (mem_inits);
1310 /* We already have issued an error message. */
1311 if (arguments == error_mark_node)
1312 continue;
1314 /* Suppress access control when calling the inherited ctor. */
1315 bool inherited_base = (DECL_INHERITED_CTOR (current_function_decl)
1316 && flag_new_inheriting_ctors
1317 && arguments);
1318 if (inherited_base)
1319 push_deferring_access_checks (dk_deferred);
1321 if (arguments == NULL_TREE)
1323 /* If these initializations are taking place in a copy constructor,
1324 the base class should probably be explicitly initialized if there
1325 is a user-defined constructor in the base class (other than the
1326 default constructor, which will be called anyway). */
1327 if (extra_warnings
1328 && DECL_COPY_CONSTRUCTOR_P (current_function_decl)
1329 && type_has_user_nondefault_constructor (BINFO_TYPE (subobject)))
1330 warning_at (DECL_SOURCE_LOCATION (current_function_decl),
1331 OPT_Wextra, "base class %q#T should be explicitly "
1332 "initialized in the copy constructor",
1333 BINFO_TYPE (subobject));
1336 /* Initialize the base. */
1337 if (!BINFO_VIRTUAL_P (subobject))
1339 tree base_addr;
1341 base_addr = build_base_path (PLUS_EXPR, current_class_ptr,
1342 subobject, 1, tf_warning_or_error);
1343 expand_aggr_init_1 (subobject, NULL_TREE,
1344 cp_build_fold_indirect_ref (base_addr),
1345 arguments,
1346 flags,
1347 tf_warning_or_error);
1348 expand_cleanup_for_base (subobject, NULL_TREE);
1350 else if (!ABSTRACT_CLASS_TYPE_P (current_class_type))
1351 /* C++14 DR1658 Means we do not have to construct vbases of
1352 abstract classes. */
1353 construct_virtual_base (subobject, arguments);
1354 else
1355 /* When not constructing vbases of abstract classes, at least mark
1356 the arguments expressions as read to avoid
1357 -Wunused-but-set-parameter false positives. */
1358 cp_walk_tree (&arguments, mark_exp_read_r, NULL, NULL);
1360 if (inherited_base)
1361 pop_deferring_access_checks ();
1363 in_base_initializer = 0;
1365 /* Initialize the vptrs. */
1366 initialize_vtbl_ptrs (current_class_ptr);
1368 /* Initialize the data members. */
1369 while (mem_inits)
1371 perform_member_init (TREE_PURPOSE (mem_inits),
1372 TREE_VALUE (mem_inits));
1373 mem_inits = TREE_CHAIN (mem_inits);
1377 /* Returns the address of the vtable (i.e., the value that should be
1378 assigned to the vptr) for BINFO. */
1380 tree
1381 build_vtbl_address (tree binfo)
1383 tree binfo_for = binfo;
1384 tree vtbl;
1386 if (BINFO_VPTR_INDEX (binfo) && BINFO_VIRTUAL_P (binfo))
1387 /* If this is a virtual primary base, then the vtable we want to store
1388 is that for the base this is being used as the primary base of. We
1389 can't simply skip the initialization, because we may be expanding the
1390 inits of a subobject constructor where the virtual base layout
1391 can be different. */
1392 while (BINFO_PRIMARY_P (binfo_for))
1393 binfo_for = BINFO_INHERITANCE_CHAIN (binfo_for);
1395 /* Figure out what vtable BINFO's vtable is based on, and mark it as
1396 used. */
1397 vtbl = get_vtbl_decl_for_binfo (binfo_for);
1398 TREE_USED (vtbl) = true;
1400 /* Now compute the address to use when initializing the vptr. */
1401 vtbl = unshare_expr (BINFO_VTABLE (binfo_for));
1402 if (VAR_P (vtbl))
1403 vtbl = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (vtbl)), vtbl);
1405 return vtbl;
1408 /* This code sets up the virtual function tables appropriate for
1409 the pointer DECL. It is a one-ply initialization.
1411 BINFO is the exact type that DECL is supposed to be. In
1412 multiple inheritance, this might mean "C's A" if C : A, B. */
1414 static void
1415 expand_virtual_init (tree binfo, tree decl)
1417 tree vtbl, vtbl_ptr;
1418 tree vtt_index;
1420 /* Compute the initializer for vptr. */
1421 vtbl = build_vtbl_address (binfo);
1423 /* We may get this vptr from a VTT, if this is a subobject
1424 constructor or subobject destructor. */
1425 vtt_index = BINFO_VPTR_INDEX (binfo);
1426 if (vtt_index)
1428 tree vtbl2;
1429 tree vtt_parm;
1431 /* Compute the value to use, when there's a VTT. */
1432 vtt_parm = current_vtt_parm;
1433 vtbl2 = fold_build_pointer_plus (vtt_parm, vtt_index);
1434 vtbl2 = cp_build_fold_indirect_ref (vtbl2);
1435 vtbl2 = convert (TREE_TYPE (vtbl), vtbl2);
1437 /* The actual initializer is the VTT value only in the subobject
1438 constructor. In maybe_clone_body we'll substitute NULL for
1439 the vtt_parm in the case of the non-subobject constructor. */
1440 vtbl = build_if_in_charge (vtbl, vtbl2);
1443 /* Compute the location of the vtpr. */
1444 vtbl_ptr = build_vfield_ref (cp_build_fold_indirect_ref (decl),
1445 TREE_TYPE (binfo));
1446 gcc_assert (vtbl_ptr != error_mark_node);
1448 /* Assign the vtable to the vptr. */
1449 vtbl = convert_force (TREE_TYPE (vtbl_ptr), vtbl, 0, tf_warning_or_error);
1450 finish_expr_stmt (cp_build_modify_expr (input_location, vtbl_ptr, NOP_EXPR,
1451 vtbl, tf_warning_or_error));
1454 /* If an exception is thrown in a constructor, those base classes already
1455 constructed must be destroyed. This function creates the cleanup
1456 for BINFO, which has just been constructed. If FLAG is non-NULL,
1457 it is a DECL which is nonzero when this base needs to be
1458 destroyed. */
1460 static void
1461 expand_cleanup_for_base (tree binfo, tree flag)
1463 tree expr;
1465 if (!type_build_dtor_call (BINFO_TYPE (binfo)))
1466 return;
1468 /* Call the destructor. */
1469 expr = build_special_member_call (current_class_ref,
1470 base_dtor_identifier,
1471 NULL,
1472 binfo,
1473 LOOKUP_NORMAL | LOOKUP_NONVIRTUAL,
1474 tf_warning_or_error);
1476 if (TYPE_HAS_TRIVIAL_DESTRUCTOR (BINFO_TYPE (binfo)))
1477 return;
1479 if (flag)
1480 expr = fold_build3_loc (input_location,
1481 COND_EXPR, void_type_node,
1482 c_common_truthvalue_conversion (input_location, flag),
1483 expr, integer_zero_node);
1485 finish_eh_cleanup (expr);
1488 /* Construct the virtual base-class VBASE passing the ARGUMENTS to its
1489 constructor. */
1491 static void
1492 construct_virtual_base (tree vbase, tree arguments)
1494 tree inner_if_stmt;
1495 tree exp;
1496 tree flag;
1498 /* If there are virtual base classes with destructors, we need to
1499 emit cleanups to destroy them if an exception is thrown during
1500 the construction process. These exception regions (i.e., the
1501 period during which the cleanups must occur) begin from the time
1502 the construction is complete to the end of the function. If we
1503 create a conditional block in which to initialize the
1504 base-classes, then the cleanup region for the virtual base begins
1505 inside a block, and ends outside of that block. This situation
1506 confuses the sjlj exception-handling code. Therefore, we do not
1507 create a single conditional block, but one for each
1508 initialization. (That way the cleanup regions always begin
1509 in the outer block.) We trust the back end to figure out
1510 that the FLAG will not change across initializations, and
1511 avoid doing multiple tests. */
1512 flag = DECL_CHAIN (DECL_ARGUMENTS (current_function_decl));
1513 inner_if_stmt = begin_if_stmt ();
1514 finish_if_stmt_cond (flag, inner_if_stmt);
1516 /* Compute the location of the virtual base. If we're
1517 constructing virtual bases, then we must be the most derived
1518 class. Therefore, we don't have to look up the virtual base;
1519 we already know where it is. */
1520 exp = convert_to_base_statically (current_class_ref, vbase);
1522 expand_aggr_init_1 (vbase, current_class_ref, exp, arguments,
1523 0, tf_warning_or_error);
1524 finish_then_clause (inner_if_stmt);
1525 finish_if_stmt (inner_if_stmt);
1527 expand_cleanup_for_base (vbase, flag);
1530 /* Find the context in which this FIELD can be initialized. */
1532 static tree
1533 initializing_context (tree field)
1535 tree t = DECL_CONTEXT (field);
1537 /* Anonymous union members can be initialized in the first enclosing
1538 non-anonymous union context. */
1539 while (t && ANON_AGGR_TYPE_P (t))
1540 t = TYPE_CONTEXT (t);
1541 return t;
1544 /* Function to give error message if member initialization specification
1545 is erroneous. FIELD is the member we decided to initialize.
1546 TYPE is the type for which the initialization is being performed.
1547 FIELD must be a member of TYPE.
1549 MEMBER_NAME is the name of the member. */
1551 static int
1552 member_init_ok_or_else (tree field, tree type, tree member_name)
1554 if (field == error_mark_node)
1555 return 0;
1556 if (!field)
1558 error ("class %qT does not have any field named %qD", type,
1559 member_name);
1560 return 0;
1562 if (VAR_P (field))
1564 error ("%q#D is a static data member; it can only be "
1565 "initialized at its definition",
1566 field);
1567 return 0;
1569 if (TREE_CODE (field) != FIELD_DECL)
1571 error ("%q#D is not a non-static data member of %qT",
1572 field, type);
1573 return 0;
1575 if (initializing_context (field) != type)
1577 error ("class %qT does not have any field named %qD", type,
1578 member_name);
1579 return 0;
1582 return 1;
1585 /* NAME is a FIELD_DECL, an IDENTIFIER_NODE which names a field, or it
1586 is a _TYPE node or TYPE_DECL which names a base for that type.
1587 Check the validity of NAME, and return either the base _TYPE, base
1588 binfo, or the FIELD_DECL of the member. If NAME is invalid, return
1589 NULL_TREE and issue a diagnostic.
1591 An old style unnamed direct single base construction is permitted,
1592 where NAME is NULL. */
1594 tree
1595 expand_member_init (tree name)
1597 tree basetype;
1598 tree field;
1600 if (!current_class_ref)
1601 return NULL_TREE;
1603 if (!name)
1605 /* This is an obsolete unnamed base class initializer. The
1606 parser will already have warned about its use. */
1607 switch (BINFO_N_BASE_BINFOS (TYPE_BINFO (current_class_type)))
1609 case 0:
1610 error ("unnamed initializer for %qT, which has no base classes",
1611 current_class_type);
1612 return NULL_TREE;
1613 case 1:
1614 basetype = BINFO_TYPE
1615 (BINFO_BASE_BINFO (TYPE_BINFO (current_class_type), 0));
1616 break;
1617 default:
1618 error ("unnamed initializer for %qT, which uses multiple inheritance",
1619 current_class_type);
1620 return NULL_TREE;
1623 else if (TYPE_P (name))
1625 basetype = TYPE_MAIN_VARIANT (name);
1626 name = TYPE_NAME (name);
1628 else if (TREE_CODE (name) == TYPE_DECL)
1629 basetype = TYPE_MAIN_VARIANT (TREE_TYPE (name));
1630 else
1631 basetype = NULL_TREE;
1633 if (basetype)
1635 tree class_binfo;
1636 tree direct_binfo;
1637 tree virtual_binfo;
1638 int i;
1640 if (current_template_parms
1641 || same_type_p (basetype, current_class_type))
1642 return basetype;
1644 class_binfo = TYPE_BINFO (current_class_type);
1645 direct_binfo = NULL_TREE;
1646 virtual_binfo = NULL_TREE;
1648 /* Look for a direct base. */
1649 for (i = 0; BINFO_BASE_ITERATE (class_binfo, i, direct_binfo); ++i)
1650 if (SAME_BINFO_TYPE_P (BINFO_TYPE (direct_binfo), basetype))
1651 break;
1653 /* Look for a virtual base -- unless the direct base is itself
1654 virtual. */
1655 if (!direct_binfo || !BINFO_VIRTUAL_P (direct_binfo))
1656 virtual_binfo = binfo_for_vbase (basetype, current_class_type);
1658 /* [class.base.init]
1660 If a mem-initializer-id is ambiguous because it designates
1661 both a direct non-virtual base class and an inherited virtual
1662 base class, the mem-initializer is ill-formed. */
1663 if (direct_binfo && virtual_binfo)
1665 error ("%qD is both a direct base and an indirect virtual base",
1666 basetype);
1667 return NULL_TREE;
1670 if (!direct_binfo && !virtual_binfo)
1672 if (CLASSTYPE_VBASECLASSES (current_class_type))
1673 error ("type %qT is not a direct or virtual base of %qT",
1674 basetype, current_class_type);
1675 else
1676 error ("type %qT is not a direct base of %qT",
1677 basetype, current_class_type);
1678 return NULL_TREE;
1681 return direct_binfo ? direct_binfo : virtual_binfo;
1683 else
1685 if (identifier_p (name))
1686 field = lookup_field (current_class_type, name, 1, false);
1687 else
1688 field = name;
1690 if (member_init_ok_or_else (field, current_class_type, name))
1691 return field;
1694 return NULL_TREE;
1697 /* This is like `expand_member_init', only it stores one aggregate
1698 value into another.
1700 INIT comes in two flavors: it is either a value which
1701 is to be stored in EXP, or it is a parameter list
1702 to go to a constructor, which will operate on EXP.
1703 If INIT is not a parameter list for a constructor, then set
1704 LOOKUP_ONLYCONVERTING.
1705 If FLAGS is LOOKUP_ONLYCONVERTING then it is the = init form of
1706 the initializer, if FLAGS is 0, then it is the (init) form.
1707 If `init' is a CONSTRUCTOR, then we emit a warning message,
1708 explaining that such initializations are invalid.
1710 If INIT resolves to a CALL_EXPR which happens to return
1711 something of the type we are looking for, then we know
1712 that we can safely use that call to perform the
1713 initialization.
1715 The virtual function table pointer cannot be set up here, because
1716 we do not really know its type.
1718 This never calls operator=().
1720 When initializing, nothing is CONST.
1722 A default copy constructor may have to be used to perform the
1723 initialization.
1725 A constructor or a conversion operator may have to be used to
1726 perform the initialization, but not both, as it would be ambiguous. */
1728 tree
1729 build_aggr_init (tree exp, tree init, int flags, tsubst_flags_t complain)
1731 tree stmt_expr;
1732 tree compound_stmt;
1733 int destroy_temps;
1734 tree type = TREE_TYPE (exp);
1735 int was_const = TREE_READONLY (exp);
1736 int was_volatile = TREE_THIS_VOLATILE (exp);
1737 int is_global;
1739 if (init == error_mark_node)
1740 return error_mark_node;
1742 location_t init_loc = (init
1743 ? cp_expr_loc_or_loc (init, input_location)
1744 : location_of (exp));
1746 TREE_READONLY (exp) = 0;
1747 TREE_THIS_VOLATILE (exp) = 0;
1749 if (TREE_CODE (type) == ARRAY_TYPE)
1751 tree itype = init ? TREE_TYPE (init) : NULL_TREE;
1752 int from_array = 0;
1754 if (VAR_P (exp) && DECL_DECOMPOSITION_P (exp))
1756 from_array = 1;
1757 init = mark_rvalue_use (init);
1758 if (init && DECL_P (init)
1759 && !(flags & LOOKUP_ONLYCONVERTING))
1761 /* Wrap the initializer in a CONSTRUCTOR so that build_vec_init
1762 recognizes it as direct-initialization. */
1763 init = build_constructor_single (init_list_type_node,
1764 NULL_TREE, init);
1765 CONSTRUCTOR_IS_DIRECT_INIT (init) = true;
1768 else
1770 /* Must arrange to initialize each element of EXP
1771 from elements of INIT. */
1772 if (cv_qualified_p (type))
1773 TREE_TYPE (exp) = cv_unqualified (type);
1774 if (itype && cv_qualified_p (itype))
1775 TREE_TYPE (init) = cv_unqualified (itype);
1776 from_array = (itype && same_type_p (TREE_TYPE (init),
1777 TREE_TYPE (exp)));
1779 if (init && !BRACE_ENCLOSED_INITIALIZER_P (init)
1780 && (!from_array
1781 || (TREE_CODE (init) != CONSTRUCTOR
1782 /* Can happen, eg, handling the compound-literals
1783 extension (ext/complit12.C). */
1784 && TREE_CODE (init) != TARGET_EXPR)))
1786 if (complain & tf_error)
1787 error_at (init_loc, "array must be initialized "
1788 "with a brace-enclosed initializer");
1789 return error_mark_node;
1793 stmt_expr = build_vec_init (exp, NULL_TREE, init,
1794 /*explicit_value_init_p=*/false,
1795 from_array,
1796 complain);
1797 TREE_READONLY (exp) = was_const;
1798 TREE_THIS_VOLATILE (exp) = was_volatile;
1799 TREE_TYPE (exp) = type;
1800 /* Restore the type of init unless it was used directly. */
1801 if (init && TREE_CODE (stmt_expr) != INIT_EXPR)
1802 TREE_TYPE (init) = itype;
1803 return stmt_expr;
1806 if (init && init != void_type_node
1807 && TREE_CODE (init) != TREE_LIST
1808 && !(TREE_CODE (init) == TARGET_EXPR
1809 && TARGET_EXPR_DIRECT_INIT_P (init))
1810 && !DIRECT_LIST_INIT_P (init))
1811 flags |= LOOKUP_ONLYCONVERTING;
1813 is_global = begin_init_stmts (&stmt_expr, &compound_stmt);
1814 destroy_temps = stmts_are_full_exprs_p ();
1815 current_stmt_tree ()->stmts_are_full_exprs_p = 0;
1816 expand_aggr_init_1 (TYPE_BINFO (type), exp, exp,
1817 init, LOOKUP_NORMAL|flags, complain);
1818 stmt_expr = finish_init_stmts (is_global, stmt_expr, compound_stmt);
1819 current_stmt_tree ()->stmts_are_full_exprs_p = destroy_temps;
1820 TREE_READONLY (exp) = was_const;
1821 TREE_THIS_VOLATILE (exp) = was_volatile;
1823 if ((VAR_P (exp) || TREE_CODE (exp) == PARM_DECL)
1824 && TREE_SIDE_EFFECTS (stmt_expr)
1825 && !lookup_attribute ("warn_unused", TYPE_ATTRIBUTES (type)))
1826 /* Just know that we've seen something for this node. */
1827 TREE_USED (exp) = 1;
1829 return stmt_expr;
1832 static void
1833 expand_default_init (tree binfo, tree true_exp, tree exp, tree init, int flags,
1834 tsubst_flags_t complain)
1836 tree type = TREE_TYPE (exp);
1838 /* It fails because there may not be a constructor which takes
1839 its own type as the first (or only parameter), but which does
1840 take other types via a conversion. So, if the thing initializing
1841 the expression is a unit element of type X, first try X(X&),
1842 followed by initialization by X. If neither of these work
1843 out, then look hard. */
1844 tree rval;
1845 vec<tree, va_gc> *parms;
1847 /* If we have direct-initialization from an initializer list, pull
1848 it out of the TREE_LIST so the code below can see it. */
1849 if (init && TREE_CODE (init) == TREE_LIST
1850 && DIRECT_LIST_INIT_P (TREE_VALUE (init)))
1852 gcc_checking_assert ((flags & LOOKUP_ONLYCONVERTING) == 0
1853 && TREE_CHAIN (init) == NULL_TREE);
1854 init = TREE_VALUE (init);
1855 /* Only call reshape_init if it has not been called earlier
1856 by the callers. */
1857 if (BRACE_ENCLOSED_INITIALIZER_P (init) && CP_AGGREGATE_TYPE_P (type))
1858 init = reshape_init (type, init, complain);
1861 if (init && BRACE_ENCLOSED_INITIALIZER_P (init)
1862 && CP_AGGREGATE_TYPE_P (type))
1863 /* A brace-enclosed initializer for an aggregate. In C++0x this can
1864 happen for direct-initialization, too. */
1865 init = digest_init (type, init, complain);
1867 /* A CONSTRUCTOR of the target's type is a previously digested
1868 initializer, whether that happened just above or in
1869 cp_parser_late_parsing_nsdmi.
1871 A TARGET_EXPR with TARGET_EXPR_DIRECT_INIT_P or TARGET_EXPR_LIST_INIT_P
1872 set represents the whole initialization, so we shouldn't build up
1873 another ctor call. */
1874 if (init
1875 && (TREE_CODE (init) == CONSTRUCTOR
1876 || (TREE_CODE (init) == TARGET_EXPR
1877 && (TARGET_EXPR_DIRECT_INIT_P (init)
1878 || TARGET_EXPR_LIST_INIT_P (init))))
1879 && same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (init), type))
1881 /* Early initialization via a TARGET_EXPR only works for
1882 complete objects. */
1883 gcc_assert (TREE_CODE (init) == CONSTRUCTOR || true_exp == exp);
1885 init = build2 (INIT_EXPR, TREE_TYPE (exp), exp, init);
1886 TREE_SIDE_EFFECTS (init) = 1;
1887 finish_expr_stmt (init);
1888 return;
1891 if (init && TREE_CODE (init) != TREE_LIST
1892 && (flags & LOOKUP_ONLYCONVERTING))
1894 /* Base subobjects should only get direct-initialization. */
1895 gcc_assert (true_exp == exp);
1897 if (flags & DIRECT_BIND)
1898 /* Do nothing. We hit this in two cases: Reference initialization,
1899 where we aren't initializing a real variable, so we don't want
1900 to run a new constructor; and catching an exception, where we
1901 have already built up the constructor call so we could wrap it
1902 in an exception region. */;
1903 else
1904 init = ocp_convert (type, init, CONV_IMPLICIT|CONV_FORCE_TEMP,
1905 flags, complain);
1907 if (TREE_CODE (init) == MUST_NOT_THROW_EXPR)
1908 /* We need to protect the initialization of a catch parm with a
1909 call to terminate(), which shows up as a MUST_NOT_THROW_EXPR
1910 around the TARGET_EXPR for the copy constructor. See
1911 initialize_handler_parm. */
1913 TREE_OPERAND (init, 0) = build2 (INIT_EXPR, TREE_TYPE (exp), exp,
1914 TREE_OPERAND (init, 0));
1915 TREE_TYPE (init) = void_type_node;
1917 else
1918 init = build2 (INIT_EXPR, TREE_TYPE (exp), exp, init);
1919 TREE_SIDE_EFFECTS (init) = 1;
1920 finish_expr_stmt (init);
1921 return;
1924 if (init == NULL_TREE)
1925 parms = NULL;
1926 else if (TREE_CODE (init) == TREE_LIST && !TREE_TYPE (init))
1928 parms = make_tree_vector ();
1929 for (; init != NULL_TREE; init = TREE_CHAIN (init))
1930 vec_safe_push (parms, TREE_VALUE (init));
1932 else
1933 parms = make_tree_vector_single (init);
1935 if (exp == current_class_ref && current_function_decl
1936 && DECL_HAS_IN_CHARGE_PARM_P (current_function_decl))
1938 /* Delegating constructor. */
1939 tree complete;
1940 tree base;
1941 tree elt; unsigned i;
1943 /* Unshare the arguments for the second call. */
1944 vec<tree, va_gc> *parms2 = make_tree_vector ();
1945 FOR_EACH_VEC_SAFE_ELT (parms, i, elt)
1947 elt = break_out_target_exprs (elt);
1948 vec_safe_push (parms2, elt);
1950 complete = build_special_member_call (exp, complete_ctor_identifier,
1951 &parms2, binfo, flags,
1952 complain);
1953 complete = fold_build_cleanup_point_expr (void_type_node, complete);
1954 release_tree_vector (parms2);
1956 base = build_special_member_call (exp, base_ctor_identifier,
1957 &parms, binfo, flags,
1958 complain);
1959 base = fold_build_cleanup_point_expr (void_type_node, base);
1960 rval = build_if_in_charge (complete, base);
1962 else
1964 tree ctor_name = (true_exp == exp
1965 ? complete_ctor_identifier : base_ctor_identifier);
1967 rval = build_special_member_call (exp, ctor_name, &parms, binfo, flags,
1968 complain);
1971 if (parms != NULL)
1972 release_tree_vector (parms);
1974 if (exp == true_exp && TREE_CODE (rval) == CALL_EXPR)
1976 tree fn = get_callee_fndecl (rval);
1977 if (fn && DECL_DECLARED_CONSTEXPR_P (fn))
1979 tree e = maybe_constant_init (rval, exp);
1980 if (TREE_CONSTANT (e))
1981 rval = build2 (INIT_EXPR, type, exp, e);
1985 /* FIXME put back convert_to_void? */
1986 if (TREE_SIDE_EFFECTS (rval))
1987 finish_expr_stmt (rval);
1990 /* This function is responsible for initializing EXP with INIT
1991 (if any).
1993 BINFO is the binfo of the type for who we are performing the
1994 initialization. For example, if W is a virtual base class of A and B,
1995 and C : A, B.
1996 If we are initializing B, then W must contain B's W vtable, whereas
1997 were we initializing C, W must contain C's W vtable.
1999 TRUE_EXP is nonzero if it is the true expression being initialized.
2000 In this case, it may be EXP, or may just contain EXP. The reason we
2001 need this is because if EXP is a base element of TRUE_EXP, we
2002 don't necessarily know by looking at EXP where its virtual
2003 baseclass fields should really be pointing. But we do know
2004 from TRUE_EXP. In constructors, we don't know anything about
2005 the value being initialized.
2007 FLAGS is just passed to `build_new_method_call'. See that function
2008 for its description. */
2010 static void
2011 expand_aggr_init_1 (tree binfo, tree true_exp, tree exp, tree init, int flags,
2012 tsubst_flags_t complain)
2014 tree type = TREE_TYPE (exp);
2016 gcc_assert (init != error_mark_node && type != error_mark_node);
2017 gcc_assert (building_stmt_list_p ());
2019 /* Use a function returning the desired type to initialize EXP for us.
2020 If the function is a constructor, and its first argument is
2021 NULL_TREE, know that it was meant for us--just slide exp on
2022 in and expand the constructor. Constructors now come
2023 as TARGET_EXPRs. */
2025 if (init && VAR_P (exp)
2026 && COMPOUND_LITERAL_P (init))
2028 vec<tree, va_gc> *cleanups = NULL;
2029 /* If store_init_value returns NULL_TREE, the INIT has been
2030 recorded as the DECL_INITIAL for EXP. That means there's
2031 nothing more we have to do. */
2032 init = store_init_value (exp, init, &cleanups, flags);
2033 if (init)
2034 finish_expr_stmt (init);
2035 gcc_assert (!cleanups);
2036 return;
2039 /* List-initialization from {} becomes value-initialization for non-aggregate
2040 classes with default constructors. Handle this here when we're
2041 initializing a base, so protected access works. */
2042 if (exp != true_exp && init && TREE_CODE (init) == TREE_LIST)
2044 tree elt = TREE_VALUE (init);
2045 if (DIRECT_LIST_INIT_P (elt)
2046 && CONSTRUCTOR_ELTS (elt) == 0
2047 && CLASSTYPE_NON_AGGREGATE (type)
2048 && TYPE_HAS_DEFAULT_CONSTRUCTOR (type))
2049 init = void_type_node;
2052 /* If an explicit -- but empty -- initializer list was present,
2053 that's value-initialization. */
2054 if (init == void_type_node)
2056 /* If the type has data but no user-provided ctor, we need to zero
2057 out the object. */
2058 if (!type_has_user_provided_constructor (type)
2059 && !is_really_empty_class (type))
2061 tree field_size = NULL_TREE;
2062 if (exp != true_exp && CLASSTYPE_AS_BASE (type) != type)
2063 /* Don't clobber already initialized virtual bases. */
2064 field_size = TYPE_SIZE (CLASSTYPE_AS_BASE (type));
2065 init = build_zero_init_1 (type, NULL_TREE, /*static_storage_p=*/false,
2066 field_size);
2067 init = build2 (INIT_EXPR, type, exp, init);
2068 finish_expr_stmt (init);
2071 /* If we don't need to mess with the constructor at all,
2072 then we're done. */
2073 if (! type_build_ctor_call (type))
2074 return;
2076 /* Otherwise fall through and call the constructor. */
2077 init = NULL_TREE;
2080 /* We know that expand_default_init can handle everything we want
2081 at this point. */
2082 expand_default_init (binfo, true_exp, exp, init, flags, complain);
2085 /* Report an error if TYPE is not a user-defined, class type. If
2086 OR_ELSE is nonzero, give an error message. */
2089 is_class_type (tree type, int or_else)
2091 if (type == error_mark_node)
2092 return 0;
2094 if (! CLASS_TYPE_P (type))
2096 if (or_else)
2097 error ("%qT is not a class type", type);
2098 return 0;
2100 return 1;
2103 tree
2104 get_type_value (tree name)
2106 if (name == error_mark_node)
2107 return NULL_TREE;
2109 if (IDENTIFIER_HAS_TYPE_VALUE (name))
2110 return IDENTIFIER_TYPE_VALUE (name);
2111 else
2112 return NULL_TREE;
2115 /* Build a reference to a member of an aggregate. This is not a C++
2116 `&', but really something which can have its address taken, and
2117 then act as a pointer to member, for example TYPE :: FIELD can have
2118 its address taken by saying & TYPE :: FIELD. ADDRESS_P is true if
2119 this expression is the operand of "&".
2121 @@ Prints out lousy diagnostics for operator <typename>
2122 @@ fields.
2124 @@ This function should be rewritten and placed in search.c. */
2126 tree
2127 build_offset_ref (tree type, tree member, bool address_p,
2128 tsubst_flags_t complain)
2130 tree decl;
2131 tree basebinfo = NULL_TREE;
2133 /* class templates can come in as TEMPLATE_DECLs here. */
2134 if (TREE_CODE (member) == TEMPLATE_DECL)
2135 return member;
2137 if (dependent_scope_p (type) || type_dependent_expression_p (member))
2138 return build_qualified_name (NULL_TREE, type, member,
2139 /*template_p=*/false);
2141 gcc_assert (TYPE_P (type));
2142 if (! is_class_type (type, 1))
2143 return error_mark_node;
2145 gcc_assert (DECL_P (member) || BASELINK_P (member));
2146 /* Callers should call mark_used before this point. */
2147 gcc_assert (!DECL_P (member) || TREE_USED (member));
2149 type = TYPE_MAIN_VARIANT (type);
2150 if (!COMPLETE_OR_OPEN_TYPE_P (complete_type (type)))
2152 if (complain & tf_error)
2153 error ("incomplete type %qT does not have member %qD", type, member);
2154 return error_mark_node;
2157 /* Entities other than non-static members need no further
2158 processing. */
2159 if (TREE_CODE (member) == TYPE_DECL)
2160 return member;
2161 if (VAR_P (member) || TREE_CODE (member) == CONST_DECL)
2162 return convert_from_reference (member);
2164 if (TREE_CODE (member) == FIELD_DECL && DECL_C_BIT_FIELD (member))
2166 if (complain & tf_error)
2167 error ("invalid pointer to bit-field %qD", member);
2168 return error_mark_node;
2171 /* Set up BASEBINFO for member lookup. */
2172 decl = maybe_dummy_object (type, &basebinfo);
2174 /* A lot of this logic is now handled in lookup_member. */
2175 if (BASELINK_P (member))
2177 /* Go from the TREE_BASELINK to the member function info. */
2178 tree t = BASELINK_FUNCTIONS (member);
2180 if (TREE_CODE (t) != TEMPLATE_ID_EXPR && !really_overloaded_fn (t))
2182 /* Get rid of a potential OVERLOAD around it. */
2183 t = OVL_FIRST (t);
2185 /* Unique functions are handled easily. */
2187 /* For non-static member of base class, we need a special rule
2188 for access checking [class.protected]:
2190 If the access is to form a pointer to member, the
2191 nested-name-specifier shall name the derived class
2192 (or any class derived from that class). */
2193 bool ok;
2194 if (address_p && DECL_P (t)
2195 && DECL_NONSTATIC_MEMBER_P (t))
2196 ok = perform_or_defer_access_check (TYPE_BINFO (type), t, t,
2197 complain);
2198 else
2199 ok = perform_or_defer_access_check (basebinfo, t, t,
2200 complain);
2201 if (!ok)
2202 return error_mark_node;
2203 if (DECL_STATIC_FUNCTION_P (t))
2204 return t;
2205 member = t;
2207 else
2208 TREE_TYPE (member) = unknown_type_node;
2210 else if (address_p && TREE_CODE (member) == FIELD_DECL)
2212 /* We need additional test besides the one in
2213 check_accessibility_of_qualified_id in case it is
2214 a pointer to non-static member. */
2215 if (!perform_or_defer_access_check (TYPE_BINFO (type), member, member,
2216 complain))
2217 return error_mark_node;
2220 if (!address_p)
2222 /* If MEMBER is non-static, then the program has fallen afoul of
2223 [expr.prim]:
2225 An id-expression that denotes a nonstatic data member or
2226 nonstatic member function of a class can only be used:
2228 -- as part of a class member access (_expr.ref_) in which the
2229 object-expression refers to the member's class or a class
2230 derived from that class, or
2232 -- to form a pointer to member (_expr.unary.op_), or
2234 -- in the body of a nonstatic member function of that class or
2235 of a class derived from that class (_class.mfct.nonstatic_), or
2237 -- in a mem-initializer for a constructor for that class or for
2238 a class derived from that class (_class.base.init_). */
2239 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (member))
2241 /* Build a representation of the qualified name suitable
2242 for use as the operand to "&" -- even though the "&" is
2243 not actually present. */
2244 member = build2 (OFFSET_REF, TREE_TYPE (member), decl, member);
2245 /* In Microsoft mode, treat a non-static member function as if
2246 it were a pointer-to-member. */
2247 if (flag_ms_extensions)
2249 PTRMEM_OK_P (member) = 1;
2250 return cp_build_addr_expr (member, complain);
2252 if (complain & tf_error)
2253 error ("invalid use of non-static member function %qD",
2254 TREE_OPERAND (member, 1));
2255 return error_mark_node;
2257 else if (TREE_CODE (member) == FIELD_DECL)
2259 if (complain & tf_error)
2260 error ("invalid use of non-static data member %qD", member);
2261 return error_mark_node;
2263 return member;
2266 member = build2 (OFFSET_REF, TREE_TYPE (member), decl, member);
2267 PTRMEM_OK_P (member) = 1;
2268 return member;
2271 /* If DECL is a scalar enumeration constant or variable with a
2272 constant initializer, return the initializer (or, its initializers,
2273 recursively); otherwise, return DECL. If STRICT_P, the
2274 initializer is only returned if DECL is a
2275 constant-expression. If RETURN_AGGREGATE_CST_OK_P, it is ok to
2276 return an aggregate constant. */
2278 static tree
2279 constant_value_1 (tree decl, bool strict_p, bool return_aggregate_cst_ok_p)
2281 while (TREE_CODE (decl) == CONST_DECL
2282 || decl_constant_var_p (decl)
2283 || (!strict_p && VAR_P (decl)
2284 && CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (decl))))
2286 tree init;
2287 /* If DECL is a static data member in a template
2288 specialization, we must instantiate it here. The
2289 initializer for the static data member is not processed
2290 until needed; we need it now. */
2291 mark_used (decl, tf_none);
2292 init = DECL_INITIAL (decl);
2293 if (init == error_mark_node)
2295 if (TREE_CODE (decl) == CONST_DECL
2296 || DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
2297 /* Treat the error as a constant to avoid cascading errors on
2298 excessively recursive template instantiation (c++/9335). */
2299 return init;
2300 else
2301 return decl;
2303 /* Initializers in templates are generally expanded during
2304 instantiation, so before that for const int i(2)
2305 INIT is a TREE_LIST with the actual initializer as
2306 TREE_VALUE. */
2307 if (processing_template_decl
2308 && init
2309 && TREE_CODE (init) == TREE_LIST
2310 && TREE_CHAIN (init) == NULL_TREE)
2311 init = TREE_VALUE (init);
2312 /* Instantiate a non-dependent initializer for user variables. We
2313 mustn't do this for the temporary for an array compound literal;
2314 trying to instatiate the initializer will keep creating new
2315 temporaries until we crash. Probably it's not useful to do it for
2316 other artificial variables, either. */
2317 if (!DECL_ARTIFICIAL (decl))
2318 init = instantiate_non_dependent_or_null (init);
2319 if (!init
2320 || !TREE_TYPE (init)
2321 || !TREE_CONSTANT (init)
2322 || (!return_aggregate_cst_ok_p
2323 /* Unless RETURN_AGGREGATE_CST_OK_P is true, do not
2324 return an aggregate constant (of which string
2325 literals are a special case), as we do not want
2326 to make inadvertent copies of such entities, and
2327 we must be sure that their addresses are the
2328 same everywhere. */
2329 && (TREE_CODE (init) == CONSTRUCTOR
2330 || TREE_CODE (init) == STRING_CST)))
2331 break;
2332 /* Don't return a CONSTRUCTOR for a variable with partial run-time
2333 initialization, since it doesn't represent the entire value. */
2334 if (TREE_CODE (init) == CONSTRUCTOR
2335 && !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl))
2336 break;
2337 /* If the variable has a dynamic initializer, don't use its
2338 DECL_INITIAL which doesn't reflect the real value. */
2339 if (VAR_P (decl)
2340 && TREE_STATIC (decl)
2341 && !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl)
2342 && DECL_NONTRIVIALLY_INITIALIZED_P (decl))
2343 break;
2344 decl = unshare_expr (init);
2346 return decl;
2349 /* If DECL is a CONST_DECL, or a constant VAR_DECL initialized by constant
2350 of integral or enumeration type, or a constexpr variable of scalar type,
2351 then return that value. These are those variables permitted in constant
2352 expressions by [5.19/1]. */
2354 tree
2355 scalar_constant_value (tree decl)
2357 return constant_value_1 (decl, /*strict_p=*/true,
2358 /*return_aggregate_cst_ok_p=*/false);
2361 /* Like scalar_constant_value, but can also return aggregate initializers. */
2363 tree
2364 decl_really_constant_value (tree decl)
2366 return constant_value_1 (decl, /*strict_p=*/true,
2367 /*return_aggregate_cst_ok_p=*/true);
2370 /* A more relaxed version of scalar_constant_value, used by the
2371 common C/C++ code. */
2373 tree
2374 decl_constant_value (tree decl)
2376 return constant_value_1 (decl, /*strict_p=*/processing_template_decl,
2377 /*return_aggregate_cst_ok_p=*/true);
2380 /* Common subroutines of build_new and build_vec_delete. */
2382 /* Build and return a NEW_EXPR. If NELTS is non-NULL, TYPE[NELTS] is
2383 the type of the object being allocated; otherwise, it's just TYPE.
2384 INIT is the initializer, if any. USE_GLOBAL_NEW is true if the
2385 user explicitly wrote "::operator new". PLACEMENT, if non-NULL, is
2386 a vector of arguments to be provided as arguments to a placement
2387 new operator. This routine performs no semantic checks; it just
2388 creates and returns a NEW_EXPR. */
2390 static tree
2391 build_raw_new_expr (vec<tree, va_gc> *placement, tree type, tree nelts,
2392 vec<tree, va_gc> *init, int use_global_new)
2394 tree init_list;
2395 tree new_expr;
2397 /* If INIT is NULL, the we want to store NULL_TREE in the NEW_EXPR.
2398 If INIT is not NULL, then we want to store VOID_ZERO_NODE. This
2399 permits us to distinguish the case of a missing initializer "new
2400 int" from an empty initializer "new int()". */
2401 if (init == NULL)
2402 init_list = NULL_TREE;
2403 else if (init->is_empty ())
2404 init_list = void_node;
2405 else
2406 init_list = build_tree_list_vec (init);
2408 new_expr = build4 (NEW_EXPR, build_pointer_type (type),
2409 build_tree_list_vec (placement), type, nelts,
2410 init_list);
2411 NEW_EXPR_USE_GLOBAL (new_expr) = use_global_new;
2412 TREE_SIDE_EFFECTS (new_expr) = 1;
2414 return new_expr;
2417 /* Diagnose uninitialized const members or reference members of type
2418 TYPE. USING_NEW is used to disambiguate the diagnostic between a
2419 new expression without a new-initializer and a declaration. Returns
2420 the error count. */
2422 static int
2423 diagnose_uninitialized_cst_or_ref_member_1 (tree type, tree origin,
2424 bool using_new, bool complain)
2426 tree field;
2427 int error_count = 0;
2429 if (type_has_user_provided_constructor (type))
2430 return 0;
2432 for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
2434 tree field_type;
2436 if (TREE_CODE (field) != FIELD_DECL)
2437 continue;
2439 field_type = strip_array_types (TREE_TYPE (field));
2441 if (type_has_user_provided_constructor (field_type))
2442 continue;
2444 if (TYPE_REF_P (field_type))
2446 ++ error_count;
2447 if (complain)
2449 if (DECL_CONTEXT (field) == origin)
2451 if (using_new)
2452 error ("uninitialized reference member in %q#T "
2453 "using %<new%> without new-initializer", origin);
2454 else
2455 error ("uninitialized reference member in %q#T", origin);
2457 else
2459 if (using_new)
2460 error ("uninitialized reference member in base %q#T "
2461 "of %q#T using %<new%> without new-initializer",
2462 DECL_CONTEXT (field), origin);
2463 else
2464 error ("uninitialized reference member in base %q#T "
2465 "of %q#T", DECL_CONTEXT (field), origin);
2467 inform (DECL_SOURCE_LOCATION (field),
2468 "%q#D should be initialized", field);
2472 if (CP_TYPE_CONST_P (field_type))
2474 ++ error_count;
2475 if (complain)
2477 if (DECL_CONTEXT (field) == origin)
2479 if (using_new)
2480 error ("uninitialized const member in %q#T "
2481 "using %<new%> without new-initializer", origin);
2482 else
2483 error ("uninitialized const member in %q#T", origin);
2485 else
2487 if (using_new)
2488 error ("uninitialized const member in base %q#T "
2489 "of %q#T using %<new%> without new-initializer",
2490 DECL_CONTEXT (field), origin);
2491 else
2492 error ("uninitialized const member in base %q#T "
2493 "of %q#T", DECL_CONTEXT (field), origin);
2495 inform (DECL_SOURCE_LOCATION (field),
2496 "%q#D should be initialized", field);
2500 if (CLASS_TYPE_P (field_type))
2501 error_count
2502 += diagnose_uninitialized_cst_or_ref_member_1 (field_type, origin,
2503 using_new, complain);
2505 return error_count;
2509 diagnose_uninitialized_cst_or_ref_member (tree type, bool using_new, bool complain)
2511 return diagnose_uninitialized_cst_or_ref_member_1 (type, type, using_new, complain);
2514 /* Call __cxa_bad_array_new_length to indicate that the size calculation
2515 overflowed. Pretend it returns sizetype so that it plays nicely in the
2516 COND_EXPR. */
2518 tree
2519 throw_bad_array_new_length (void)
2521 if (!fn)
2523 tree name = get_identifier ("__cxa_throw_bad_array_new_length");
2525 fn = get_global_binding (name);
2526 if (!fn)
2527 fn = push_throw_library_fn
2528 (name, build_function_type_list (sizetype, NULL_TREE));
2531 return build_cxx_call (fn, 0, NULL, tf_warning_or_error);
2534 /* Attempt to find the initializer for flexible array field T in the
2535 initializer INIT, when non-null. Returns the initializer when
2536 successful and NULL otherwise. */
2537 static tree
2538 find_flexarray_init (tree t, tree init)
2540 if (!init || init == error_mark_node)
2541 return NULL_TREE;
2543 unsigned HOST_WIDE_INT idx;
2544 tree field, elt;
2546 /* Iterate over all top-level initializer elements. */
2547 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (init), idx, field, elt)
2548 /* If the member T is found, return it. */
2549 if (field == t)
2550 return elt;
2552 return NULL_TREE;
2555 /* Attempt to verify that the argument, OPER, of a placement new expression
2556 refers to an object sufficiently large for an object of TYPE or an array
2557 of NELTS of such objects when NELTS is non-null, and issue a warning when
2558 it does not. SIZE specifies the size needed to construct the object or
2559 array and captures the result of NELTS * sizeof (TYPE). (SIZE could be
2560 greater when the array under construction requires a cookie to store
2561 NELTS. GCC's placement new expression stores the cookie when invoking
2562 a user-defined placement new operator function but not the default one.
2563 Placement new expressions with user-defined placement new operator are
2564 not diagnosed since we don't know how they use the buffer (this could
2565 be a future extension). */
2566 static void
2567 warn_placement_new_too_small (tree type, tree nelts, tree size, tree oper)
2569 location_t loc = cp_expr_loc_or_loc (oper, input_location);
2571 /* The number of bytes to add to or subtract from the size of the provided
2572 buffer based on an offset into an array or an array element reference.
2573 Although intermediate results may be negative (as in a[3] - 2) a valid
2574 final result cannot be. */
2575 offset_int adjust = 0;
2576 /* True when the size of the entire destination object should be used
2577 to compute the possibly optimistic estimate of the available space. */
2578 bool use_obj_size = false;
2579 /* True when the reference to the destination buffer is an ADDR_EXPR. */
2580 bool addr_expr = false;
2582 STRIP_NOPS (oper);
2584 /* Using a function argument or a (non-array) variable as an argument
2585 to placement new is not checked since it's unknown what it might
2586 point to. */
2587 if (TREE_CODE (oper) == PARM_DECL
2588 || VAR_P (oper)
2589 || TREE_CODE (oper) == COMPONENT_REF)
2590 return;
2592 /* Evaluate any constant expressions. */
2593 size = fold_non_dependent_expr (size);
2595 /* Handle the common case of array + offset expression when the offset
2596 is a constant. */
2597 if (TREE_CODE (oper) == POINTER_PLUS_EXPR)
2599 /* If the offset is compile-time constant, use it to compute a more
2600 accurate estimate of the size of the buffer. Since the operand
2601 of POINTER_PLUS_EXPR is represented as an unsigned type, convert
2602 it to signed first.
2603 Otherwise, use the size of the entire array as an optimistic
2604 estimate (this may lead to false negatives). */
2605 tree adj = TREE_OPERAND (oper, 1);
2606 if (CONSTANT_CLASS_P (adj))
2607 adjust += wi::to_offset (convert (ssizetype, adj));
2608 else
2609 use_obj_size = true;
2611 oper = TREE_OPERAND (oper, 0);
2613 STRIP_NOPS (oper);
2616 if (TREE_CODE (oper) == TARGET_EXPR)
2617 oper = TREE_OPERAND (oper, 1);
2618 else if (TREE_CODE (oper) == ADDR_EXPR)
2620 addr_expr = true;
2621 oper = TREE_OPERAND (oper, 0);
2624 STRIP_NOPS (oper);
2626 if (TREE_CODE (oper) == ARRAY_REF
2627 && (addr_expr || TREE_CODE (TREE_TYPE (oper)) == ARRAY_TYPE))
2629 /* Similar to the offset computed above, see if the array index
2630 is a compile-time constant. If so, and unless the offset was
2631 not a compile-time constant, use the index to determine the
2632 size of the buffer. Otherwise, use the entire array as
2633 an optimistic estimate of the size. */
2634 const_tree adj = fold_non_dependent_expr (TREE_OPERAND (oper, 1));
2635 if (!use_obj_size && CONSTANT_CLASS_P (adj))
2636 adjust += wi::to_offset (adj);
2637 else
2639 use_obj_size = true;
2640 adjust = 0;
2643 oper = TREE_OPERAND (oper, 0);
2646 /* Refers to the declared object that constains the subobject referenced
2647 by OPER. When the object is initialized, makes it possible to determine
2648 the actual size of a flexible array member used as the buffer passed
2649 as OPER to placement new. */
2650 tree var_decl = NULL_TREE;
2651 /* True when operand is a COMPONENT_REF, to distinguish flexible array
2652 members from arrays of unspecified size. */
2653 bool compref = TREE_CODE (oper) == COMPONENT_REF;
2655 /* For COMPONENT_REF (i.e., a struct member) the size of the entire
2656 enclosing struct. Used to validate the adjustment (offset) into
2657 an array at the end of a struct. */
2658 offset_int compsize = 0;
2660 /* Descend into a struct or union to find the member whose address
2661 is being used as the argument. */
2662 if (TREE_CODE (oper) == COMPONENT_REF)
2664 tree comptype = TREE_TYPE (TREE_OPERAND (oper, 0));
2665 compsize = wi::to_offset (TYPE_SIZE_UNIT (comptype));
2667 tree op0 = oper;
2668 while (TREE_CODE (op0 = TREE_OPERAND (op0, 0)) == COMPONENT_REF);
2669 if (VAR_P (op0))
2670 var_decl = op0;
2671 oper = TREE_OPERAND (oper, 1);
2674 tree opertype = TREE_TYPE (oper);
2675 if ((addr_expr || !INDIRECT_TYPE_P (opertype))
2676 && (VAR_P (oper)
2677 || TREE_CODE (oper) == FIELD_DECL
2678 || TREE_CODE (oper) == PARM_DECL))
2680 /* A possibly optimistic estimate of the number of bytes available
2681 in the destination buffer. */
2682 offset_int bytes_avail = 0;
2683 /* True when the estimate above is in fact the exact size
2684 of the destination buffer rather than an estimate. */
2685 bool exact_size = true;
2687 /* Treat members of unions and members of structs uniformly, even
2688 though the size of a member of a union may be viewed as extending
2689 to the end of the union itself (it is by __builtin_object_size). */
2690 if ((VAR_P (oper) || use_obj_size)
2691 && DECL_SIZE_UNIT (oper)
2692 && tree_fits_uhwi_p (DECL_SIZE_UNIT (oper)))
2694 /* Use the size of the entire array object when the expression
2695 refers to a variable or its size depends on an expression
2696 that's not a compile-time constant. */
2697 bytes_avail = wi::to_offset (DECL_SIZE_UNIT (oper));
2698 exact_size = !use_obj_size;
2700 else if (tree opersize = TYPE_SIZE_UNIT (opertype))
2702 /* Use the size of the type of the destination buffer object
2703 as the optimistic estimate of the available space in it.
2704 Use the maximum possible size for zero-size arrays and
2705 flexible array members (except of initialized objects
2706 thereof). */
2707 if (TREE_CODE (opersize) == INTEGER_CST)
2708 bytes_avail = wi::to_offset (opersize);
2711 if (bytes_avail == 0)
2713 if (var_decl)
2715 /* Constructing into a buffer provided by the flexible array
2716 member of a declared object (which is permitted as a G++
2717 extension). If the array member has been initialized,
2718 determine its size from the initializer. Otherwise,
2719 the array size is zero. */
2720 if (tree init = find_flexarray_init (oper,
2721 DECL_INITIAL (var_decl)))
2722 bytes_avail = wi::to_offset (TYPE_SIZE_UNIT (TREE_TYPE (init)));
2724 else
2725 bytes_avail = (wi::to_offset (TYPE_MAX_VALUE (ptrdiff_type_node))
2726 - compsize);
2729 tree_code oper_code = TREE_CODE (opertype);
2731 if (compref && oper_code == ARRAY_TYPE)
2733 tree nelts = array_type_nelts_top (opertype);
2734 tree nelts_cst = maybe_constant_value (nelts);
2735 if (TREE_CODE (nelts_cst) == INTEGER_CST
2736 && integer_onep (nelts_cst)
2737 && !var_decl
2738 && warn_placement_new < 2)
2739 return;
2742 /* Reduce the size of the buffer by the adjustment computed above
2743 from the offset and/or the index into the array. */
2744 if (bytes_avail < adjust || adjust < 0)
2745 bytes_avail = 0;
2746 else
2748 tree elttype = (TREE_CODE (opertype) == ARRAY_TYPE
2749 ? TREE_TYPE (opertype) : opertype);
2750 if (tree eltsize = TYPE_SIZE_UNIT (elttype))
2752 bytes_avail -= adjust * wi::to_offset (eltsize);
2753 if (bytes_avail < 0)
2754 bytes_avail = 0;
2758 /* The minimum amount of space needed for the allocation. This
2759 is an optimistic estimate that makes it possible to detect
2760 placement new invocation for some undersize buffers but not
2761 others. */
2762 offset_int bytes_need;
2764 if (CONSTANT_CLASS_P (size))
2765 bytes_need = wi::to_offset (size);
2766 else if (nelts && CONSTANT_CLASS_P (nelts))
2767 bytes_need = (wi::to_offset (nelts)
2768 * wi::to_offset (TYPE_SIZE_UNIT (type)));
2769 else if (tree_fits_uhwi_p (TYPE_SIZE_UNIT (type)))
2770 bytes_need = wi::to_offset (TYPE_SIZE_UNIT (type));
2771 else
2773 /* The type is a VLA. */
2774 return;
2777 if (bytes_avail < bytes_need)
2779 if (nelts)
2780 if (CONSTANT_CLASS_P (nelts))
2781 warning_at (loc, OPT_Wplacement_new_,
2782 exact_size ?
2783 "placement new constructing an object of type "
2784 "%<%T [%wu]%> and size %qwu in a region of type %qT "
2785 "and size %qwi"
2786 : "placement new constructing an object of type "
2787 "%<%T [%wu]%> and size %qwu in a region of type %qT "
2788 "and size at most %qwu",
2789 type, tree_to_uhwi (nelts), bytes_need.to_uhwi (),
2790 opertype, bytes_avail.to_uhwi ());
2791 else
2792 warning_at (loc, OPT_Wplacement_new_,
2793 exact_size ?
2794 "placement new constructing an array of objects "
2795 "of type %qT and size %qwu in a region of type %qT "
2796 "and size %qwi"
2797 : "placement new constructing an array of objects "
2798 "of type %qT and size %qwu in a region of type %qT "
2799 "and size at most %qwu",
2800 type, bytes_need.to_uhwi (), opertype,
2801 bytes_avail.to_uhwi ());
2802 else
2803 warning_at (loc, OPT_Wplacement_new_,
2804 exact_size ?
2805 "placement new constructing an object of type %qT "
2806 "and size %qwu in a region of type %qT and size %qwi"
2807 : "placement new constructing an object of type %qT "
2808 "and size %qwu in a region of type %qT and size "
2809 "at most %qwu",
2810 type, bytes_need.to_uhwi (), opertype,
2811 bytes_avail.to_uhwi ());
2816 /* True if alignof(T) > __STDCPP_DEFAULT_NEW_ALIGNMENT__. */
2818 bool
2819 type_has_new_extended_alignment (tree t)
2821 return (aligned_new_threshold
2822 && TYPE_ALIGN_UNIT (t) > (unsigned)aligned_new_threshold);
2825 /* Return the alignment we expect malloc to guarantee. This should just be
2826 MALLOC_ABI_ALIGNMENT, but that macro defaults to only BITS_PER_WORD for some
2827 reason, so don't let the threshold be smaller than max_align_t_align. */
2829 unsigned
2830 malloc_alignment ()
2832 return MAX (max_align_t_align(), MALLOC_ABI_ALIGNMENT);
2835 /* Determine whether an allocation function is a namespace-scope
2836 non-replaceable placement new function. See DR 1748.
2837 TODO: Enable in all standard modes. */
2838 static bool
2839 std_placement_new_fn_p (tree alloc_fn)
2841 if (DECL_NAMESPACE_SCOPE_P (alloc_fn))
2843 tree first_arg = TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (alloc_fn)));
2844 if ((TREE_VALUE (first_arg) == ptr_type_node)
2845 && TREE_CHAIN (first_arg) == void_list_node)
2846 return true;
2848 return false;
2851 /* Generate code for a new-expression, including calling the "operator
2852 new" function, initializing the object, and, if an exception occurs
2853 during construction, cleaning up. The arguments are as for
2854 build_raw_new_expr. This may change PLACEMENT and INIT.
2855 TYPE is the type of the object being constructed, possibly an array
2856 of NELTS elements when NELTS is non-null (in "new T[NELTS]", T may
2857 be an array of the form U[inner], with the whole expression being
2858 "new U[NELTS][inner]"). */
2860 static tree
2861 build_new_1 (vec<tree, va_gc> **placement, tree type, tree nelts,
2862 vec<tree, va_gc> **init, bool globally_qualified_p,
2863 tsubst_flags_t complain)
2865 tree size, rval;
2866 /* True iff this is a call to "operator new[]" instead of just
2867 "operator new". */
2868 bool array_p = false;
2869 /* If ARRAY_P is true, the element type of the array. This is never
2870 an ARRAY_TYPE; for something like "new int[3][4]", the
2871 ELT_TYPE is "int". If ARRAY_P is false, this is the same type as
2872 TYPE. */
2873 tree elt_type;
2874 /* The type of the new-expression. (This type is always a pointer
2875 type.) */
2876 tree pointer_type;
2877 tree non_const_pointer_type;
2878 /* The most significant array bound in int[OUTER_NELTS][inner]. */
2879 tree outer_nelts = NULL_TREE;
2880 /* For arrays with a non-constant number of elements, a bounds checks
2881 on the NELTS parameter to avoid integer overflow at runtime. */
2882 tree outer_nelts_check = NULL_TREE;
2883 bool outer_nelts_from_type = false;
2884 /* Number of the "inner" elements in "new T[OUTER_NELTS][inner]". */
2885 offset_int inner_nelts_count = 1;
2886 tree alloc_call, alloc_expr;
2887 /* Size of the inner array elements (those with constant dimensions). */
2888 offset_int inner_size;
2889 /* The address returned by the call to "operator new". This node is
2890 a VAR_DECL and is therefore reusable. */
2891 tree alloc_node;
2892 tree alloc_fn;
2893 tree cookie_expr, init_expr;
2894 int nothrow, check_new;
2895 /* If non-NULL, the number of extra bytes to allocate at the
2896 beginning of the storage allocated for an array-new expression in
2897 order to store the number of elements. */
2898 tree cookie_size = NULL_TREE;
2899 tree placement_first;
2900 tree placement_expr = NULL_TREE;
2901 /* True if the function we are calling is a placement allocation
2902 function. */
2903 bool placement_allocation_fn_p;
2904 /* True if the storage must be initialized, either by a constructor
2905 or due to an explicit new-initializer. */
2906 bool is_initialized;
2907 /* The address of the thing allocated, not including any cookie. In
2908 particular, if an array cookie is in use, DATA_ADDR is the
2909 address of the first array element. This node is a VAR_DECL, and
2910 is therefore reusable. */
2911 tree data_addr;
2912 tree init_preeval_expr = NULL_TREE;
2913 tree orig_type = type;
2915 if (nelts)
2917 outer_nelts = nelts;
2918 array_p = true;
2920 else if (TREE_CODE (type) == ARRAY_TYPE)
2922 /* Transforms new (T[N]) to new T[N]. The former is a GNU
2923 extension for variable N. (This also covers new T where T is
2924 a VLA typedef.) */
2925 array_p = true;
2926 nelts = array_type_nelts_top (type);
2927 outer_nelts = nelts;
2928 type = TREE_TYPE (type);
2929 outer_nelts_from_type = true;
2932 /* Lots of logic below depends on whether we have a constant number of
2933 elements, so go ahead and fold it now. */
2934 const_tree cst_outer_nelts = fold_non_dependent_expr (outer_nelts, complain);
2936 /* If our base type is an array, then make sure we know how many elements
2937 it has. */
2938 for (elt_type = type;
2939 TREE_CODE (elt_type) == ARRAY_TYPE;
2940 elt_type = TREE_TYPE (elt_type))
2942 tree inner_nelts = array_type_nelts_top (elt_type);
2943 tree inner_nelts_cst = maybe_constant_value (inner_nelts);
2944 if (TREE_CODE (inner_nelts_cst) == INTEGER_CST)
2946 wi::overflow_type overflow;
2947 offset_int result = wi::mul (wi::to_offset (inner_nelts_cst),
2948 inner_nelts_count, SIGNED, &overflow);
2949 if (overflow)
2951 if (complain & tf_error)
2952 error ("integer overflow in array size");
2953 nelts = error_mark_node;
2955 inner_nelts_count = result;
2957 else
2959 if (complain & tf_error)
2961 error_at (cp_expr_loc_or_loc (inner_nelts, input_location),
2962 "array size in new-expression must be constant");
2963 cxx_constant_value(inner_nelts);
2965 nelts = error_mark_node;
2967 if (nelts != error_mark_node)
2968 nelts = cp_build_binary_op (input_location,
2969 MULT_EXPR, nelts,
2970 inner_nelts_cst,
2971 complain);
2974 if (variably_modified_type_p (elt_type, NULL_TREE) && (complain & tf_error))
2976 error ("variably modified type not allowed in new-expression");
2977 return error_mark_node;
2980 if (nelts == error_mark_node)
2981 return error_mark_node;
2983 /* Warn if we performed the (T[N]) to T[N] transformation and N is
2984 variable. */
2985 if (outer_nelts_from_type
2986 && !TREE_CONSTANT (cst_outer_nelts))
2988 if (complain & tf_warning_or_error)
2990 pedwarn (cp_expr_loc_or_loc (outer_nelts, input_location), OPT_Wvla,
2991 typedef_variant_p (orig_type)
2992 ? G_("non-constant array new length must be specified "
2993 "directly, not by typedef")
2994 : G_("non-constant array new length must be specified "
2995 "without parentheses around the type-id"));
2997 else
2998 return error_mark_node;
3001 if (VOID_TYPE_P (elt_type))
3003 if (complain & tf_error)
3004 error ("invalid type %<void%> for new");
3005 return error_mark_node;
3008 if (is_std_init_list (elt_type))
3009 warning (OPT_Winit_list_lifetime,
3010 "%<new%> of initializer_list does not "
3011 "extend the lifetime of the underlying array");
3013 if (abstract_virtuals_error_sfinae (ACU_NEW, elt_type, complain))
3014 return error_mark_node;
3016 is_initialized = (type_build_ctor_call (elt_type) || *init != NULL);
3018 if (*init == NULL && cxx_dialect < cxx11)
3020 bool maybe_uninitialized_error = false;
3021 /* A program that calls for default-initialization [...] of an
3022 entity of reference type is ill-formed. */
3023 if (CLASSTYPE_REF_FIELDS_NEED_INIT (elt_type))
3024 maybe_uninitialized_error = true;
3026 /* A new-expression that creates an object of type T initializes
3027 that object as follows:
3028 - If the new-initializer is omitted:
3029 -- If T is a (possibly cv-qualified) non-POD class type
3030 (or array thereof), the object is default-initialized (8.5).
3031 [...]
3032 -- Otherwise, the object created has indeterminate
3033 value. If T is a const-qualified type, or a (possibly
3034 cv-qualified) POD class type (or array thereof)
3035 containing (directly or indirectly) a member of
3036 const-qualified type, the program is ill-formed; */
3038 if (CLASSTYPE_READONLY_FIELDS_NEED_INIT (elt_type))
3039 maybe_uninitialized_error = true;
3041 if (maybe_uninitialized_error
3042 && diagnose_uninitialized_cst_or_ref_member (elt_type,
3043 /*using_new=*/true,
3044 complain & tf_error))
3045 return error_mark_node;
3048 if (CP_TYPE_CONST_P (elt_type) && *init == NULL
3049 && default_init_uninitialized_part (elt_type))
3051 if (complain & tf_error)
3052 error ("uninitialized const in %<new%> of %q#T", elt_type);
3053 return error_mark_node;
3056 size = size_in_bytes (elt_type);
3057 if (array_p)
3059 /* Maximum available size in bytes. Half of the address space
3060 minus the cookie size. */
3061 offset_int max_size
3062 = wi::set_bit_in_zero <offset_int> (TYPE_PRECISION (sizetype) - 1);
3063 /* Maximum number of outer elements which can be allocated. */
3064 offset_int max_outer_nelts;
3065 tree max_outer_nelts_tree;
3067 gcc_assert (TREE_CODE (size) == INTEGER_CST);
3068 cookie_size = targetm.cxx.get_cookie_size (elt_type);
3069 gcc_assert (TREE_CODE (cookie_size) == INTEGER_CST);
3070 gcc_checking_assert (wi::ltu_p (wi::to_offset (cookie_size), max_size));
3071 /* Unconditionally subtract the cookie size. This decreases the
3072 maximum object size and is safe even if we choose not to use
3073 a cookie after all. */
3074 max_size -= wi::to_offset (cookie_size);
3075 wi::overflow_type overflow;
3076 inner_size = wi::mul (wi::to_offset (size), inner_nelts_count, SIGNED,
3077 &overflow);
3078 if (overflow || wi::gtu_p (inner_size, max_size))
3080 if (complain & tf_error)
3081 error ("size of array is too large");
3082 return error_mark_node;
3085 max_outer_nelts = wi::udiv_trunc (max_size, inner_size);
3086 max_outer_nelts_tree = wide_int_to_tree (sizetype, max_outer_nelts);
3088 size = size_binop (MULT_EXPR, size, fold_convert (sizetype, nelts));
3090 if (TREE_CODE (cst_outer_nelts) == INTEGER_CST)
3092 if (tree_int_cst_lt (max_outer_nelts_tree, cst_outer_nelts))
3094 /* When the array size is constant, check it at compile time
3095 to make sure it doesn't exceed the implementation-defined
3096 maximum, as required by C++ 14 (in C++ 11 this requirement
3097 isn't explicitly stated but it's enforced anyway -- see
3098 grokdeclarator in cp/decl.c). */
3099 if (complain & tf_error)
3100 error ("size of array is too large");
3101 return error_mark_node;
3104 else
3106 /* When a runtime check is necessary because the array size
3107 isn't constant, keep only the top-most seven bits (starting
3108 with the most significant non-zero bit) of the maximum size
3109 to compare the array size against, to simplify encoding the
3110 constant maximum size in the instruction stream. */
3112 unsigned shift = (max_outer_nelts.get_precision ()) - 7
3113 - wi::clz (max_outer_nelts);
3114 max_outer_nelts = (max_outer_nelts >> shift) << shift;
3116 outer_nelts_check = fold_build2 (LE_EXPR, boolean_type_node,
3117 outer_nelts,
3118 max_outer_nelts_tree);
3122 tree align_arg = NULL_TREE;
3123 if (type_has_new_extended_alignment (elt_type))
3124 align_arg = build_int_cst (align_type_node, TYPE_ALIGN_UNIT (elt_type));
3126 alloc_fn = NULL_TREE;
3128 /* If PLACEMENT is a single simple pointer type not passed by
3129 reference, prepare to capture it in a temporary variable. Do
3130 this now, since PLACEMENT will change in the calls below. */
3131 placement_first = NULL_TREE;
3132 if (vec_safe_length (*placement) == 1
3133 && (TYPE_PTR_P (TREE_TYPE ((**placement)[0]))))
3134 placement_first = (**placement)[0];
3136 bool member_new_p = false;
3138 /* Allocate the object. */
3139 tree fnname;
3140 tree fns;
3142 fnname = ovl_op_identifier (false, array_p ? VEC_NEW_EXPR : NEW_EXPR);
3144 member_new_p = !globally_qualified_p
3145 && CLASS_TYPE_P (elt_type)
3146 && (array_p
3147 ? TYPE_HAS_ARRAY_NEW_OPERATOR (elt_type)
3148 : TYPE_HAS_NEW_OPERATOR (elt_type));
3150 if (member_new_p)
3152 /* Use a class-specific operator new. */
3153 /* If a cookie is required, add some extra space. */
3154 if (array_p && TYPE_VEC_NEW_USES_COOKIE (elt_type))
3155 size = size_binop (PLUS_EXPR, size, cookie_size);
3156 else
3158 cookie_size = NULL_TREE;
3159 /* No size arithmetic necessary, so the size check is
3160 not needed. */
3161 if (outer_nelts_check != NULL && inner_size == 1)
3162 outer_nelts_check = NULL_TREE;
3164 /* Perform the overflow check. */
3165 tree errval = TYPE_MAX_VALUE (sizetype);
3166 if (cxx_dialect >= cxx11 && flag_exceptions)
3167 errval = throw_bad_array_new_length ();
3168 if (outer_nelts_check != NULL_TREE)
3169 size = fold_build3 (COND_EXPR, sizetype, outer_nelts_check,
3170 size, errval);
3171 /* Create the argument list. */
3172 vec_safe_insert (*placement, 0, size);
3173 /* Do name-lookup to find the appropriate operator. */
3174 fns = lookup_fnfields (elt_type, fnname, /*protect=*/2);
3175 if (fns == NULL_TREE)
3177 if (complain & tf_error)
3178 error ("no suitable %qD found in class %qT", fnname, elt_type);
3179 return error_mark_node;
3181 if (TREE_CODE (fns) == TREE_LIST)
3183 if (complain & tf_error)
3185 error ("request for member %qD is ambiguous", fnname);
3186 print_candidates (fns);
3188 return error_mark_node;
3190 tree dummy = build_dummy_object (elt_type);
3191 alloc_call = NULL_TREE;
3192 if (align_arg)
3194 vec<tree, va_gc> *align_args
3195 = vec_copy_and_insert (*placement, align_arg, 1);
3196 alloc_call
3197 = build_new_method_call (dummy, fns, &align_args,
3198 /*conversion_path=*/NULL_TREE,
3199 LOOKUP_NORMAL, &alloc_fn, tf_none);
3200 /* If no matching function is found and the allocated object type
3201 has new-extended alignment, the alignment argument is removed
3202 from the argument list, and overload resolution is performed
3203 again. */
3204 if (alloc_call == error_mark_node)
3205 alloc_call = NULL_TREE;
3207 if (!alloc_call)
3208 alloc_call = build_new_method_call (dummy, fns, placement,
3209 /*conversion_path=*/NULL_TREE,
3210 LOOKUP_NORMAL,
3211 &alloc_fn, complain);
3213 else
3215 /* Use a global operator new. */
3216 /* See if a cookie might be required. */
3217 if (!(array_p && TYPE_VEC_NEW_USES_COOKIE (elt_type)))
3219 cookie_size = NULL_TREE;
3220 /* No size arithmetic necessary, so the size check is
3221 not needed. */
3222 if (outer_nelts_check != NULL && inner_size == 1)
3223 outer_nelts_check = NULL_TREE;
3226 alloc_call = build_operator_new_call (fnname, placement,
3227 &size, &cookie_size,
3228 align_arg, outer_nelts_check,
3229 &alloc_fn, complain);
3232 if (alloc_call == error_mark_node)
3233 return error_mark_node;
3235 gcc_assert (alloc_fn != NULL_TREE);
3237 /* Now, check to see if this function is actually a placement
3238 allocation function. This can happen even when PLACEMENT is NULL
3239 because we might have something like:
3241 struct S { void* operator new (size_t, int i = 0); };
3243 A call to `new S' will get this allocation function, even though
3244 there is no explicit placement argument. If there is more than
3245 one argument, or there are variable arguments, then this is a
3246 placement allocation function. */
3247 placement_allocation_fn_p
3248 = (type_num_arguments (TREE_TYPE (alloc_fn)) > 1
3249 || varargs_function_p (alloc_fn));
3251 if (warn_aligned_new
3252 && !placement_allocation_fn_p
3253 && TYPE_ALIGN (elt_type) > malloc_alignment ()
3254 && (warn_aligned_new > 1
3255 || CP_DECL_CONTEXT (alloc_fn) == global_namespace)
3256 && !aligned_allocation_fn_p (alloc_fn))
3258 if (warning (OPT_Waligned_new_, "%<new%> of type %qT with extended "
3259 "alignment %d", elt_type, TYPE_ALIGN_UNIT (elt_type)))
3261 inform (input_location, "uses %qD, which does not have an alignment "
3262 "parameter", alloc_fn);
3263 if (!aligned_new_threshold)
3264 inform (input_location, "use %<-faligned-new%> to enable C++17 "
3265 "over-aligned new support");
3269 /* If we found a simple case of PLACEMENT_EXPR above, then copy it
3270 into a temporary variable. */
3271 if (!processing_template_decl
3272 && TREE_CODE (alloc_call) == CALL_EXPR
3273 && call_expr_nargs (alloc_call) == 2
3274 && TREE_CODE (TREE_TYPE (CALL_EXPR_ARG (alloc_call, 0))) == INTEGER_TYPE
3275 && TYPE_PTR_P (TREE_TYPE (CALL_EXPR_ARG (alloc_call, 1))))
3277 tree placement = CALL_EXPR_ARG (alloc_call, 1);
3279 if (placement_first != NULL_TREE
3280 && (INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (TREE_TYPE (placement)))
3281 || VOID_TYPE_P (TREE_TYPE (TREE_TYPE (placement)))))
3283 placement_expr = get_target_expr (placement_first);
3284 CALL_EXPR_ARG (alloc_call, 1)
3285 = fold_convert (TREE_TYPE (placement), placement_expr);
3288 if (!member_new_p
3289 && VOID_TYPE_P (TREE_TYPE (TREE_TYPE (CALL_EXPR_ARG (alloc_call, 1)))))
3291 /* Attempt to make the warning point at the operator new argument. */
3292 if (placement_first)
3293 placement = placement_first;
3295 warn_placement_new_too_small (orig_type, nelts, size, placement);
3299 /* In the simple case, we can stop now. */
3300 pointer_type = build_pointer_type (type);
3301 if (!cookie_size && !is_initialized)
3302 return build_nop (pointer_type, alloc_call);
3304 /* Store the result of the allocation call in a variable so that we can
3305 use it more than once. */
3306 alloc_expr = get_target_expr (alloc_call);
3307 alloc_node = TARGET_EXPR_SLOT (alloc_expr);
3309 /* Strip any COMPOUND_EXPRs from ALLOC_CALL. */
3310 while (TREE_CODE (alloc_call) == COMPOUND_EXPR)
3311 alloc_call = TREE_OPERAND (alloc_call, 1);
3313 /* Preevaluate the placement args so that we don't reevaluate them for a
3314 placement delete. */
3315 if (placement_allocation_fn_p)
3317 tree inits;
3318 stabilize_call (alloc_call, &inits);
3319 if (inits)
3320 alloc_expr = build2 (COMPOUND_EXPR, TREE_TYPE (alloc_expr), inits,
3321 alloc_expr);
3324 /* unless an allocation function is declared with an empty excep-
3325 tion-specification (_except.spec_), throw(), it indicates failure to
3326 allocate storage by throwing a bad_alloc exception (clause _except_,
3327 _lib.bad.alloc_); it returns a non-null pointer otherwise If the allo-
3328 cation function is declared with an empty exception-specification,
3329 throw(), it returns null to indicate failure to allocate storage and a
3330 non-null pointer otherwise.
3332 So check for a null exception spec on the op new we just called. */
3334 nothrow = TYPE_NOTHROW_P (TREE_TYPE (alloc_fn));
3335 check_new
3336 = flag_check_new || (nothrow && !std_placement_new_fn_p (alloc_fn));
3338 if (cookie_size)
3340 tree cookie;
3341 tree cookie_ptr;
3342 tree size_ptr_type;
3344 /* Adjust so we're pointing to the start of the object. */
3345 data_addr = fold_build_pointer_plus (alloc_node, cookie_size);
3347 /* Store the number of bytes allocated so that we can know how
3348 many elements to destroy later. We use the last sizeof
3349 (size_t) bytes to store the number of elements. */
3350 cookie_ptr = size_binop (MINUS_EXPR, cookie_size, size_in_bytes (sizetype));
3351 cookie_ptr = fold_build_pointer_plus_loc (input_location,
3352 alloc_node, cookie_ptr);
3353 size_ptr_type = build_pointer_type (sizetype);
3354 cookie_ptr = fold_convert (size_ptr_type, cookie_ptr);
3355 cookie = cp_build_fold_indirect_ref (cookie_ptr);
3357 cookie_expr = build2 (MODIFY_EXPR, sizetype, cookie, nelts);
3359 if (targetm.cxx.cookie_has_size ())
3361 /* Also store the element size. */
3362 cookie_ptr = fold_build_pointer_plus (cookie_ptr,
3363 fold_build1_loc (input_location,
3364 NEGATE_EXPR, sizetype,
3365 size_in_bytes (sizetype)));
3367 cookie = cp_build_fold_indirect_ref (cookie_ptr);
3368 cookie = build2 (MODIFY_EXPR, sizetype, cookie,
3369 size_in_bytes (elt_type));
3370 cookie_expr = build2 (COMPOUND_EXPR, TREE_TYPE (cookie_expr),
3371 cookie, cookie_expr);
3374 else
3376 cookie_expr = NULL_TREE;
3377 data_addr = alloc_node;
3380 /* Now use a pointer to the type we've actually allocated. */
3382 /* But we want to operate on a non-const version to start with,
3383 since we'll be modifying the elements. */
3384 non_const_pointer_type = build_pointer_type
3385 (cp_build_qualified_type (type, cp_type_quals (type) & ~TYPE_QUAL_CONST));
3387 data_addr = fold_convert (non_const_pointer_type, data_addr);
3388 /* Any further uses of alloc_node will want this type, too. */
3389 alloc_node = fold_convert (non_const_pointer_type, alloc_node);
3391 /* Now initialize the allocated object. Note that we preevaluate the
3392 initialization expression, apart from the actual constructor call or
3393 assignment--we do this because we want to delay the allocation as long
3394 as possible in order to minimize the size of the exception region for
3395 placement delete. */
3396 if (is_initialized)
3398 bool stable;
3399 bool explicit_value_init_p = false;
3401 if (*init != NULL && (*init)->is_empty ())
3403 *init = NULL;
3404 explicit_value_init_p = true;
3407 if (processing_template_decl && explicit_value_init_p)
3409 /* build_value_init doesn't work in templates, and we don't need
3410 the initializer anyway since we're going to throw it away and
3411 rebuild it at instantiation time, so just build up a single
3412 constructor call to get any appropriate diagnostics. */
3413 init_expr = cp_build_fold_indirect_ref (data_addr);
3414 if (type_build_ctor_call (elt_type))
3415 init_expr = build_special_member_call (init_expr,
3416 complete_ctor_identifier,
3417 init, elt_type,
3418 LOOKUP_NORMAL,
3419 complain);
3420 stable = stabilize_init (init_expr, &init_preeval_expr);
3422 else if (array_p)
3424 tree vecinit = NULL_TREE;
3425 if (vec_safe_length (*init) == 1
3426 && DIRECT_LIST_INIT_P ((**init)[0]))
3428 vecinit = (**init)[0];
3429 if (CONSTRUCTOR_NELTS (vecinit) == 0)
3430 /* List-value-initialization, leave it alone. */;
3431 else
3433 tree arraytype, domain;
3434 if (TREE_CONSTANT (nelts))
3435 domain = compute_array_index_type (NULL_TREE, nelts,
3436 complain);
3437 else
3438 /* We'll check the length at runtime. */
3439 domain = NULL_TREE;
3440 arraytype = build_cplus_array_type (type, domain);
3441 vecinit = digest_init (arraytype, vecinit, complain);
3444 else if (*init)
3446 if (complain & tf_error)
3447 error ("parenthesized initializer in array new");
3448 return error_mark_node;
3450 init_expr
3451 = build_vec_init (data_addr,
3452 cp_build_binary_op (input_location,
3453 MINUS_EXPR, outer_nelts,
3454 integer_one_node,
3455 complain),
3456 vecinit,
3457 explicit_value_init_p,
3458 /*from_array=*/0,
3459 complain);
3461 /* An array initialization is stable because the initialization
3462 of each element is a full-expression, so the temporaries don't
3463 leak out. */
3464 stable = true;
3466 else
3468 init_expr = cp_build_fold_indirect_ref (data_addr);
3470 if (type_build_ctor_call (type) && !explicit_value_init_p)
3472 init_expr = build_special_member_call (init_expr,
3473 complete_ctor_identifier,
3474 init, elt_type,
3475 LOOKUP_NORMAL,
3476 complain);
3478 else if (explicit_value_init_p)
3480 /* Something like `new int()'. NO_CLEANUP is needed so
3481 we don't try and build a (possibly ill-formed)
3482 destructor. */
3483 tree val = build_value_init (type, complain | tf_no_cleanup);
3484 if (val == error_mark_node)
3485 return error_mark_node;
3486 init_expr = build2 (INIT_EXPR, type, init_expr, val);
3488 else
3490 tree ie;
3492 /* We are processing something like `new int (10)', which
3493 means allocate an int, and initialize it with 10. */
3495 ie = build_x_compound_expr_from_vec (*init, "new initializer",
3496 complain);
3497 init_expr = cp_build_modify_expr (input_location, init_expr,
3498 INIT_EXPR, ie, complain);
3500 /* If the initializer uses C++14 aggregate NSDMI that refer to the
3501 object being initialized, replace them now and don't try to
3502 preevaluate. */
3503 bool had_placeholder = false;
3504 if (!processing_template_decl
3505 && TREE_CODE (init_expr) == INIT_EXPR)
3506 TREE_OPERAND (init_expr, 1)
3507 = replace_placeholders (TREE_OPERAND (init_expr, 1),
3508 TREE_OPERAND (init_expr, 0),
3509 &had_placeholder);
3510 stable = (!had_placeholder
3511 && stabilize_init (init_expr, &init_preeval_expr));
3514 if (init_expr == error_mark_node)
3515 return error_mark_node;
3517 /* If any part of the object initialization terminates by throwing an
3518 exception and a suitable deallocation function can be found, the
3519 deallocation function is called to free the memory in which the
3520 object was being constructed, after which the exception continues
3521 to propagate in the context of the new-expression. If no
3522 unambiguous matching deallocation function can be found,
3523 propagating the exception does not cause the object's memory to be
3524 freed. */
3525 if (flag_exceptions)
3527 enum tree_code dcode = array_p ? VEC_DELETE_EXPR : DELETE_EXPR;
3528 tree cleanup;
3530 /* The Standard is unclear here, but the right thing to do
3531 is to use the same method for finding deallocation
3532 functions that we use for finding allocation functions. */
3533 cleanup = (build_op_delete_call
3534 (dcode,
3535 alloc_node,
3536 size,
3537 globally_qualified_p,
3538 placement_allocation_fn_p ? alloc_call : NULL_TREE,
3539 alloc_fn,
3540 complain));
3542 if (!cleanup)
3543 /* We're done. */;
3544 else if (stable)
3545 /* This is much simpler if we were able to preevaluate all of
3546 the arguments to the constructor call. */
3548 /* CLEANUP is compiler-generated, so no diagnostics. */
3549 TREE_NO_WARNING (cleanup) = true;
3550 init_expr = build2 (TRY_CATCH_EXPR, void_type_node,
3551 init_expr, cleanup);
3552 /* Likewise, this try-catch is compiler-generated. */
3553 TREE_NO_WARNING (init_expr) = true;
3555 else
3556 /* Ack! First we allocate the memory. Then we set our sentry
3557 variable to true, and expand a cleanup that deletes the
3558 memory if sentry is true. Then we run the constructor, and
3559 finally clear the sentry.
3561 We need to do this because we allocate the space first, so
3562 if there are any temporaries with cleanups in the
3563 constructor args and we weren't able to preevaluate them, we
3564 need this EH region to extend until end of full-expression
3565 to preserve nesting. */
3567 tree end, sentry, begin;
3569 begin = get_target_expr (boolean_true_node);
3570 CLEANUP_EH_ONLY (begin) = 1;
3572 sentry = TARGET_EXPR_SLOT (begin);
3574 /* CLEANUP is compiler-generated, so no diagnostics. */
3575 TREE_NO_WARNING (cleanup) = true;
3577 TARGET_EXPR_CLEANUP (begin)
3578 = build3 (COND_EXPR, void_type_node, sentry,
3579 cleanup, void_node);
3581 end = build2 (MODIFY_EXPR, TREE_TYPE (sentry),
3582 sentry, boolean_false_node);
3584 init_expr
3585 = build2 (COMPOUND_EXPR, void_type_node, begin,
3586 build2 (COMPOUND_EXPR, void_type_node, init_expr,
3587 end));
3588 /* Likewise, this is compiler-generated. */
3589 TREE_NO_WARNING (init_expr) = true;
3593 else
3594 init_expr = NULL_TREE;
3596 /* Now build up the return value in reverse order. */
3598 rval = data_addr;
3600 if (init_expr)
3601 rval = build2 (COMPOUND_EXPR, TREE_TYPE (rval), init_expr, rval);
3602 if (cookie_expr)
3603 rval = build2 (COMPOUND_EXPR, TREE_TYPE (rval), cookie_expr, rval);
3605 if (rval == data_addr)
3606 /* If we don't have an initializer or a cookie, strip the TARGET_EXPR
3607 and return the call (which doesn't need to be adjusted). */
3608 rval = TARGET_EXPR_INITIAL (alloc_expr);
3609 else
3611 if (check_new)
3613 tree ifexp = cp_build_binary_op (input_location,
3614 NE_EXPR, alloc_node,
3615 nullptr_node,
3616 complain);
3617 rval = build_conditional_expr (input_location, ifexp, rval,
3618 alloc_node, complain);
3621 /* Perform the allocation before anything else, so that ALLOC_NODE
3622 has been initialized before we start using it. */
3623 rval = build2 (COMPOUND_EXPR, TREE_TYPE (rval), alloc_expr, rval);
3626 if (init_preeval_expr)
3627 rval = build2 (COMPOUND_EXPR, TREE_TYPE (rval), init_preeval_expr, rval);
3629 /* A new-expression is never an lvalue. */
3630 gcc_assert (!obvalue_p (rval));
3632 return convert (pointer_type, rval);
3635 /* Generate a representation for a C++ "new" expression. *PLACEMENT
3636 is a vector of placement-new arguments (or NULL if none). If NELTS
3637 is NULL, TYPE is the type of the storage to be allocated. If NELTS
3638 is not NULL, then this is an array-new allocation; TYPE is the type
3639 of the elements in the array and NELTS is the number of elements in
3640 the array. *INIT, if non-NULL, is the initializer for the new
3641 object, or an empty vector to indicate an initializer of "()". If
3642 USE_GLOBAL_NEW is true, then the user explicitly wrote "::new"
3643 rather than just "new". This may change PLACEMENT and INIT. */
3645 tree
3646 build_new (vec<tree, va_gc> **placement, tree type, tree nelts,
3647 vec<tree, va_gc> **init, int use_global_new, tsubst_flags_t complain)
3649 tree rval;
3650 vec<tree, va_gc> *orig_placement = NULL;
3651 tree orig_nelts = NULL_TREE;
3652 vec<tree, va_gc> *orig_init = NULL;
3654 if (type == error_mark_node)
3655 return error_mark_node;
3657 if (nelts == NULL_TREE
3658 /* Don't do auto deduction where it might affect mangling. */
3659 && (!processing_template_decl || at_function_scope_p ()))
3661 tree auto_node = type_uses_auto (type);
3662 if (auto_node)
3664 tree d_init = NULL_TREE;
3665 const size_t len = vec_safe_length (*init);
3666 /* E.g. new auto(x) must have exactly one element, or
3667 a {} initializer will have one element. */
3668 if (len == 1)
3670 d_init = (**init)[0];
3671 d_init = resolve_nondeduced_context (d_init, complain);
3673 /* For the rest, e.g. new A(1, 2, 3), create a list. */
3674 else if (len > 1)
3676 unsigned int n;
3677 tree t;
3678 tree *pp = &d_init;
3679 FOR_EACH_VEC_ELT (**init, n, t)
3681 t = resolve_nondeduced_context (t, complain);
3682 *pp = build_tree_list (NULL_TREE, t);
3683 pp = &TREE_CHAIN (*pp);
3686 type = do_auto_deduction (type, d_init, auto_node, complain);
3690 if (processing_template_decl)
3692 if (dependent_type_p (type)
3693 || any_type_dependent_arguments_p (*placement)
3694 || (nelts && type_dependent_expression_p (nelts))
3695 || (nelts && *init)
3696 || any_type_dependent_arguments_p (*init))
3697 return build_raw_new_expr (*placement, type, nelts, *init,
3698 use_global_new);
3700 orig_placement = make_tree_vector_copy (*placement);
3701 orig_nelts = nelts;
3702 if (*init)
3704 orig_init = make_tree_vector_copy (*init);
3705 /* Also copy any CONSTRUCTORs in *init, since reshape_init and
3706 digest_init clobber them in place. */
3707 for (unsigned i = 0; i < orig_init->length(); ++i)
3709 tree e = (**init)[i];
3710 if (TREE_CODE (e) == CONSTRUCTOR)
3711 (**init)[i] = copy_node (e);
3715 make_args_non_dependent (*placement);
3716 if (nelts)
3717 nelts = build_non_dependent_expr (nelts);
3718 make_args_non_dependent (*init);
3721 if (nelts)
3723 if (!build_expr_type_conversion (WANT_INT | WANT_ENUM, nelts, false))
3725 if (complain & tf_error)
3726 permerror (input_location, "size in array new must have integral type");
3727 else
3728 return error_mark_node;
3731 /* Try to determine the constant value only for the purposes
3732 of the diagnostic below but continue to use the original
3733 value and handle const folding later. */
3734 const_tree cst_nelts = fold_non_dependent_expr (nelts, complain);
3736 /* The expression in a noptr-new-declarator is erroneous if it's of
3737 non-class type and its value before converting to std::size_t is
3738 less than zero. ... If the expression is a constant expression,
3739 the program is ill-fomed. */
3740 if (TREE_CODE (cst_nelts) == INTEGER_CST
3741 && tree_int_cst_sgn (cst_nelts) == -1)
3743 if (complain & tf_error)
3744 error ("size of array is negative");
3745 return error_mark_node;
3748 nelts = mark_rvalue_use (nelts);
3749 nelts = cp_save_expr (cp_convert (sizetype, nelts, complain));
3752 /* ``A reference cannot be created by the new operator. A reference
3753 is not an object (8.2.2, 8.4.3), so a pointer to it could not be
3754 returned by new.'' ARM 5.3.3 */
3755 if (TYPE_REF_P (type))
3757 if (complain & tf_error)
3758 error ("new cannot be applied to a reference type");
3759 else
3760 return error_mark_node;
3761 type = TREE_TYPE (type);
3764 if (TREE_CODE (type) == FUNCTION_TYPE)
3766 if (complain & tf_error)
3767 error ("new cannot be applied to a function type");
3768 return error_mark_node;
3771 /* The type allocated must be complete. If the new-type-id was
3772 "T[N]" then we are just checking that "T" is complete here, but
3773 that is equivalent, since the value of "N" doesn't matter. */
3774 if (!complete_type_or_maybe_complain (type, NULL_TREE, complain))
3775 return error_mark_node;
3777 rval = build_new_1 (placement, type, nelts, init, use_global_new, complain);
3778 if (rval == error_mark_node)
3779 return error_mark_node;
3781 if (processing_template_decl)
3783 tree ret = build_raw_new_expr (orig_placement, type, orig_nelts,
3784 orig_init, use_global_new);
3785 release_tree_vector (orig_placement);
3786 release_tree_vector (orig_init);
3787 return ret;
3790 /* Wrap it in a NOP_EXPR so warn_if_unused_value doesn't complain. */
3791 rval = build1 (NOP_EXPR, TREE_TYPE (rval), rval);
3792 TREE_NO_WARNING (rval) = 1;
3794 return rval;
3797 static tree
3798 build_vec_delete_1 (tree base, tree maxindex, tree type,
3799 special_function_kind auto_delete_vec,
3800 int use_global_delete, tsubst_flags_t complain)
3802 tree virtual_size;
3803 tree ptype = build_pointer_type (type = complete_type (type));
3804 tree size_exp;
3806 /* Temporary variables used by the loop. */
3807 tree tbase, tbase_init;
3809 /* This is the body of the loop that implements the deletion of a
3810 single element, and moves temp variables to next elements. */
3811 tree body;
3813 /* This is the LOOP_EXPR that governs the deletion of the elements. */
3814 tree loop = 0;
3816 /* This is the thing that governs what to do after the loop has run. */
3817 tree deallocate_expr = 0;
3819 /* This is the BIND_EXPR which holds the outermost iterator of the
3820 loop. It is convenient to set this variable up and test it before
3821 executing any other code in the loop.
3822 This is also the containing expression returned by this function. */
3823 tree controller = NULL_TREE;
3824 tree tmp;
3826 /* We should only have 1-D arrays here. */
3827 gcc_assert (TREE_CODE (type) != ARRAY_TYPE);
3829 if (base == error_mark_node || maxindex == error_mark_node)
3830 return error_mark_node;
3832 if (!COMPLETE_TYPE_P (type))
3834 if ((complain & tf_warning)
3835 && warning (OPT_Wdelete_incomplete,
3836 "possible problem detected in invocation of "
3837 "delete [] operator:"))
3839 cxx_incomplete_type_diagnostic (base, type, DK_WARNING);
3840 inform (input_location, "neither the destructor nor the "
3841 "class-specific operator delete [] will be called, "
3842 "even if they are declared when the class is defined");
3844 /* This size won't actually be used. */
3845 size_exp = size_one_node;
3846 goto no_destructor;
3849 size_exp = size_in_bytes (type);
3851 if (! MAYBE_CLASS_TYPE_P (type))
3852 goto no_destructor;
3853 else if (TYPE_HAS_TRIVIAL_DESTRUCTOR (type))
3855 /* Make sure the destructor is callable. */
3856 if (type_build_dtor_call (type))
3858 tmp = build_delete (ptype, base, sfk_complete_destructor,
3859 LOOKUP_NORMAL|LOOKUP_DESTRUCTOR, 1,
3860 complain);
3861 if (tmp == error_mark_node)
3862 return error_mark_node;
3864 goto no_destructor;
3867 /* The below is short by the cookie size. */
3868 virtual_size = size_binop (MULT_EXPR, size_exp,
3869 fold_convert (sizetype, maxindex));
3871 tbase = create_temporary_var (ptype);
3872 tbase_init
3873 = cp_build_modify_expr (input_location, tbase, NOP_EXPR,
3874 fold_build_pointer_plus_loc (input_location,
3875 fold_convert (ptype,
3876 base),
3877 virtual_size),
3878 complain);
3879 if (tbase_init == error_mark_node)
3880 return error_mark_node;
3881 controller = build3 (BIND_EXPR, void_type_node, tbase,
3882 NULL_TREE, NULL_TREE);
3883 TREE_SIDE_EFFECTS (controller) = 1;
3885 body = build1 (EXIT_EXPR, void_type_node,
3886 build2 (EQ_EXPR, boolean_type_node, tbase,
3887 fold_convert (ptype, base)));
3888 tmp = fold_build1_loc (input_location, NEGATE_EXPR, sizetype, size_exp);
3889 tmp = fold_build_pointer_plus (tbase, tmp);
3890 tmp = cp_build_modify_expr (input_location, tbase, NOP_EXPR, tmp, complain);
3891 if (tmp == error_mark_node)
3892 return error_mark_node;
3893 body = build_compound_expr (input_location, body, tmp);
3894 tmp = build_delete (ptype, tbase, sfk_complete_destructor,
3895 LOOKUP_NORMAL|LOOKUP_DESTRUCTOR, 1,
3896 complain);
3897 if (tmp == error_mark_node)
3898 return error_mark_node;
3899 body = build_compound_expr (input_location, body, tmp);
3901 loop = build1 (LOOP_EXPR, void_type_node, body);
3902 loop = build_compound_expr (input_location, tbase_init, loop);
3904 no_destructor:
3905 /* Delete the storage if appropriate. */
3906 if (auto_delete_vec == sfk_deleting_destructor)
3908 tree base_tbd;
3910 /* The below is short by the cookie size. */
3911 virtual_size = size_binop (MULT_EXPR, size_exp,
3912 fold_convert (sizetype, maxindex));
3914 if (! TYPE_VEC_NEW_USES_COOKIE (type))
3915 /* no header */
3916 base_tbd = base;
3917 else
3919 tree cookie_size;
3921 cookie_size = targetm.cxx.get_cookie_size (type);
3922 base_tbd = cp_build_binary_op (input_location,
3923 MINUS_EXPR,
3924 cp_convert (string_type_node,
3925 base, complain),
3926 cookie_size,
3927 complain);
3928 if (base_tbd == error_mark_node)
3929 return error_mark_node;
3930 base_tbd = cp_convert (ptype, base_tbd, complain);
3931 /* True size with header. */
3932 virtual_size = size_binop (PLUS_EXPR, virtual_size, cookie_size);
3935 deallocate_expr = build_op_delete_call (VEC_DELETE_EXPR,
3936 base_tbd, virtual_size,
3937 use_global_delete & 1,
3938 /*placement=*/NULL_TREE,
3939 /*alloc_fn=*/NULL_TREE,
3940 complain);
3943 body = loop;
3944 if (!deallocate_expr)
3946 else if (!body)
3947 body = deallocate_expr;
3948 else
3949 /* The delete operator mist be called, even if a destructor
3950 throws. */
3951 body = build2 (TRY_FINALLY_EXPR, void_type_node, body, deallocate_expr);
3953 if (!body)
3954 body = integer_zero_node;
3956 /* Outermost wrapper: If pointer is null, punt. */
3957 tree cond = build2_loc (input_location, NE_EXPR, boolean_type_node, base,
3958 fold_convert (TREE_TYPE (base), nullptr_node));
3959 /* This is a compiler generated comparison, don't emit
3960 e.g. -Wnonnull-compare warning for it. */
3961 TREE_NO_WARNING (cond) = 1;
3962 body = build3_loc (input_location, COND_EXPR, void_type_node,
3963 cond, body, integer_zero_node);
3964 COND_EXPR_IS_VEC_DELETE (body) = true;
3965 body = build1 (NOP_EXPR, void_type_node, body);
3967 if (controller)
3969 TREE_OPERAND (controller, 1) = body;
3970 body = controller;
3973 if (TREE_CODE (base) == SAVE_EXPR)
3974 /* Pre-evaluate the SAVE_EXPR outside of the BIND_EXPR. */
3975 body = build2 (COMPOUND_EXPR, void_type_node, base, body);
3977 return convert_to_void (body, ICV_CAST, complain);
3980 /* Create an unnamed variable of the indicated TYPE. */
3982 tree
3983 create_temporary_var (tree type)
3985 tree decl;
3987 decl = build_decl (input_location,
3988 VAR_DECL, NULL_TREE, type);
3989 TREE_USED (decl) = 1;
3990 DECL_ARTIFICIAL (decl) = 1;
3991 DECL_IGNORED_P (decl) = 1;
3992 DECL_CONTEXT (decl) = current_function_decl;
3994 return decl;
3997 /* Create a new temporary variable of the indicated TYPE, initialized
3998 to INIT.
4000 It is not entered into current_binding_level, because that breaks
4001 things when it comes time to do final cleanups (which take place
4002 "outside" the binding contour of the function). */
4004 tree
4005 get_temp_regvar (tree type, tree init)
4007 tree decl;
4009 decl = create_temporary_var (type);
4010 add_decl_expr (decl);
4012 finish_expr_stmt (cp_build_modify_expr (input_location, decl, INIT_EXPR,
4013 init, tf_warning_or_error));
4015 return decl;
4018 /* Subroutine of build_vec_init. Returns true if assigning to an array of
4019 INNER_ELT_TYPE from INIT is trivial. */
4021 static bool
4022 vec_copy_assign_is_trivial (tree inner_elt_type, tree init)
4024 tree fromtype = inner_elt_type;
4025 if (lvalue_p (init))
4026 fromtype = cp_build_reference_type (fromtype, /*rval*/false);
4027 return is_trivially_xible (MODIFY_EXPR, inner_elt_type, fromtype);
4030 /* Subroutine of build_vec_init: Check that the array has at least N
4031 elements. Other parameters are local variables in build_vec_init. */
4033 void
4034 finish_length_check (tree atype, tree iterator, tree obase, unsigned n)
4036 tree nelts = build_int_cst (ptrdiff_type_node, n - 1);
4037 if (TREE_CODE (atype) != ARRAY_TYPE)
4039 if (flag_exceptions)
4041 tree c = fold_build2 (LT_EXPR, boolean_type_node, iterator,
4042 nelts);
4043 c = build3 (COND_EXPR, void_type_node, c,
4044 throw_bad_array_new_length (), void_node);
4045 finish_expr_stmt (c);
4047 /* Don't check an array new when -fno-exceptions. */
4049 else if (sanitize_flags_p (SANITIZE_BOUNDS)
4050 && current_function_decl != NULL_TREE)
4052 /* Make sure the last element of the initializer is in bounds. */
4053 finish_expr_stmt
4054 (ubsan_instrument_bounds
4055 (input_location, obase, &nelts, /*ignore_off_by_one*/false));
4059 /* `build_vec_init' returns tree structure that performs
4060 initialization of a vector of aggregate types.
4062 BASE is a reference to the vector, of ARRAY_TYPE, or a pointer
4063 to the first element, of POINTER_TYPE.
4064 MAXINDEX is the maximum index of the array (one less than the
4065 number of elements). It is only used if BASE is a pointer or
4066 TYPE_DOMAIN (TREE_TYPE (BASE)) == NULL_TREE.
4068 INIT is the (possibly NULL) initializer.
4070 If EXPLICIT_VALUE_INIT_P is true, then INIT must be NULL. All
4071 elements in the array are value-initialized.
4073 FROM_ARRAY is 0 if we should init everything with INIT
4074 (i.e., every element initialized from INIT).
4075 FROM_ARRAY is 1 if we should index into INIT in parallel
4076 with initialization of DECL.
4077 FROM_ARRAY is 2 if we should index into INIT in parallel,
4078 but use assignment instead of initialization. */
4080 tree
4081 build_vec_init (tree base, tree maxindex, tree init,
4082 bool explicit_value_init_p,
4083 int from_array, tsubst_flags_t complain)
4085 tree rval;
4086 tree base2 = NULL_TREE;
4087 tree itype = NULL_TREE;
4088 tree iterator;
4089 /* The type of BASE. */
4090 tree atype = TREE_TYPE (base);
4091 /* The type of an element in the array. */
4092 tree type = TREE_TYPE (atype);
4093 /* The element type reached after removing all outer array
4094 types. */
4095 tree inner_elt_type;
4096 /* The type of a pointer to an element in the array. */
4097 tree ptype;
4098 tree stmt_expr;
4099 tree compound_stmt;
4100 int destroy_temps;
4101 tree try_block = NULL_TREE;
4102 int num_initialized_elts = 0;
4103 bool is_global;
4104 tree obase = base;
4105 bool xvalue = false;
4106 bool errors = false;
4107 location_t loc = (init ? cp_expr_loc_or_loc (init, input_location)
4108 : location_of (base));
4110 if (TREE_CODE (atype) == ARRAY_TYPE && TYPE_DOMAIN (atype))
4111 maxindex = array_type_nelts (atype);
4113 if (maxindex == NULL_TREE || maxindex == error_mark_node)
4114 return error_mark_node;
4116 maxindex = maybe_constant_value (maxindex);
4117 if (explicit_value_init_p)
4118 gcc_assert (!init);
4120 inner_elt_type = strip_array_types (type);
4122 /* Look through the TARGET_EXPR around a compound literal. */
4123 if (init && TREE_CODE (init) == TARGET_EXPR
4124 && TREE_CODE (TARGET_EXPR_INITIAL (init)) == CONSTRUCTOR
4125 && from_array != 2)
4126 init = TARGET_EXPR_INITIAL (init);
4128 bool direct_init = false;
4129 if (from_array && init && BRACE_ENCLOSED_INITIALIZER_P (init)
4130 && CONSTRUCTOR_NELTS (init) == 1)
4132 tree elt = CONSTRUCTOR_ELT (init, 0)->value;
4133 if (TREE_CODE (TREE_TYPE (elt)) == ARRAY_TYPE)
4135 direct_init = DIRECT_LIST_INIT_P (init);
4136 init = elt;
4140 /* If we have a braced-init-list or string constant, make sure that the array
4141 is big enough for all the initializers. */
4142 bool length_check = (init
4143 && (TREE_CODE (init) == STRING_CST
4144 || (TREE_CODE (init) == CONSTRUCTOR
4145 && CONSTRUCTOR_NELTS (init) > 0))
4146 && !TREE_CONSTANT (maxindex));
4148 if (init
4149 && TREE_CODE (atype) == ARRAY_TYPE
4150 && TREE_CONSTANT (maxindex)
4151 && (from_array == 2
4152 ? vec_copy_assign_is_trivial (inner_elt_type, init)
4153 : !TYPE_NEEDS_CONSTRUCTING (type))
4154 && ((TREE_CODE (init) == CONSTRUCTOR
4155 && (BRACE_ENCLOSED_INITIALIZER_P (init)
4156 || (same_type_ignoring_top_level_qualifiers_p
4157 (atype, TREE_TYPE (init))))
4158 /* Don't do this if the CONSTRUCTOR might contain something
4159 that might throw and require us to clean up. */
4160 && (vec_safe_is_empty (CONSTRUCTOR_ELTS (init))
4161 || ! TYPE_HAS_NONTRIVIAL_DESTRUCTOR (inner_elt_type)))
4162 || from_array))
4164 /* Do non-default initialization of trivial arrays resulting from
4165 brace-enclosed initializers. In this case, digest_init and
4166 store_constructor will handle the semantics for us. */
4168 if (BRACE_ENCLOSED_INITIALIZER_P (init))
4169 init = digest_init (atype, init, complain);
4170 stmt_expr = build2 (INIT_EXPR, atype, base, init);
4171 return stmt_expr;
4174 maxindex = cp_convert (ptrdiff_type_node, maxindex, complain);
4175 maxindex = fold_simple (maxindex);
4177 if (TREE_CODE (atype) == ARRAY_TYPE)
4179 ptype = build_pointer_type (type);
4180 base = decay_conversion (base, complain);
4181 if (base == error_mark_node)
4182 return error_mark_node;
4183 base = cp_convert (ptype, base, complain);
4185 else
4186 ptype = atype;
4188 /* The code we are generating looks like:
4190 T* t1 = (T*) base;
4191 T* rval = t1;
4192 ptrdiff_t iterator = maxindex;
4193 try {
4194 for (; iterator != -1; --iterator) {
4195 ... initialize *t1 ...
4196 ++t1;
4198 } catch (...) {
4199 ... destroy elements that were constructed ...
4201 rval;
4204 We can omit the try and catch blocks if we know that the
4205 initialization will never throw an exception, or if the array
4206 elements do not have destructors. We can omit the loop completely if
4207 the elements of the array do not have constructors.
4209 We actually wrap the entire body of the above in a STMT_EXPR, for
4210 tidiness.
4212 When copying from array to another, when the array elements have
4213 only trivial copy constructors, we should use __builtin_memcpy
4214 rather than generating a loop. That way, we could take advantage
4215 of whatever cleverness the back end has for dealing with copies
4216 of blocks of memory. */
4218 is_global = begin_init_stmts (&stmt_expr, &compound_stmt);
4219 destroy_temps = stmts_are_full_exprs_p ();
4220 current_stmt_tree ()->stmts_are_full_exprs_p = 0;
4221 rval = get_temp_regvar (ptype, base);
4222 base = get_temp_regvar (ptype, rval);
4223 iterator = get_temp_regvar (ptrdiff_type_node, maxindex);
4225 /* If initializing one array from another, initialize element by
4226 element. We rely upon the below calls to do the argument
4227 checking. Evaluate the initializer before entering the try block. */
4228 if (from_array && init && TREE_CODE (init) != CONSTRUCTOR)
4230 if (lvalue_kind (init) & clk_rvalueref)
4231 xvalue = true;
4232 base2 = decay_conversion (init, complain);
4233 if (base2 == error_mark_node)
4234 return error_mark_node;
4235 itype = TREE_TYPE (base2);
4236 base2 = get_temp_regvar (itype, base2);
4237 itype = TREE_TYPE (itype);
4240 /* Protect the entire array initialization so that we can destroy
4241 the partially constructed array if an exception is thrown.
4242 But don't do this if we're assigning. */
4243 if (flag_exceptions && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
4244 && from_array != 2)
4246 try_block = begin_try_block ();
4249 /* Should we try to create a constant initializer? */
4250 bool try_const = (TREE_CODE (atype) == ARRAY_TYPE
4251 && TREE_CONSTANT (maxindex)
4252 && (init ? TREE_CODE (init) == CONSTRUCTOR
4253 : (type_has_constexpr_default_constructor
4254 (inner_elt_type)))
4255 && (literal_type_p (inner_elt_type)
4256 || TYPE_HAS_CONSTEXPR_CTOR (inner_elt_type)));
4257 vec<constructor_elt, va_gc> *const_vec = NULL;
4258 bool saw_non_const = false;
4259 /* If we're initializing a static array, we want to do static
4260 initialization of any elements with constant initializers even if
4261 some are non-constant. */
4262 bool do_static_init = (DECL_P (obase) && TREE_STATIC (obase));
4264 bool empty_list = false;
4265 if (init && BRACE_ENCLOSED_INITIALIZER_P (init)
4266 && CONSTRUCTOR_NELTS (init) == 0)
4267 /* Skip over the handling of non-empty init lists. */
4268 empty_list = true;
4270 /* Maybe pull out constant value when from_array? */
4272 else if (init != NULL_TREE && TREE_CODE (init) == CONSTRUCTOR)
4274 /* Do non-default initialization of non-trivial arrays resulting from
4275 brace-enclosed initializers. */
4276 unsigned HOST_WIDE_INT idx;
4277 tree field, elt;
4278 /* If the constructor already has the array type, it's been through
4279 digest_init, so we shouldn't try to do anything more. */
4280 bool digested = same_type_p (atype, TREE_TYPE (init));
4281 from_array = 0;
4283 if (length_check)
4284 finish_length_check (atype, iterator, obase, CONSTRUCTOR_NELTS (init));
4286 if (try_const)
4287 vec_alloc (const_vec, CONSTRUCTOR_NELTS (init));
4289 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (init), idx, field, elt)
4291 tree baseref = build1 (INDIRECT_REF, type, base);
4292 tree one_init;
4294 num_initialized_elts++;
4296 current_stmt_tree ()->stmts_are_full_exprs_p = 1;
4297 if (digested)
4298 one_init = build2 (INIT_EXPR, type, baseref, elt);
4299 else if (MAYBE_CLASS_TYPE_P (type) || TREE_CODE (type) == ARRAY_TYPE)
4300 one_init = build_aggr_init (baseref, elt, 0, complain);
4301 else
4302 one_init = cp_build_modify_expr (input_location, baseref,
4303 NOP_EXPR, elt, complain);
4304 if (one_init == error_mark_node)
4305 errors = true;
4306 if (try_const)
4308 tree e = maybe_constant_init (one_init);
4309 if (reduced_constant_expression_p (e))
4311 CONSTRUCTOR_APPEND_ELT (const_vec, field, e);
4312 if (do_static_init)
4313 one_init = NULL_TREE;
4314 else
4315 one_init = build2 (INIT_EXPR, type, baseref, e);
4317 else
4319 if (do_static_init)
4321 tree value = build_zero_init (TREE_TYPE (e), NULL_TREE,
4322 true);
4323 if (value)
4324 CONSTRUCTOR_APPEND_ELT (const_vec, field, value);
4326 saw_non_const = true;
4330 if (one_init)
4331 finish_expr_stmt (one_init);
4332 current_stmt_tree ()->stmts_are_full_exprs_p = 0;
4334 one_init = cp_build_unary_op (PREINCREMENT_EXPR, base, false,
4335 complain);
4336 if (one_init == error_mark_node)
4337 errors = true;
4338 else
4339 finish_expr_stmt (one_init);
4341 one_init = cp_build_unary_op (PREDECREMENT_EXPR, iterator, false,
4342 complain);
4343 if (one_init == error_mark_node)
4344 errors = true;
4345 else
4346 finish_expr_stmt (one_init);
4349 /* Any elements without explicit initializers get T{}. */
4350 empty_list = true;
4352 else if (init && TREE_CODE (init) == STRING_CST)
4354 /* Check that the array is at least as long as the string. */
4355 if (length_check)
4356 finish_length_check (atype, iterator, obase,
4357 TREE_STRING_LENGTH (init));
4358 tree length = build_int_cst (ptrdiff_type_node,
4359 TREE_STRING_LENGTH (init));
4361 /* Copy the string to the first part of the array. */
4362 tree alias_set = build_int_cst (build_pointer_type (type), 0);
4363 tree lhs = build2 (MEM_REF, TREE_TYPE (init), base, alias_set);
4364 tree stmt = build2 (MODIFY_EXPR, void_type_node, lhs, init);
4365 finish_expr_stmt (stmt);
4367 /* Adjust the counter and pointer. */
4368 stmt = cp_build_binary_op (loc, MINUS_EXPR, iterator, length, complain);
4369 stmt = build2 (MODIFY_EXPR, void_type_node, iterator, stmt);
4370 finish_expr_stmt (stmt);
4372 stmt = cp_build_binary_op (loc, PLUS_EXPR, base, length, complain);
4373 stmt = build2 (MODIFY_EXPR, void_type_node, base, stmt);
4374 finish_expr_stmt (stmt);
4376 /* And set the rest of the array to NUL. */
4377 from_array = 0;
4378 explicit_value_init_p = true;
4380 else if (from_array)
4382 if (init)
4383 /* OK, we set base2 above. */;
4384 else if (CLASS_TYPE_P (type)
4385 && ! TYPE_HAS_DEFAULT_CONSTRUCTOR (type))
4387 if (complain & tf_error)
4388 error ("initializer ends prematurely");
4389 errors = true;
4393 /* Now, default-initialize any remaining elements. We don't need to
4394 do that if a) the type does not need constructing, or b) we've
4395 already initialized all the elements.
4397 We do need to keep going if we're copying an array. */
4399 if (try_const && !init)
4400 /* With a constexpr default constructor, which we checked for when
4401 setting try_const above, default-initialization is equivalent to
4402 value-initialization, and build_value_init gives us something more
4403 friendly to maybe_constant_init. */
4404 explicit_value_init_p = true;
4405 if (from_array
4406 || ((type_build_ctor_call (type) || init || explicit_value_init_p)
4407 && ! (tree_fits_shwi_p (maxindex)
4408 && (num_initialized_elts
4409 == tree_to_shwi (maxindex) + 1))))
4411 /* If the ITERATOR is lesser or equal to -1, then we don't have to loop;
4412 we've already initialized all the elements. */
4413 tree for_stmt;
4414 tree elt_init;
4415 tree to;
4417 for_stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
4418 finish_init_stmt (for_stmt);
4419 finish_for_cond (build2 (GT_EXPR, boolean_type_node, iterator,
4420 build_int_cst (TREE_TYPE (iterator), -1)),
4421 for_stmt, false, 0);
4422 elt_init = cp_build_unary_op (PREDECREMENT_EXPR, iterator, false,
4423 complain);
4424 if (elt_init == error_mark_node)
4425 errors = true;
4426 finish_for_expr (elt_init, for_stmt);
4428 to = build1 (INDIRECT_REF, type, base);
4430 /* If the initializer is {}, then all elements are initialized from T{}.
4431 But for non-classes, that's the same as value-initialization. */
4432 if (empty_list)
4434 if (cxx_dialect >= cxx11 && AGGREGATE_TYPE_P (type))
4436 init = build_constructor (init_list_type_node, NULL);
4438 else
4440 init = NULL_TREE;
4441 explicit_value_init_p = true;
4445 if (from_array)
4447 tree from;
4449 if (base2)
4451 from = build1 (INDIRECT_REF, itype, base2);
4452 if (xvalue)
4453 from = move (from);
4454 if (direct_init)
4455 from = build_tree_list (NULL_TREE, from);
4457 else
4458 from = NULL_TREE;
4460 if (TREE_CODE (type) == ARRAY_TYPE)
4461 elt_init = build_vec_init (to, NULL_TREE, from, /*val_init*/false,
4462 from_array, complain);
4463 else if (from_array == 2)
4464 elt_init = cp_build_modify_expr (input_location, to, NOP_EXPR,
4465 from, complain);
4466 else if (type_build_ctor_call (type))
4467 elt_init = build_aggr_init (to, from, 0, complain);
4468 else if (from)
4469 elt_init = cp_build_modify_expr (input_location, to, NOP_EXPR, from,
4470 complain);
4471 else
4472 gcc_unreachable ();
4474 else if (TREE_CODE (type) == ARRAY_TYPE)
4476 if (init && !BRACE_ENCLOSED_INITIALIZER_P (init))
4478 if ((complain & tf_error))
4479 error_at (loc, "array must be initialized "
4480 "with a brace-enclosed initializer");
4481 elt_init = error_mark_node;
4483 else
4484 elt_init = build_vec_init (build1 (INDIRECT_REF, type, base),
4485 0, init,
4486 explicit_value_init_p,
4487 0, complain);
4489 else if (explicit_value_init_p)
4491 elt_init = build_value_init (type, complain);
4492 if (elt_init != error_mark_node)
4493 elt_init = build2 (INIT_EXPR, type, to, elt_init);
4495 else
4497 gcc_assert (type_build_ctor_call (type) || init);
4498 if (CLASS_TYPE_P (type))
4499 elt_init = build_aggr_init (to, init, 0, complain);
4500 else
4502 if (TREE_CODE (init) == TREE_LIST)
4503 init = build_x_compound_expr_from_list (init, ELK_INIT,
4504 complain);
4505 elt_init = (init == error_mark_node
4506 ? error_mark_node
4507 : build2 (INIT_EXPR, type, to, init));
4511 if (elt_init == error_mark_node)
4512 errors = true;
4514 if (try_const)
4516 /* FIXME refs to earlier elts */
4517 tree e = maybe_constant_init (elt_init);
4518 if (reduced_constant_expression_p (e))
4520 if (initializer_zerop (e))
4521 /* Don't fill the CONSTRUCTOR with zeros. */
4522 e = NULL_TREE;
4523 if (do_static_init)
4524 elt_init = NULL_TREE;
4526 else
4528 saw_non_const = true;
4529 if (do_static_init)
4530 e = build_zero_init (TREE_TYPE (e), NULL_TREE, true);
4531 else
4532 e = NULL_TREE;
4535 if (e)
4537 int max = tree_to_shwi (maxindex)+1;
4538 for (; num_initialized_elts < max; ++num_initialized_elts)
4540 tree field = size_int (num_initialized_elts);
4541 CONSTRUCTOR_APPEND_ELT (const_vec, field, e);
4546 current_stmt_tree ()->stmts_are_full_exprs_p = 1;
4547 if (elt_init && !errors)
4548 finish_expr_stmt (elt_init);
4549 current_stmt_tree ()->stmts_are_full_exprs_p = 0;
4551 finish_expr_stmt (cp_build_unary_op (PREINCREMENT_EXPR, base, false,
4552 complain));
4553 if (base2)
4554 finish_expr_stmt (cp_build_unary_op (PREINCREMENT_EXPR, base2, false,
4555 complain));
4557 finish_for_stmt (for_stmt);
4560 /* Make sure to cleanup any partially constructed elements. */
4561 if (flag_exceptions && TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type)
4562 && from_array != 2)
4564 tree e;
4565 tree m = cp_build_binary_op (input_location,
4566 MINUS_EXPR, maxindex, iterator,
4567 complain);
4569 /* Flatten multi-dimensional array since build_vec_delete only
4570 expects one-dimensional array. */
4571 if (TREE_CODE (type) == ARRAY_TYPE)
4572 m = cp_build_binary_op (input_location,
4573 MULT_EXPR, m,
4574 /* Avoid mixing signed and unsigned. */
4575 convert (TREE_TYPE (m),
4576 array_type_nelts_total (type)),
4577 complain);
4579 finish_cleanup_try_block (try_block);
4580 e = build_vec_delete_1 (rval, m,
4581 inner_elt_type, sfk_complete_destructor,
4582 /*use_global_delete=*/0, complain);
4583 if (e == error_mark_node)
4584 errors = true;
4585 finish_cleanup (e, try_block);
4588 /* The value of the array initialization is the array itself, RVAL
4589 is a pointer to the first element. */
4590 finish_stmt_expr_expr (rval, stmt_expr);
4592 stmt_expr = finish_init_stmts (is_global, stmt_expr, compound_stmt);
4594 current_stmt_tree ()->stmts_are_full_exprs_p = destroy_temps;
4596 if (errors)
4597 return error_mark_node;
4599 if (try_const)
4601 if (!saw_non_const)
4603 tree const_init = build_constructor (atype, const_vec);
4604 return build2 (INIT_EXPR, atype, obase, const_init);
4606 else if (do_static_init && !vec_safe_is_empty (const_vec))
4607 DECL_INITIAL (obase) = build_constructor (atype, const_vec);
4608 else
4609 vec_free (const_vec);
4612 /* Now make the result have the correct type. */
4613 if (TREE_CODE (atype) == ARRAY_TYPE)
4615 atype = build_pointer_type (atype);
4616 stmt_expr = build1 (NOP_EXPR, atype, stmt_expr);
4617 stmt_expr = cp_build_fold_indirect_ref (stmt_expr);
4618 TREE_NO_WARNING (stmt_expr) = 1;
4621 return stmt_expr;
4624 /* Call the DTOR_KIND destructor for EXP. FLAGS are as for
4625 build_delete. */
4627 static tree
4628 build_dtor_call (tree exp, special_function_kind dtor_kind, int flags,
4629 tsubst_flags_t complain)
4631 tree name;
4632 switch (dtor_kind)
4634 case sfk_complete_destructor:
4635 name = complete_dtor_identifier;
4636 break;
4638 case sfk_base_destructor:
4639 name = base_dtor_identifier;
4640 break;
4642 case sfk_deleting_destructor:
4643 name = deleting_dtor_identifier;
4644 break;
4646 default:
4647 gcc_unreachable ();
4650 return build_special_member_call (exp, name,
4651 /*args=*/NULL,
4652 /*binfo=*/TREE_TYPE (exp),
4653 flags,
4654 complain);
4657 /* Generate a call to a destructor. TYPE is the type to cast ADDR to.
4658 ADDR is an expression which yields the store to be destroyed.
4659 AUTO_DELETE is the name of the destructor to call, i.e., either
4660 sfk_complete_destructor, sfk_base_destructor, or
4661 sfk_deleting_destructor.
4663 FLAGS is the logical disjunction of zero or more LOOKUP_
4664 flags. See cp-tree.h for more info. */
4666 tree
4667 build_delete (tree otype, tree addr, special_function_kind auto_delete,
4668 int flags, int use_global_delete, tsubst_flags_t complain)
4670 tree expr;
4672 if (addr == error_mark_node)
4673 return error_mark_node;
4675 tree type = TYPE_MAIN_VARIANT (otype);
4677 /* Can happen when CURRENT_EXCEPTION_OBJECT gets its type
4678 set to `error_mark_node' before it gets properly cleaned up. */
4679 if (type == error_mark_node)
4680 return error_mark_node;
4682 if (TYPE_PTR_P (type))
4683 type = TYPE_MAIN_VARIANT (TREE_TYPE (type));
4685 if (TREE_CODE (type) == ARRAY_TYPE)
4687 if (TYPE_DOMAIN (type) == NULL_TREE)
4689 if (complain & tf_error)
4690 error ("unknown array size in delete");
4691 return error_mark_node;
4693 return build_vec_delete (addr, array_type_nelts (type),
4694 auto_delete, use_global_delete, complain);
4697 bool deleting = (auto_delete == sfk_deleting_destructor);
4698 gcc_assert (deleting == !(flags & LOOKUP_DESTRUCTOR));
4700 if (TYPE_PTR_P (otype))
4702 addr = mark_rvalue_use (addr);
4704 /* We don't want to warn about delete of void*, only other
4705 incomplete types. Deleting other incomplete types
4706 invokes undefined behavior, but it is not ill-formed, so
4707 compile to something that would even do The Right Thing
4708 (TM) should the type have a trivial dtor and no delete
4709 operator. */
4710 if (!VOID_TYPE_P (type))
4712 complete_type (type);
4713 if (!COMPLETE_TYPE_P (type))
4715 if ((complain & tf_warning)
4716 && warning (OPT_Wdelete_incomplete,
4717 "possible problem detected in invocation of "
4718 "delete operator:"))
4720 cxx_incomplete_type_diagnostic (addr, type, DK_WARNING);
4721 inform (input_location,
4722 "neither the destructor nor the class-specific "
4723 "operator delete will be called, even if they are "
4724 "declared when the class is defined");
4727 else if (deleting && warn_delnonvdtor
4728 && MAYBE_CLASS_TYPE_P (type) && !CLASSTYPE_FINAL (type)
4729 && TYPE_POLYMORPHIC_P (type))
4731 tree dtor = CLASSTYPE_DESTRUCTOR (type);
4732 if (!dtor || !DECL_VINDEX (dtor))
4734 if (CLASSTYPE_PURE_VIRTUALS (type))
4735 warning (OPT_Wdelete_non_virtual_dtor,
4736 "deleting object of abstract class type %qT"
4737 " which has non-virtual destructor"
4738 " will cause undefined behavior", type);
4739 else
4740 warning (OPT_Wdelete_non_virtual_dtor,
4741 "deleting object of polymorphic class type %qT"
4742 " which has non-virtual destructor"
4743 " might cause undefined behavior", type);
4748 /* Throw away const and volatile on target type of addr. */
4749 addr = convert_force (build_pointer_type (type), addr, 0, complain);
4751 else
4753 /* Don't check PROTECT here; leave that decision to the
4754 destructor. If the destructor is accessible, call it,
4755 else report error. */
4756 addr = cp_build_addr_expr (addr, complain);
4757 if (addr == error_mark_node)
4758 return error_mark_node;
4760 addr = convert_force (build_pointer_type (type), addr, 0, complain);
4763 if (deleting)
4764 /* We will use ADDR multiple times so we must save it. */
4765 addr = save_expr (addr);
4767 bool virtual_p = false;
4768 if (type_build_dtor_call (type))
4770 if (CLASSTYPE_LAZY_DESTRUCTOR (type))
4771 lazily_declare_fn (sfk_destructor, type);
4772 virtual_p = DECL_VIRTUAL_P (CLASSTYPE_DESTRUCTOR (type));
4775 tree head = NULL_TREE;
4776 tree do_delete = NULL_TREE;
4778 if (!deleting)
4780 /* Leave do_delete null. */
4782 /* For `::delete x', we must not use the deleting destructor
4783 since then we would not be sure to get the global `operator
4784 delete'. */
4785 else if (use_global_delete)
4787 head = get_target_expr (build_headof (addr));
4788 /* Delete the object. */
4789 do_delete = build_op_delete_call (DELETE_EXPR,
4790 head,
4791 cxx_sizeof_nowarn (type),
4792 /*global_p=*/true,
4793 /*placement=*/NULL_TREE,
4794 /*alloc_fn=*/NULL_TREE,
4795 complain);
4796 /* Otherwise, treat this like a complete object destructor
4797 call. */
4798 auto_delete = sfk_complete_destructor;
4800 /* If the destructor is non-virtual, there is no deleting
4801 variant. Instead, we must explicitly call the appropriate
4802 `operator delete' here. */
4803 else if (!virtual_p)
4805 /* Build the call. */
4806 do_delete = build_op_delete_call (DELETE_EXPR,
4807 addr,
4808 cxx_sizeof_nowarn (type),
4809 /*global_p=*/false,
4810 /*placement=*/NULL_TREE,
4811 /*alloc_fn=*/NULL_TREE,
4812 complain);
4813 /* Call the complete object destructor. */
4814 auto_delete = sfk_complete_destructor;
4816 else if (TYPE_GETS_REG_DELETE (type))
4818 /* Make sure we have access to the member op delete, even though
4819 we'll actually be calling it from the destructor. */
4820 build_op_delete_call (DELETE_EXPR, addr, cxx_sizeof_nowarn (type),
4821 /*global_p=*/false,
4822 /*placement=*/NULL_TREE,
4823 /*alloc_fn=*/NULL_TREE,
4824 complain);
4827 if (type_build_dtor_call (type))
4828 expr = build_dtor_call (cp_build_fold_indirect_ref (addr),
4829 auto_delete, flags, complain);
4830 else
4831 expr = build_trivial_dtor_call (addr);
4832 if (expr == error_mark_node)
4833 return error_mark_node;
4835 if (!deleting)
4836 return expr;
4838 if (do_delete && !TREE_SIDE_EFFECTS (expr))
4839 expr = do_delete;
4840 else if (do_delete)
4841 /* The delete operator must be called, regardless of whether
4842 the destructor throws.
4844 [expr.delete]/7 The deallocation function is called
4845 regardless of whether the destructor for the object or some
4846 element of the array throws an exception. */
4847 expr = build2 (TRY_FINALLY_EXPR, void_type_node, expr, do_delete);
4849 /* We need to calculate this before the dtor changes the vptr. */
4850 if (head)
4851 expr = build2 (COMPOUND_EXPR, void_type_node, head, expr);
4853 /* Handle deleting a null pointer. */
4854 warning_sentinel s (warn_address);
4855 tree ifexp = cp_build_binary_op (input_location, NE_EXPR, addr,
4856 nullptr_node, complain);
4857 ifexp = cp_fully_fold (ifexp);
4859 if (ifexp == error_mark_node)
4860 return error_mark_node;
4861 /* This is a compiler generated comparison, don't emit
4862 e.g. -Wnonnull-compare warning for it. */
4863 else if (TREE_CODE (ifexp) == NE_EXPR)
4864 TREE_NO_WARNING (ifexp) = 1;
4866 if (!integer_nonzerop (ifexp))
4867 expr = build3 (COND_EXPR, void_type_node, ifexp, expr, void_node);
4869 return expr;
4872 /* At the beginning of a destructor, push cleanups that will call the
4873 destructors for our base classes and members.
4875 Called from begin_destructor_body. */
4877 void
4878 push_base_cleanups (void)
4880 tree binfo, base_binfo;
4881 int i;
4882 tree member;
4883 tree expr;
4884 vec<tree, va_gc> *vbases;
4886 /* Run destructors for all virtual baseclasses. */
4887 if (!ABSTRACT_CLASS_TYPE_P (current_class_type)
4888 && CLASSTYPE_VBASECLASSES (current_class_type))
4890 tree cond = (condition_conversion
4891 (build2 (BIT_AND_EXPR, integer_type_node,
4892 current_in_charge_parm,
4893 integer_two_node)));
4895 /* The CLASSTYPE_VBASECLASSES vector is in initialization
4896 order, which is also the right order for pushing cleanups. */
4897 for (vbases = CLASSTYPE_VBASECLASSES (current_class_type), i = 0;
4898 vec_safe_iterate (vbases, i, &base_binfo); i++)
4900 if (type_build_dtor_call (BINFO_TYPE (base_binfo)))
4902 expr = build_special_member_call (current_class_ref,
4903 base_dtor_identifier,
4904 NULL,
4905 base_binfo,
4906 (LOOKUP_NORMAL
4907 | LOOKUP_NONVIRTUAL),
4908 tf_warning_or_error);
4909 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (BINFO_TYPE (base_binfo)))
4911 expr = build3 (COND_EXPR, void_type_node, cond,
4912 expr, void_node);
4913 finish_decl_cleanup (NULL_TREE, expr);
4919 /* Take care of the remaining baseclasses. */
4920 for (binfo = TYPE_BINFO (current_class_type), i = 0;
4921 BINFO_BASE_ITERATE (binfo, i, base_binfo); i++)
4923 if (BINFO_VIRTUAL_P (base_binfo)
4924 || !type_build_dtor_call (BINFO_TYPE (base_binfo)))
4925 continue;
4927 expr = build_special_member_call (current_class_ref,
4928 base_dtor_identifier,
4929 NULL, base_binfo,
4930 LOOKUP_NORMAL | LOOKUP_NONVIRTUAL,
4931 tf_warning_or_error);
4932 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (BINFO_TYPE (base_binfo)))
4933 finish_decl_cleanup (NULL_TREE, expr);
4936 /* Don't automatically destroy union members. */
4937 if (TREE_CODE (current_class_type) == UNION_TYPE)
4938 return;
4940 for (member = TYPE_FIELDS (current_class_type); member;
4941 member = DECL_CHAIN (member))
4943 tree this_type = TREE_TYPE (member);
4944 if (this_type == error_mark_node
4945 || TREE_CODE (member) != FIELD_DECL
4946 || DECL_ARTIFICIAL (member))
4947 continue;
4948 if (ANON_AGGR_TYPE_P (this_type))
4949 continue;
4950 if (type_build_dtor_call (this_type))
4952 tree this_member = (build_class_member_access_expr
4953 (current_class_ref, member,
4954 /*access_path=*/NULL_TREE,
4955 /*preserve_reference=*/false,
4956 tf_warning_or_error));
4957 expr = build_delete (this_type, this_member,
4958 sfk_complete_destructor,
4959 LOOKUP_NONVIRTUAL|LOOKUP_DESTRUCTOR|LOOKUP_NORMAL,
4960 0, tf_warning_or_error);
4961 if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (this_type))
4962 finish_decl_cleanup (NULL_TREE, expr);
4967 /* Build a C++ vector delete expression.
4968 MAXINDEX is the number of elements to be deleted.
4969 ELT_SIZE is the nominal size of each element in the vector.
4970 BASE is the expression that should yield the store to be deleted.
4971 This function expands (or synthesizes) these calls itself.
4972 AUTO_DELETE_VEC says whether the container (vector) should be deallocated.
4974 This also calls delete for virtual baseclasses of elements of the vector.
4976 Update: MAXINDEX is no longer needed. The size can be extracted from the
4977 start of the vector for pointers, and from the type for arrays. We still
4978 use MAXINDEX for arrays because it happens to already have one of the
4979 values we'd have to extract. (We could use MAXINDEX with pointers to
4980 confirm the size, and trap if the numbers differ; not clear that it'd
4981 be worth bothering.) */
4983 tree
4984 build_vec_delete (tree base, tree maxindex,
4985 special_function_kind auto_delete_vec,
4986 int use_global_delete, tsubst_flags_t complain)
4988 tree type;
4989 tree rval;
4990 tree base_init = NULL_TREE;
4992 type = TREE_TYPE (base);
4994 if (TYPE_PTR_P (type))
4996 /* Step back one from start of vector, and read dimension. */
4997 tree cookie_addr;
4998 tree size_ptr_type = build_pointer_type (sizetype);
5000 base = mark_rvalue_use (base);
5001 if (TREE_SIDE_EFFECTS (base))
5003 base_init = get_target_expr (base);
5004 base = TARGET_EXPR_SLOT (base_init);
5006 type = strip_array_types (TREE_TYPE (type));
5007 cookie_addr = fold_build1_loc (input_location, NEGATE_EXPR,
5008 sizetype, TYPE_SIZE_UNIT (sizetype));
5009 cookie_addr = fold_build_pointer_plus (fold_convert (size_ptr_type, base),
5010 cookie_addr);
5011 maxindex = cp_build_fold_indirect_ref (cookie_addr);
5013 else if (TREE_CODE (type) == ARRAY_TYPE)
5015 /* Get the total number of things in the array, maxindex is a
5016 bad name. */
5017 maxindex = array_type_nelts_total (type);
5018 type = strip_array_types (type);
5019 base = decay_conversion (base, complain);
5020 if (base == error_mark_node)
5021 return error_mark_node;
5022 if (TREE_SIDE_EFFECTS (base))
5024 base_init = get_target_expr (base);
5025 base = TARGET_EXPR_SLOT (base_init);
5028 else
5030 if (base != error_mark_node && !(complain & tf_error))
5031 error ("type to vector delete is neither pointer or array type");
5032 return error_mark_node;
5035 rval = build_vec_delete_1 (base, maxindex, type, auto_delete_vec,
5036 use_global_delete, complain);
5037 if (base_init && rval != error_mark_node)
5038 rval = build2 (COMPOUND_EXPR, TREE_TYPE (rval), base_init, rval);
5040 return rval;
5043 #include "gt-cp-init.h"