d: Merge upstream dmd, druntime c8ae4adb2e, phobos 792c8b7c1.
[official-gcc.git] / gcc / cp / constexpr.cc
blob3f7892aa88a9f9b949eab33c771ce58e1523092c
1 /* Perform -*- C++ -*- constant expression evaluation, including calls to
2 constexpr functions. These routines are used both during actual parsing
3 and during the instantiation of template functions.
5 Copyright (C) 1998-2022 Free Software Foundation, Inc.
7 This file is part of GCC.
9 GCC is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3, or (at your option)
12 any later version.
14 GCC is distributed in the hope that it will be useful, but
15 WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3. If not see
21 <http://www.gnu.org/licenses/>. */
23 #include "config.h"
24 #include "system.h"
25 #include "coretypes.h"
26 #include "cp-tree.h"
27 #include "varasm.h"
28 #include "c-family/c-objc.h"
29 #include "tree-iterator.h"
30 #include "gimplify.h"
31 #include "builtins.h"
32 #include "tree-inline.h"
33 #include "ubsan.h"
34 #include "timevar.h"
35 #include "fold-const-call.h"
36 #include "stor-layout.h"
37 #include "cgraph.h"
38 #include "opts.h"
39 #include "stringpool.h"
40 #include "attribs.h"
41 #include "fold-const.h"
42 #include "intl.h"
44 static bool verify_constant (tree, bool, bool *, bool *);
45 #define VERIFY_CONSTANT(X) \
46 do { \
47 if (verify_constant ((X), ctx->quiet, non_constant_p, overflow_p)) \
48 return t; \
49 } while (0)
51 static HOST_WIDE_INT find_array_ctor_elt (tree ary, tree dindex,
52 bool insert = false);
53 static int array_index_cmp (tree key, tree index);
55 /* Returns true iff FUN is an instantiation of a constexpr function
56 template or a defaulted constexpr function. */
58 bool
59 is_instantiation_of_constexpr (tree fun)
61 return ((DECL_TEMPLOID_INSTANTIATION (fun)
62 && DECL_DECLARED_CONSTEXPR_P (DECL_TI_TEMPLATE (fun)))
63 || (DECL_DEFAULTED_FN (fun)
64 && DECL_DECLARED_CONSTEXPR_P (fun)));
67 /* Return true if T is a literal type. */
69 bool
70 literal_type_p (tree t)
72 if (SCALAR_TYPE_P (t)
73 || VECTOR_TYPE_P (t)
74 || TYPE_REF_P (t)
75 || (VOID_TYPE_P (t) && cxx_dialect >= cxx14))
76 return true;
77 if (CLASS_TYPE_P (t))
79 t = complete_type (t);
80 gcc_assert (COMPLETE_TYPE_P (t) || errorcount);
81 return CLASSTYPE_LITERAL_P (t);
83 if (TREE_CODE (t) == ARRAY_TYPE)
84 return literal_type_p (strip_array_types (t));
85 return false;
88 /* If DECL is a variable declared `constexpr', require its type
89 be literal. Return error_mark_node if we give an error, the
90 DECL otherwise. */
92 tree
93 ensure_literal_type_for_constexpr_object (tree decl)
95 tree type = TREE_TYPE (decl);
96 if (VAR_P (decl)
97 && (DECL_DECLARED_CONSTEXPR_P (decl)
98 || var_in_constexpr_fn (decl))
99 && !processing_template_decl)
101 tree stype = strip_array_types (type);
102 if (CLASS_TYPE_P (stype) && !COMPLETE_TYPE_P (complete_type (stype)))
103 /* Don't complain here, we'll complain about incompleteness
104 when we try to initialize the variable. */;
105 else if (!literal_type_p (type))
107 if (DECL_DECLARED_CONSTEXPR_P (decl))
109 auto_diagnostic_group d;
110 error_at (DECL_SOURCE_LOCATION (decl),
111 "the type %qT of %<constexpr%> variable %qD "
112 "is not literal", type, decl);
113 explain_non_literal_class (type);
114 decl = error_mark_node;
116 else if (cxx_dialect < cxx23)
118 if (!is_instantiation_of_constexpr (current_function_decl))
120 auto_diagnostic_group d;
121 error_at (DECL_SOURCE_LOCATION (decl),
122 "variable %qD of non-literal type %qT in "
123 "%<constexpr%> function only available with "
124 "%<-std=c++2b%> or %<-std=gnu++2b%>", decl, type);
125 explain_non_literal_class (type);
126 decl = error_mark_node;
128 cp_function_chain->invalid_constexpr = true;
131 else if (DECL_DECLARED_CONSTEXPR_P (decl)
132 && variably_modified_type_p (type, NULL_TREE))
134 error_at (DECL_SOURCE_LOCATION (decl),
135 "%<constexpr%> variable %qD has variably-modified "
136 "type %qT", decl, type);
137 decl = error_mark_node;
140 return decl;
143 /* Issue a diagnostic with text GMSGID for constructs that are invalid in
144 constexpr functions. CONSTEXPR_FUNDEF_P is true if we're checking
145 a constexpr function body; if so, don't report hard errors and issue
146 a pedwarn pre-C++23, or a warning in C++23, if requested by
147 -Winvalid-constexpr. Otherwise, we're not in the context where we are
148 checking if a function can be marked 'constexpr', so give a hard error. */
150 ATTRIBUTE_GCC_DIAG(3,4)
151 static bool
152 constexpr_error (location_t location, bool constexpr_fundef_p,
153 const char *gmsgid, ...)
155 diagnostic_info diagnostic;
156 va_list ap;
157 rich_location richloc (line_table, location);
158 va_start (ap, gmsgid);
159 bool ret;
160 if (!constexpr_fundef_p)
162 /* Report an error that cannot be suppressed. */
163 diagnostic_set_info (&diagnostic, gmsgid, &ap, &richloc, DK_ERROR);
164 ret = diagnostic_report_diagnostic (global_dc, &diagnostic);
166 else if (warn_invalid_constexpr)
168 diagnostic_set_info (&diagnostic, gmsgid, &ap, &richloc,
169 cxx_dialect < cxx23 ? DK_PEDWARN : DK_WARNING);
170 diagnostic.option_index = OPT_Winvalid_constexpr;
171 ret = diagnostic_report_diagnostic (global_dc, &diagnostic);
173 else
174 ret = false;
175 va_end (ap);
176 return ret;
179 struct constexpr_fundef_hasher : ggc_ptr_hash<constexpr_fundef>
181 static hashval_t hash (const constexpr_fundef *);
182 static bool equal (const constexpr_fundef *, const constexpr_fundef *);
185 /* This table holds all constexpr function definitions seen in
186 the current translation unit. */
188 static GTY (()) hash_table<constexpr_fundef_hasher> *constexpr_fundef_table;
190 /* Utility function used for managing the constexpr function table.
191 Return true if the entries pointed to by P and Q are for the
192 same constexpr function. */
194 inline bool
195 constexpr_fundef_hasher::equal (const constexpr_fundef *lhs,
196 const constexpr_fundef *rhs)
198 return lhs->decl == rhs->decl;
201 /* Utility function used for managing the constexpr function table.
202 Return a hash value for the entry pointed to by Q. */
204 inline hashval_t
205 constexpr_fundef_hasher::hash (const constexpr_fundef *fundef)
207 return DECL_UID (fundef->decl);
210 /* Return a previously saved definition of function FUN. */
212 constexpr_fundef *
213 retrieve_constexpr_fundef (tree fun)
215 if (constexpr_fundef_table == NULL)
216 return NULL;
218 constexpr_fundef fundef = { fun, NULL_TREE, NULL_TREE, NULL_TREE };
219 return constexpr_fundef_table->find (&fundef);
222 /* Check whether the parameter and return types of FUN are valid for a
223 constexpr function, and complain if COMPLAIN. */
225 bool
226 is_valid_constexpr_fn (tree fun, bool complain)
228 bool ret = true;
230 if (DECL_INHERITED_CTOR (fun)
231 && TREE_CODE (fun) == TEMPLATE_DECL)
233 ret = false;
234 if (complain)
235 error ("inherited constructor %qD is not %<constexpr%>",
236 DECL_INHERITED_CTOR (fun));
238 else
240 for (tree parm = FUNCTION_FIRST_USER_PARM (fun);
241 parm != NULL_TREE; parm = TREE_CHAIN (parm))
242 if (!literal_type_p (TREE_TYPE (parm)))
244 ret = false;
245 if (complain)
247 auto_diagnostic_group d;
248 if (constexpr_error (input_location, /*constexpr_fundef_p*/true,
249 "invalid type for parameter %d of "
250 "%<constexpr%> function %q+#D",
251 DECL_PARM_INDEX (parm), fun))
252 explain_non_literal_class (TREE_TYPE (parm));
257 if (LAMBDA_TYPE_P (CP_DECL_CONTEXT (fun)) && cxx_dialect < cxx17)
259 ret = false;
260 if (complain)
261 inform (DECL_SOURCE_LOCATION (fun),
262 "lambdas are implicitly %<constexpr%> only in C++17 and later");
264 else if (DECL_DESTRUCTOR_P (fun))
266 if (cxx_dialect < cxx20)
268 ret = false;
269 if (complain)
270 error_at (DECL_SOURCE_LOCATION (fun),
271 "%<constexpr%> destructors only available"
272 " with %<-std=c++20%> or %<-std=gnu++20%>");
275 else if (!DECL_CONSTRUCTOR_P (fun))
277 tree rettype = TREE_TYPE (TREE_TYPE (fun));
278 if (!literal_type_p (rettype))
280 ret = false;
281 if (complain)
283 auto_diagnostic_group d;
284 if (constexpr_error (input_location, /*constexpr_fundef_p*/true,
285 "invalid return type %qT of %<constexpr%> "
286 "function %q+D", rettype, fun))
287 explain_non_literal_class (rettype);
291 /* C++14 DR 1684 removed this restriction. */
292 if (cxx_dialect < cxx14
293 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fun)
294 && !CLASSTYPE_LITERAL_P (DECL_CONTEXT (fun)))
296 ret = false;
297 if (complain)
299 auto_diagnostic_group d;
300 if (pedwarn (DECL_SOURCE_LOCATION (fun), OPT_Wpedantic,
301 "enclosing class of %<constexpr%> non-static"
302 " member function %q+#D is not a literal type",
303 fun))
304 explain_non_literal_class (DECL_CONTEXT (fun));
308 else if (CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fun)))
310 ret = false;
311 if (complain)
312 error ("%q#T has virtual base classes", DECL_CONTEXT (fun));
315 return ret;
318 /* Subroutine of build_data_member_initialization. MEMBER is a COMPONENT_REF
319 for a member of an anonymous aggregate, INIT is the initializer for that
320 member, and VEC_OUTER is the vector of constructor elements for the class
321 whose constructor we are processing. Add the initializer to the vector
322 and return true to indicate success. */
324 static bool
325 build_anon_member_initialization (tree member, tree init,
326 vec<constructor_elt, va_gc> **vec_outer)
328 /* MEMBER presents the relevant fields from the inside out, but we need
329 to build up the initializer from the outside in so that we can reuse
330 previously built CONSTRUCTORs if this is, say, the second field in an
331 anonymous struct. So we use a vec as a stack. */
332 auto_vec<tree, 2> fields;
335 fields.safe_push (TREE_OPERAND (member, 1));
336 member = TREE_OPERAND (member, 0);
338 while (ANON_AGGR_TYPE_P (TREE_TYPE (member))
339 && TREE_CODE (member) == COMPONENT_REF);
341 /* VEC has the constructor elements vector for the context of FIELD.
342 If FIELD is an anonymous aggregate, we will push inside it. */
343 vec<constructor_elt, va_gc> **vec = vec_outer;
344 tree field;
345 while (field = fields.pop(),
346 ANON_AGGR_TYPE_P (TREE_TYPE (field)))
348 tree ctor;
349 /* If there is already an outer constructor entry for the anonymous
350 aggregate FIELD, use it; otherwise, insert one. */
351 if (vec_safe_is_empty (*vec)
352 || (*vec)->last().index != field)
354 ctor = build_constructor (TREE_TYPE (field), NULL);
355 CONSTRUCTOR_APPEND_ELT (*vec, field, ctor);
357 else
358 ctor = (*vec)->last().value;
359 vec = &CONSTRUCTOR_ELTS (ctor);
362 /* Now we're at the innermost field, the one that isn't an anonymous
363 aggregate. Add its initializer to the CONSTRUCTOR and we're done. */
364 gcc_assert (fields.is_empty());
365 CONSTRUCTOR_APPEND_ELT (*vec, field, init);
367 return true;
370 /* Subroutine of build_constexpr_constructor_member_initializers.
371 The expression tree T represents a data member initialization
372 in a (constexpr) constructor definition. Build a pairing of
373 the data member with its initializer, and prepend that pair
374 to the existing initialization pair INITS. */
376 static bool
377 build_data_member_initialization (tree t, vec<constructor_elt, va_gc> **vec)
379 tree member, init;
380 if (TREE_CODE (t) == CLEANUP_POINT_EXPR)
381 t = TREE_OPERAND (t, 0);
382 if (TREE_CODE (t) == EXPR_STMT)
383 t = TREE_OPERAND (t, 0);
384 if (t == error_mark_node)
385 return false;
386 if (TREE_CODE (t) == STATEMENT_LIST)
388 for (tree stmt : tsi_range (t))
389 if (! build_data_member_initialization (stmt, vec))
390 return false;
391 return true;
393 if (TREE_CODE (t) == CLEANUP_STMT)
395 /* We can't see a CLEANUP_STMT in a constructor for a literal class,
396 but we can in a constexpr constructor for a non-literal class. Just
397 ignore it; either all the initialization will be constant, in which
398 case the cleanup can't run, or it can't be constexpr.
399 Still recurse into CLEANUP_BODY. */
400 return build_data_member_initialization (CLEANUP_BODY (t), vec);
402 if (TREE_CODE (t) == CONVERT_EXPR)
403 t = TREE_OPERAND (t, 0);
404 if (TREE_CODE (t) == INIT_EXPR
405 /* vptr initialization shows up as a MODIFY_EXPR. In C++14 we only
406 use what this function builds for cx_check_missing_mem_inits, and
407 assignment in the ctor body doesn't count. */
408 || (cxx_dialect < cxx14 && TREE_CODE (t) == MODIFY_EXPR))
410 member = TREE_OPERAND (t, 0);
411 init = break_out_target_exprs (TREE_OPERAND (t, 1));
413 else if (TREE_CODE (t) == CALL_EXPR)
415 tree fn = get_callee_fndecl (t);
416 if (!fn || !DECL_CONSTRUCTOR_P (fn))
417 /* We're only interested in calls to subobject constructors. */
418 return true;
419 member = CALL_EXPR_ARG (t, 0);
420 /* We don't use build_cplus_new here because it complains about
421 abstract bases. Leaving the call unwrapped means that it has the
422 wrong type, but cxx_eval_constant_expression doesn't care. */
423 init = break_out_target_exprs (t);
425 else if (TREE_CODE (t) == BIND_EXPR)
426 return build_data_member_initialization (BIND_EXPR_BODY (t), vec);
427 else
428 /* Don't add anything else to the CONSTRUCTOR. */
429 return true;
430 if (INDIRECT_REF_P (member))
431 member = TREE_OPERAND (member, 0);
432 if (TREE_CODE (member) == NOP_EXPR)
434 tree op = member;
435 STRIP_NOPS (op);
436 if (TREE_CODE (op) == ADDR_EXPR)
438 gcc_assert (same_type_ignoring_top_level_qualifiers_p
439 (TREE_TYPE (TREE_TYPE (op)),
440 TREE_TYPE (TREE_TYPE (member))));
441 /* Initializing a cv-qualified member; we need to look through
442 the const_cast. */
443 member = op;
445 else if (op == current_class_ptr
446 && (same_type_ignoring_top_level_qualifiers_p
447 (TREE_TYPE (TREE_TYPE (member)),
448 current_class_type)))
449 /* Delegating constructor. */
450 member = op;
451 else
453 /* This is an initializer for an empty base; keep it for now so
454 we can check it in cxx_eval_bare_aggregate. */
455 gcc_assert (is_empty_class (TREE_TYPE (TREE_TYPE (member))));
458 if (TREE_CODE (member) == ADDR_EXPR)
459 member = TREE_OPERAND (member, 0);
460 if (TREE_CODE (member) == COMPONENT_REF)
462 tree aggr = TREE_OPERAND (member, 0);
463 if (TREE_CODE (aggr) == VAR_DECL)
464 /* Initializing a local variable, don't add anything. */
465 return true;
466 if (TREE_CODE (aggr) != COMPONENT_REF)
467 /* Normal member initialization. */
468 member = TREE_OPERAND (member, 1);
469 else if (ANON_AGGR_TYPE_P (TREE_TYPE (aggr)))
470 /* Initializing a member of an anonymous union. */
471 return build_anon_member_initialization (member, init, vec);
472 else
473 /* We're initializing a vtable pointer in a base. Leave it as
474 COMPONENT_REF so we remember the path to get to the vfield. */
475 gcc_assert (TREE_TYPE (member) == vtbl_ptr_type_node);
478 /* Value-initialization can produce multiple initializers for the
479 same field; use the last one. */
480 if (!vec_safe_is_empty (*vec) && (*vec)->last().index == member)
481 (*vec)->last().value = init;
482 else
483 CONSTRUCTOR_APPEND_ELT (*vec, member, init);
484 return true;
487 /* Subroutine of check_constexpr_ctor_body_1 and constexpr_fn_retval.
488 In C++11 mode checks that the TYPE_DECLs in the BIND_EXPR_VARS of a
489 BIND_EXPR conform to 7.1.5/3/4 on typedef and alias declarations. */
491 static bool
492 check_constexpr_bind_expr_vars (tree t)
494 gcc_assert (TREE_CODE (t) == BIND_EXPR);
496 for (tree var = BIND_EXPR_VARS (t); var; var = DECL_CHAIN (var))
497 if (TREE_CODE (var) == TYPE_DECL
498 && DECL_IMPLICIT_TYPEDEF_P (var)
499 && !LAMBDA_TYPE_P (TREE_TYPE (var)))
500 return false;
501 return true;
504 /* Subroutine of check_constexpr_ctor_body. */
506 static bool
507 check_constexpr_ctor_body_1 (tree last, tree list)
509 switch (TREE_CODE (list))
511 case DECL_EXPR:
512 if (TREE_CODE (DECL_EXPR_DECL (list)) == USING_DECL
513 || TREE_CODE (DECL_EXPR_DECL (list)) == TYPE_DECL)
514 return true;
515 return false;
517 case CLEANUP_POINT_EXPR:
518 return check_constexpr_ctor_body (last, TREE_OPERAND (list, 0),
519 /*complain=*/false);
521 case BIND_EXPR:
522 if (!check_constexpr_bind_expr_vars (list)
523 || !check_constexpr_ctor_body (last, BIND_EXPR_BODY (list),
524 /*complain=*/false))
525 return false;
526 return true;
528 case USING_STMT:
529 case STATIC_ASSERT:
530 case DEBUG_BEGIN_STMT:
531 return true;
533 default:
534 return false;
538 /* Make sure that there are no statements after LAST in the constructor
539 body represented by LIST. */
541 bool
542 check_constexpr_ctor_body (tree last, tree list, bool complain)
544 /* C++14 doesn't require a constexpr ctor to have an empty body. */
545 if (cxx_dialect >= cxx14)
546 return true;
548 bool ok = true;
549 if (TREE_CODE (list) == STATEMENT_LIST)
551 tree_stmt_iterator i = tsi_last (list);
552 for (; !tsi_end_p (i); tsi_prev (&i))
554 tree t = tsi_stmt (i);
555 if (t == last)
556 break;
557 if (!check_constexpr_ctor_body_1 (last, t))
559 ok = false;
560 break;
564 else if (list != last
565 && !check_constexpr_ctor_body_1 (last, list))
566 ok = false;
567 if (!ok)
569 if (complain)
570 error ("%<constexpr%> constructor does not have empty body");
571 DECL_DECLARED_CONSTEXPR_P (current_function_decl) = false;
573 return ok;
576 /* V is a vector of constructor elements built up for the base and member
577 initializers of a constructor for TYPE. They need to be in increasing
578 offset order, which they might not be yet if TYPE has a primary base
579 which is not first in the base-clause or a vptr and at least one base
580 all of which are non-primary. */
582 static vec<constructor_elt, va_gc> *
583 sort_constexpr_mem_initializers (tree type, vec<constructor_elt, va_gc> *v)
585 tree pri = CLASSTYPE_PRIMARY_BINFO (type);
586 tree field_type;
587 unsigned i;
588 constructor_elt *ce;
590 if (pri)
591 field_type = BINFO_TYPE (pri);
592 else if (TYPE_CONTAINS_VPTR_P (type))
593 field_type = vtbl_ptr_type_node;
594 else
595 return v;
597 /* Find the element for the primary base or vptr and move it to the
598 beginning of the vec. */
599 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
600 if (TREE_TYPE (ce->index) == field_type)
601 break;
603 if (i > 0 && i < vec_safe_length (v))
605 vec<constructor_elt, va_gc> &vref = *v;
606 constructor_elt elt = vref[i];
607 for (; i > 0; --i)
608 vref[i] = vref[i-1];
609 vref[0] = elt;
612 return v;
615 /* Build compile-time evalable representations of member-initializer list
616 for a constexpr constructor. */
618 static tree
619 build_constexpr_constructor_member_initializers (tree type, tree body)
621 vec<constructor_elt, va_gc> *vec = NULL;
622 bool ok = true;
623 while (true)
624 switch (TREE_CODE (body))
626 case MUST_NOT_THROW_EXPR:
627 case EH_SPEC_BLOCK:
628 body = TREE_OPERAND (body, 0);
629 break;
631 case STATEMENT_LIST:
632 for (tree stmt : tsi_range (body))
634 body = stmt;
635 if (TREE_CODE (body) == BIND_EXPR)
636 break;
638 break;
640 case BIND_EXPR:
641 body = BIND_EXPR_BODY (body);
642 goto found;
644 default:
645 gcc_unreachable ();
647 found:
648 if (TREE_CODE (body) == TRY_BLOCK)
650 body = TREE_OPERAND (body, 0);
651 if (TREE_CODE (body) == BIND_EXPR)
652 body = BIND_EXPR_BODY (body);
654 if (TREE_CODE (body) == CLEANUP_POINT_EXPR)
656 body = TREE_OPERAND (body, 0);
657 if (TREE_CODE (body) == EXPR_STMT)
658 body = TREE_OPERAND (body, 0);
659 if (TREE_CODE (body) == INIT_EXPR
660 && (same_type_ignoring_top_level_qualifiers_p
661 (TREE_TYPE (TREE_OPERAND (body, 0)),
662 current_class_type)))
664 /* Trivial copy. */
665 return TREE_OPERAND (body, 1);
667 ok = build_data_member_initialization (body, &vec);
669 else if (TREE_CODE (body) == STATEMENT_LIST)
671 for (tree stmt : tsi_range (body))
673 ok = build_data_member_initialization (stmt, &vec);
674 if (!ok)
675 break;
678 else if (EXPR_P (body))
679 ok = build_data_member_initialization (body, &vec);
680 else
681 gcc_assert (errorcount > 0);
682 if (ok)
684 if (vec_safe_length (vec) > 0)
686 /* In a delegating constructor, return the target. */
687 constructor_elt *ce = &(*vec)[0];
688 if (ce->index == current_class_ptr)
690 body = ce->value;
691 vec_free (vec);
692 return body;
695 vec = sort_constexpr_mem_initializers (type, vec);
696 return build_constructor (type, vec);
698 else
699 return error_mark_node;
702 /* We have an expression tree T that represents a call, either CALL_EXPR
703 or AGGR_INIT_EXPR. If the call is lexically to a named function,
704 retrun the _DECL for that function. */
706 static tree
707 get_function_named_in_call (tree t)
709 tree fun = cp_get_callee (t);
710 if (fun && TREE_CODE (fun) == ADDR_EXPR
711 && TREE_CODE (TREE_OPERAND (fun, 0)) == FUNCTION_DECL)
712 fun = TREE_OPERAND (fun, 0);
713 return fun;
716 /* Subroutine of check_constexpr_fundef. BODY is the body of a function
717 declared to be constexpr, or a sub-statement thereof. Returns the
718 return value if suitable, error_mark_node for a statement not allowed in
719 a constexpr function, or NULL_TREE if no return value was found. */
721 tree
722 constexpr_fn_retval (tree body)
724 switch (TREE_CODE (body))
726 case STATEMENT_LIST:
728 tree expr = NULL_TREE;
729 for (tree stmt : tsi_range (body))
731 tree s = constexpr_fn_retval (stmt);
732 if (s == error_mark_node)
733 return error_mark_node;
734 else if (s == NULL_TREE)
735 /* Keep iterating. */;
736 else if (expr)
737 /* Multiple return statements. */
738 return error_mark_node;
739 else
740 expr = s;
742 return expr;
745 case RETURN_EXPR:
746 return break_out_target_exprs (TREE_OPERAND (body, 0));
748 case DECL_EXPR:
750 tree decl = DECL_EXPR_DECL (body);
751 if (TREE_CODE (decl) == USING_DECL
752 /* Accept __func__, __FUNCTION__, and __PRETTY_FUNCTION__. */
753 || DECL_ARTIFICIAL (decl))
754 return NULL_TREE;
755 return error_mark_node;
758 case CLEANUP_POINT_EXPR:
759 return constexpr_fn_retval (TREE_OPERAND (body, 0));
761 case BIND_EXPR:
762 if (!check_constexpr_bind_expr_vars (body))
763 return error_mark_node;
764 return constexpr_fn_retval (BIND_EXPR_BODY (body));
766 case USING_STMT:
767 case DEBUG_BEGIN_STMT:
768 return NULL_TREE;
770 case CALL_EXPR:
772 tree fun = get_function_named_in_call (body);
773 if (fun != NULL_TREE
774 && fndecl_built_in_p (fun, BUILT_IN_UNREACHABLE))
775 return NULL_TREE;
777 /* Fallthru. */
779 default:
780 return error_mark_node;
784 /* Subroutine of check_constexpr_fundef. BODY is the DECL_SAVED_TREE of
785 FUN; do the necessary transformations to turn it into a single expression
786 that we can store in the hash table. */
788 static tree
789 massage_constexpr_body (tree fun, tree body)
791 if (DECL_CONSTRUCTOR_P (fun))
792 body = build_constexpr_constructor_member_initializers
793 (DECL_CONTEXT (fun), body);
794 else if (cxx_dialect < cxx14)
796 if (TREE_CODE (body) == EH_SPEC_BLOCK)
797 body = EH_SPEC_STMTS (body);
798 if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
799 body = TREE_OPERAND (body, 0);
800 body = constexpr_fn_retval (body);
802 return body;
805 /* CTYPE is a type constructed from BODY. Return true if some
806 bases/fields are uninitialized, and complain if COMPLAIN. */
808 static bool
809 cx_check_missing_mem_inits (tree ctype, tree body, bool complain)
811 /* We allow uninitialized bases/fields in C++20. */
812 if (cxx_dialect >= cxx20)
813 return false;
815 unsigned nelts = 0;
817 if (body)
819 if (TREE_CODE (body) != CONSTRUCTOR)
820 return false;
821 nelts = CONSTRUCTOR_NELTS (body);
823 tree field = TYPE_FIELDS (ctype);
825 if (TREE_CODE (ctype) == UNION_TYPE)
827 if (nelts == 0 && next_aggregate_field (field))
829 if (complain)
830 error ("%<constexpr%> constructor for union %qT must "
831 "initialize exactly one non-static data member", ctype);
832 return true;
834 return false;
837 /* Iterate over the CONSTRUCTOR, checking any missing fields don't
838 need an explicit initialization. */
839 bool bad = false;
840 for (unsigned i = 0; i <= nelts; ++i)
842 tree index = NULL_TREE;
843 if (i < nelts)
845 index = CONSTRUCTOR_ELT (body, i)->index;
846 /* Skip base and vtable inits. */
847 if (TREE_CODE (index) != FIELD_DECL
848 || DECL_ARTIFICIAL (index))
849 continue;
852 for (; field != index; field = DECL_CHAIN (field))
854 tree ftype;
855 if (TREE_CODE (field) != FIELD_DECL)
856 continue;
857 if (DECL_UNNAMED_BIT_FIELD (field))
858 continue;
859 if (DECL_ARTIFICIAL (field))
860 continue;
861 if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
863 /* Recurse to check the anonymous aggregate member. */
864 bad |= cx_check_missing_mem_inits
865 (TREE_TYPE (field), NULL_TREE, complain);
866 if (bad && !complain)
867 return true;
868 continue;
870 ftype = TREE_TYPE (field);
871 if (!ftype || !TYPE_P (ftype) || !COMPLETE_TYPE_P (ftype))
872 /* A flexible array can't be intialized here, so don't complain
873 that it isn't. */
874 continue;
875 if (is_empty_field (field))
876 /* An empty field doesn't need an initializer. */
877 continue;
878 ftype = strip_array_types (ftype);
879 if (type_has_constexpr_default_constructor (ftype))
881 /* It's OK to skip a member with a trivial constexpr ctor.
882 A constexpr ctor that isn't trivial should have been
883 added in by now. */
884 gcc_checking_assert (!TYPE_HAS_COMPLEX_DFLT (ftype)
885 || errorcount != 0);
886 continue;
888 if (!complain)
889 return true;
890 auto_diagnostic_group d;
891 error ("member %qD must be initialized by mem-initializer "
892 "in %<constexpr%> constructor", field);
893 inform (DECL_SOURCE_LOCATION (field), "declared here");
894 bad = true;
896 if (field == NULL_TREE)
897 break;
899 if (ANON_AGGR_TYPE_P (TREE_TYPE (index)))
901 /* Check the anonymous aggregate initializer is valid. */
902 bad |= cx_check_missing_mem_inits
903 (TREE_TYPE (index), CONSTRUCTOR_ELT (body, i)->value, complain);
904 if (bad && !complain)
905 return true;
907 field = DECL_CHAIN (field);
910 return bad;
913 /* We are processing the definition of the constexpr function FUN.
914 Check that its body fulfills the apropriate requirements and
915 enter it in the constexpr function definition table. */
917 void
918 maybe_save_constexpr_fundef (tree fun)
920 if (processing_template_decl
921 || cp_function_chain->invalid_constexpr
922 || (DECL_CLONED_FUNCTION_P (fun) && !DECL_DELETING_DESTRUCTOR_P (fun)))
923 return;
925 /* With -fimplicit-constexpr, try to make inlines constexpr. We'll
926 actually set DECL_DECLARED_CONSTEXPR_P below if the checks pass. */
927 bool implicit = false;
928 if (flag_implicit_constexpr)
930 if (DECL_DELETING_DESTRUCTOR_P (fun)
931 && decl_implicit_constexpr_p (DECL_CLONED_FUNCTION (fun)))
932 /* Don't inherit implicit constexpr from the non-deleting
933 destructor. */
934 DECL_DECLARED_CONSTEXPR_P (fun) = false;
936 if (!DECL_DECLARED_CONSTEXPR_P (fun)
937 && DECL_DECLARED_INLINE_P (fun)
938 && !lookup_attribute ("noinline", DECL_ATTRIBUTES (fun)))
939 implicit = true;
942 if (!DECL_DECLARED_CONSTEXPR_P (fun) && !implicit)
943 return;
945 bool complain = !DECL_GENERATED_P (fun) && !implicit;
947 if (!is_valid_constexpr_fn (fun, complain))
948 return;
950 tree massaged = massage_constexpr_body (fun, DECL_SAVED_TREE (fun));
951 if (massaged == NULL_TREE || massaged == error_mark_node)
953 if (!DECL_CONSTRUCTOR_P (fun) && complain)
954 error ("body of %<constexpr%> function %qD not a return-statement",
955 fun);
956 return;
959 bool potential = potential_rvalue_constant_expression (massaged);
960 if (!potential && complain)
961 require_potential_rvalue_constant_expression_fncheck (massaged);
963 if (DECL_CONSTRUCTOR_P (fun) && potential
964 && !DECL_DEFAULTED_FN (fun))
966 if (cx_check_missing_mem_inits (DECL_CONTEXT (fun),
967 massaged, complain))
968 potential = false;
969 else if (cxx_dialect > cxx11)
971 /* What we got from massage_constexpr_body is pretty much just the
972 ctor-initializer, also check the body. */
973 massaged = DECL_SAVED_TREE (fun);
974 potential = potential_rvalue_constant_expression (massaged);
975 if (!potential && complain)
976 require_potential_rvalue_constant_expression_fncheck (massaged);
980 if (!potential && complain
981 /* If -Wno-invalid-constexpr was specified, we haven't complained
982 about non-constant expressions yet. Register the function and
983 complain in explain_invalid_constexpr_fn if the function is
984 called. */
985 && warn_invalid_constexpr != 0)
986 return;
988 if (implicit)
990 if (potential)
992 DECL_DECLARED_CONSTEXPR_P (fun) = true;
993 DECL_LANG_SPECIFIC (fun)->u.fn.implicit_constexpr = true;
994 if (DECL_CONSTRUCTOR_P (fun))
995 TYPE_HAS_CONSTEXPR_CTOR (DECL_CONTEXT (fun)) = true;
997 else
998 /* Don't bother keeping the pre-generic body of unsuitable functions
999 not explicitly declared constexpr. */
1000 return;
1003 constexpr_fundef entry = {fun, NULL_TREE, NULL_TREE, NULL_TREE};
1004 bool clear_ctx = false;
1005 if (DECL_RESULT (fun) && DECL_CONTEXT (DECL_RESULT (fun)) == NULL_TREE)
1007 clear_ctx = true;
1008 DECL_CONTEXT (DECL_RESULT (fun)) = fun;
1010 tree saved_fn = current_function_decl;
1011 current_function_decl = fun;
1012 entry.body = copy_fn (entry.decl, entry.parms, entry.result);
1013 current_function_decl = saved_fn;
1014 if (clear_ctx)
1015 DECL_CONTEXT (DECL_RESULT (entry.decl)) = NULL_TREE;
1016 if (!potential)
1017 /* For a template instantiation, we want to remember the pre-generic body
1018 for explain_invalid_constexpr_fn, but do tell cxx_eval_call_expression
1019 that it doesn't need to bother trying to expand the function. */
1020 entry.result = error_mark_node;
1022 register_constexpr_fundef (entry);
1025 /* BODY is a validated and massaged definition of a constexpr
1026 function. Register it in the hash table. */
1028 void
1029 register_constexpr_fundef (const constexpr_fundef &value)
1031 /* Create the constexpr function table if necessary. */
1032 if (constexpr_fundef_table == NULL)
1033 constexpr_fundef_table
1034 = hash_table<constexpr_fundef_hasher>::create_ggc (101);
1036 constexpr_fundef **slot = constexpr_fundef_table->find_slot
1037 (const_cast<constexpr_fundef *> (&value), INSERT);
1039 gcc_assert (*slot == NULL);
1040 *slot = ggc_alloc<constexpr_fundef> ();
1041 **slot = value;
1044 /* FUN is a non-constexpr (or, with -Wno-invalid-constexpr, a constexpr
1045 function called in a context that requires a constant expression).
1046 If it comes from a constexpr template, explain why the instantiation
1047 isn't constexpr. Otherwise, explain why the function cannot be used
1048 in a constexpr context. */
1050 void
1051 explain_invalid_constexpr_fn (tree fun)
1053 static hash_set<tree> *diagnosed;
1054 tree body;
1055 /* In C++23, a function marked 'constexpr' may not actually be a constant
1056 expression. We haven't diagnosed the problem yet: -Winvalid-constexpr
1057 wasn't enabled. The function was called, so diagnose why it cannot be
1058 used in a constant expression. */
1059 if (warn_invalid_constexpr == 0 && DECL_DECLARED_CONSTEXPR_P (fun))
1060 /* Go on. */;
1061 /* Only diagnose defaulted functions, lambdas, or instantiations. */
1062 else if (!DECL_DEFAULTED_FN (fun)
1063 && !LAMBDA_TYPE_P (CP_DECL_CONTEXT (fun))
1064 && !is_instantiation_of_constexpr (fun))
1066 inform (DECL_SOURCE_LOCATION (fun), "%qD declared here", fun);
1067 return;
1069 if (diagnosed == NULL)
1070 diagnosed = new hash_set<tree>;
1071 if (diagnosed->add (fun))
1072 /* Already explained. */
1073 return;
1075 iloc_sentinel ils = input_location;
1076 if (!lambda_static_thunk_p (fun))
1078 /* Diagnostics should completely ignore the static thunk, so leave
1079 input_location set to our caller's location. */
1080 input_location = DECL_SOURCE_LOCATION (fun);
1081 inform (input_location,
1082 "%qD is not usable as a %<constexpr%> function because:", fun);
1084 /* First check the declaration. */
1085 if (is_valid_constexpr_fn (fun, true))
1087 /* Then if it's OK, the body. */
1088 if (!DECL_DECLARED_CONSTEXPR_P (fun)
1089 && DECL_DEFAULTED_FN (fun))
1090 explain_implicit_non_constexpr (fun);
1091 else
1093 if (constexpr_fundef *fd = retrieve_constexpr_fundef (fun))
1094 body = fd->body;
1095 else
1096 body = DECL_SAVED_TREE (fun);
1097 body = massage_constexpr_body (fun, body);
1098 require_potential_rvalue_constant_expression (body);
1099 if (DECL_CONSTRUCTOR_P (fun))
1100 cx_check_missing_mem_inits (DECL_CONTEXT (fun), body, true);
1105 /* Objects of this type represent calls to constexpr functions
1106 along with the bindings of parameters to their arguments, for
1107 the purpose of compile time evaluation. */
1109 struct GTY((for_user)) constexpr_call {
1110 /* Description of the constexpr function definition. */
1111 constexpr_fundef *fundef;
1112 /* Parameter bindings environment. A TREE_VEC of arguments. */
1113 tree bindings;
1114 /* Result of the call.
1115 NULL means the call is being evaluated.
1116 error_mark_node means that the evaluation was erroneous;
1117 otherwise, the actuall value of the call. */
1118 tree result;
1119 /* The hash of this call; we remember it here to avoid having to
1120 recalculate it when expanding the hash table. */
1121 hashval_t hash;
1122 /* Whether __builtin_is_constant_evaluated() should evaluate to true. */
1123 bool manifestly_const_eval;
1126 struct constexpr_call_hasher : ggc_ptr_hash<constexpr_call>
1128 static hashval_t hash (constexpr_call *);
1129 static bool equal (constexpr_call *, constexpr_call *);
1132 enum constexpr_switch_state {
1133 /* Used when processing a switch for the first time by cxx_eval_switch_expr
1134 and default: label for that switch has not been seen yet. */
1135 css_default_not_seen,
1136 /* Used when processing a switch for the first time by cxx_eval_switch_expr
1137 and default: label for that switch has been seen already. */
1138 css_default_seen,
1139 /* Used when processing a switch for the second time by
1140 cxx_eval_switch_expr, where default: label should match. */
1141 css_default_processing
1144 /* The constexpr expansion context part which needs one instance per
1145 cxx_eval_outermost_constant_expr invocation. VALUES is a map of values of
1146 variables initialized within the expression. */
1148 class constexpr_global_ctx {
1149 /* Values for any temporaries or local variables within the
1150 constant-expression. */
1151 hash_map<tree,tree> values;
1152 public:
1153 /* Number of cxx_eval_constant_expression calls (except skipped ones,
1154 on simple constants or location wrappers) encountered during current
1155 cxx_eval_outermost_constant_expr call. */
1156 HOST_WIDE_INT constexpr_ops_count;
1157 /* Heap VAR_DECLs created during the evaluation of the outermost constant
1158 expression. */
1159 auto_vec<tree, 16> heap_vars;
1160 /* Cleanups that need to be evaluated at the end of CLEANUP_POINT_EXPR. */
1161 vec<tree> *cleanups;
1162 /* If non-null, only allow modification of existing values of the variables
1163 in this set. Set by modifiable_tracker, below. */
1164 hash_set<tree> *modifiable;
1165 /* Number of heap VAR_DECL deallocations. */
1166 unsigned heap_dealloc_count;
1167 /* Constructor. */
1168 constexpr_global_ctx ()
1169 : constexpr_ops_count (0), cleanups (NULL), modifiable (nullptr),
1170 heap_dealloc_count (0) {}
1172 tree get_value (tree t)
1174 if (tree *p = values.get (t))
1175 return *p;
1176 return NULL_TREE;
1178 tree *get_value_ptr (tree t)
1180 if (modifiable && !modifiable->contains (t))
1181 return nullptr;
1182 return values.get (t);
1184 void put_value (tree t, tree v)
1186 bool already_in_map = values.put (t, v);
1187 if (!already_in_map && modifiable)
1188 modifiable->add (t);
1190 void remove_value (tree t) { values.remove (t); }
1193 /* Helper class for constexpr_global_ctx. In some cases we want to avoid
1194 side-effects from evaluation of a particular subexpression of a
1195 constant-expression. In such cases we use modifiable_tracker to prevent
1196 modification of variables created outside of that subexpression.
1198 ??? We could change the hash_set to a hash_map, allow and track external
1199 modifications, and roll them back in the destructor. It's not clear to me
1200 that this would be worthwhile. */
1202 class modifiable_tracker
1204 hash_set<tree> set;
1205 constexpr_global_ctx *global;
1206 public:
1207 modifiable_tracker (constexpr_global_ctx *g): global(g)
1209 global->modifiable = &set;
1211 ~modifiable_tracker ()
1213 for (tree t: set)
1214 global->remove_value (t);
1215 global->modifiable = nullptr;
1219 /* The constexpr expansion context. CALL is the current function
1220 expansion, CTOR is the current aggregate initializer, OBJECT is the
1221 object being initialized by CTOR, either a VAR_DECL or a _REF. */
1223 struct constexpr_ctx {
1224 /* The part of the context that needs to be unique to the whole
1225 cxx_eval_outermost_constant_expr invocation. */
1226 constexpr_global_ctx *global;
1227 /* The innermost call we're evaluating. */
1228 constexpr_call *call;
1229 /* SAVE_EXPRs and TARGET_EXPR_SLOT vars of TARGET_EXPRs that we've seen
1230 within the current LOOP_EXPR. NULL if we aren't inside a loop. */
1231 vec<tree> *save_exprs;
1232 /* The CONSTRUCTOR we're currently building up for an aggregate
1233 initializer. */
1234 tree ctor;
1235 /* The object we're building the CONSTRUCTOR for. */
1236 tree object;
1237 /* If inside SWITCH_EXPR. */
1238 constexpr_switch_state *css_state;
1239 /* The aggregate initialization context inside which this one is nested. This
1240 is used by lookup_placeholder to resolve PLACEHOLDER_EXPRs. */
1241 const constexpr_ctx *parent;
1243 /* Whether we should error on a non-constant expression or fail quietly.
1244 This flag needs to be here, but some of the others could move to global
1245 if they get larger than a word. */
1246 bool quiet;
1247 /* Whether we are strictly conforming to constant expression rules or
1248 trying harder to get a constant value. */
1249 bool strict;
1250 /* Whether __builtin_is_constant_evaluated () should be true. */
1251 bool manifestly_const_eval;
1254 /* This internal flag controls whether we should avoid doing anything during
1255 constexpr evaluation that would cause extra DECL_UID generation, such as
1256 template instantiation and function body copying. */
1258 static bool uid_sensitive_constexpr_evaluation_value;
1260 /* An internal counter that keeps track of the number of times
1261 uid_sensitive_constexpr_evaluation_p returned true. */
1263 static unsigned uid_sensitive_constexpr_evaluation_true_counter;
1265 /* The accessor for uid_sensitive_constexpr_evaluation_value which also
1266 increments the corresponding counter. */
1268 static bool
1269 uid_sensitive_constexpr_evaluation_p ()
1271 if (uid_sensitive_constexpr_evaluation_value)
1273 ++uid_sensitive_constexpr_evaluation_true_counter;
1274 return true;
1276 else
1277 return false;
1280 /* The default constructor for uid_sensitive_constexpr_evaluation_sentinel
1281 enables the internal flag for uid_sensitive_constexpr_evaluation_p
1282 during the lifetime of the sentinel object. Upon its destruction, the
1283 previous value of uid_sensitive_constexpr_evaluation_p is restored. */
1285 uid_sensitive_constexpr_evaluation_sentinel
1286 ::uid_sensitive_constexpr_evaluation_sentinel ()
1287 : ovr (uid_sensitive_constexpr_evaluation_value, true)
1291 /* The default constructor for uid_sensitive_constexpr_evaluation_checker
1292 records the current number of times that uid_sensitive_constexpr_evaluation_p
1293 has been called and returned true. */
1295 uid_sensitive_constexpr_evaluation_checker
1296 ::uid_sensitive_constexpr_evaluation_checker ()
1297 : saved_counter (uid_sensitive_constexpr_evaluation_true_counter)
1301 /* Returns true iff uid_sensitive_constexpr_evaluation_p is true, and
1302 some constexpr evaluation was restricted due to u_s_c_e_p being called
1303 and returning true during the lifetime of this checker object. */
1305 bool
1306 uid_sensitive_constexpr_evaluation_checker::evaluation_restricted_p () const
1308 return (uid_sensitive_constexpr_evaluation_value
1309 && saved_counter != uid_sensitive_constexpr_evaluation_true_counter);
1313 /* A table of all constexpr calls that have been evaluated by the
1314 compiler in this translation unit. */
1316 static GTY (()) hash_table<constexpr_call_hasher> *constexpr_call_table;
1318 /* Compute a hash value for a constexpr call representation. */
1320 inline hashval_t
1321 constexpr_call_hasher::hash (constexpr_call *info)
1323 return info->hash;
1326 /* Return true if the objects pointed to by P and Q represent calls
1327 to the same constexpr function with the same arguments.
1328 Otherwise, return false. */
1330 bool
1331 constexpr_call_hasher::equal (constexpr_call *lhs, constexpr_call *rhs)
1333 if (lhs == rhs)
1334 return true;
1335 if (lhs->hash != rhs->hash)
1336 return false;
1337 if (lhs->manifestly_const_eval != rhs->manifestly_const_eval)
1338 return false;
1339 if (!constexpr_fundef_hasher::equal (lhs->fundef, rhs->fundef))
1340 return false;
1341 return cp_tree_equal (lhs->bindings, rhs->bindings);
1344 /* Initialize the constexpr call table, if needed. */
1346 static void
1347 maybe_initialize_constexpr_call_table (void)
1349 if (constexpr_call_table == NULL)
1350 constexpr_call_table = hash_table<constexpr_call_hasher>::create_ggc (101);
1353 /* During constexpr CALL_EXPR evaluation, to avoid issues with sharing when
1354 a function happens to get called recursively, we unshare the callee
1355 function's body and evaluate this unshared copy instead of evaluating the
1356 original body.
1358 FUNDEF_COPIES_TABLE is a per-function freelist of these unshared function
1359 copies. The underlying data structure of FUNDEF_COPIES_TABLE is a hash_map
1360 that's keyed off of the original FUNCTION_DECL and whose value is a
1361 TREE_LIST of this function's unused copies awaiting reuse.
1363 This is not GC-deletable to avoid GC affecting UID generation. */
1365 static GTY(()) decl_tree_map *fundef_copies_table;
1367 /* Reuse a copy or create a new unshared copy of the function FUN.
1368 Return this copy. We use a TREE_LIST whose PURPOSE is body, VALUE
1369 is parms, TYPE is result. */
1371 static tree
1372 get_fundef_copy (constexpr_fundef *fundef)
1374 tree copy;
1375 bool existed;
1376 tree *slot = &(hash_map_safe_get_or_insert<hm_ggc>
1377 (fundef_copies_table, fundef->decl, &existed, 127));
1379 if (!existed)
1381 /* There is no cached function available, or in use. We can use
1382 the function directly. That the slot is now created records
1383 that this function is now in use. */
1384 copy = build_tree_list (fundef->body, fundef->parms);
1385 TREE_TYPE (copy) = fundef->result;
1387 else if (*slot == NULL_TREE)
1389 if (uid_sensitive_constexpr_evaluation_p ())
1390 return NULL_TREE;
1392 /* We've already used the function itself, so make a copy. */
1393 copy = build_tree_list (NULL, NULL);
1394 tree saved_body = DECL_SAVED_TREE (fundef->decl);
1395 tree saved_parms = DECL_ARGUMENTS (fundef->decl);
1396 tree saved_result = DECL_RESULT (fundef->decl);
1397 tree saved_fn = current_function_decl;
1398 DECL_SAVED_TREE (fundef->decl) = fundef->body;
1399 DECL_ARGUMENTS (fundef->decl) = fundef->parms;
1400 DECL_RESULT (fundef->decl) = fundef->result;
1401 current_function_decl = fundef->decl;
1402 TREE_PURPOSE (copy) = copy_fn (fundef->decl, TREE_VALUE (copy),
1403 TREE_TYPE (copy));
1404 current_function_decl = saved_fn;
1405 DECL_RESULT (fundef->decl) = saved_result;
1406 DECL_ARGUMENTS (fundef->decl) = saved_parms;
1407 DECL_SAVED_TREE (fundef->decl) = saved_body;
1409 else
1411 /* We have a cached function available. */
1412 copy = *slot;
1413 *slot = TREE_CHAIN (copy);
1416 return copy;
1419 /* Save the copy COPY of function FUN for later reuse by
1420 get_fundef_copy(). By construction, there will always be an entry
1421 to find. */
1423 static void
1424 save_fundef_copy (tree fun, tree copy)
1426 tree *slot = fundef_copies_table->get (fun);
1427 TREE_CHAIN (copy) = *slot;
1428 *slot = copy;
1431 /* Whether our evaluation wants a prvalue (e.g. CONSTRUCTOR or _CST),
1432 a glvalue (e.g. VAR_DECL or _REF), or nothing. */
1434 enum value_cat {
1435 vc_prvalue = 0,
1436 vc_glvalue = 1,
1437 vc_discard = 2
1440 static tree cxx_eval_constant_expression (const constexpr_ctx *, tree,
1441 value_cat, bool *, bool *, tree * = NULL);
1442 static tree cxx_fold_indirect_ref (const constexpr_ctx *, location_t, tree, tree,
1443 bool * = NULL);
1444 static tree find_heap_var_refs (tree *, int *, void *);
1446 /* Attempt to evaluate T which represents a call to a builtin function.
1447 We assume here that all builtin functions evaluate to scalar types
1448 represented by _CST nodes. */
1450 static tree
1451 cxx_eval_builtin_function_call (const constexpr_ctx *ctx, tree t, tree fun,
1452 value_cat lval,
1453 bool *non_constant_p, bool *overflow_p)
1455 const int nargs = call_expr_nargs (t);
1456 tree *args = (tree *) alloca (nargs * sizeof (tree));
1457 tree new_call;
1458 int i;
1460 /* Don't fold __builtin_constant_p within a constexpr function. */
1461 bool bi_const_p = DECL_IS_BUILTIN_CONSTANT_P (fun);
1463 /* If we aren't requiring a constant expression, defer __builtin_constant_p
1464 in a constexpr function until we have values for the parameters. */
1465 if (bi_const_p
1466 && !ctx->manifestly_const_eval
1467 && current_function_decl
1468 && DECL_DECLARED_CONSTEXPR_P (current_function_decl))
1470 *non_constant_p = true;
1471 return t;
1474 /* For __builtin_is_constant_evaluated, defer it if not
1475 ctx->manifestly_const_eval (as sometimes we try to constant evaluate
1476 without manifestly_const_eval even expressions or parts thereof which
1477 will later be manifestly const_eval evaluated), otherwise fold it to
1478 true. */
1479 if (fndecl_built_in_p (fun, CP_BUILT_IN_IS_CONSTANT_EVALUATED,
1480 BUILT_IN_FRONTEND))
1482 if (!ctx->manifestly_const_eval)
1484 *non_constant_p = true;
1485 return t;
1487 return boolean_true_node;
1490 if (fndecl_built_in_p (fun, CP_BUILT_IN_SOURCE_LOCATION, BUILT_IN_FRONTEND))
1492 temp_override<tree> ovr (current_function_decl);
1493 if (ctx->call && ctx->call->fundef)
1494 current_function_decl = ctx->call->fundef->decl;
1495 return fold_builtin_source_location (EXPR_LOCATION (t));
1498 int strops = 0;
1499 int strret = 0;
1500 if (fndecl_built_in_p (fun, BUILT_IN_NORMAL))
1501 switch (DECL_FUNCTION_CODE (fun))
1503 case BUILT_IN_STRLEN:
1504 case BUILT_IN_STRNLEN:
1505 strops = 1;
1506 break;
1507 case BUILT_IN_MEMCHR:
1508 case BUILT_IN_STRCHR:
1509 case BUILT_IN_STRRCHR:
1510 strops = 1;
1511 strret = 1;
1512 break;
1513 case BUILT_IN_MEMCMP:
1514 case BUILT_IN_STRCMP:
1515 strops = 2;
1516 break;
1517 case BUILT_IN_STRSTR:
1518 strops = 2;
1519 strret = 1;
1520 break;
1521 case BUILT_IN_ASAN_POINTER_COMPARE:
1522 case BUILT_IN_ASAN_POINTER_SUBTRACT:
1523 /* These builtins shall be ignored during constant expression
1524 evaluation. */
1525 return void_node;
1526 case BUILT_IN_UNREACHABLE:
1527 case BUILT_IN_TRAP:
1528 if (!*non_constant_p && !ctx->quiet)
1530 /* Do not allow__builtin_unreachable in constexpr function.
1531 The __builtin_unreachable call with BUILTINS_LOCATION
1532 comes from cp_maybe_instrument_return. */
1533 if (EXPR_LOCATION (t) == BUILTINS_LOCATION)
1534 error ("%<constexpr%> call flows off the end of the function");
1535 else
1536 error ("%q+E is not a constant expression", t);
1538 *non_constant_p = true;
1539 return t;
1540 default:
1541 break;
1544 /* Be permissive for arguments to built-ins; __builtin_constant_p should
1545 return constant false for a non-constant argument. */
1546 constexpr_ctx new_ctx = *ctx;
1547 new_ctx.quiet = true;
1548 for (i = 0; i < nargs; ++i)
1550 tree arg = CALL_EXPR_ARG (t, i);
1551 tree oarg = arg;
1553 /* To handle string built-ins we need to pass ADDR_EXPR<STRING_CST> since
1554 expand_builtin doesn't know how to look in the values table. */
1555 bool strop = i < strops;
1556 if (strop)
1558 STRIP_NOPS (arg);
1559 if (TREE_CODE (arg) == ADDR_EXPR)
1560 arg = TREE_OPERAND (arg, 0);
1561 else
1562 strop = false;
1565 /* If builtin_valid_in_constant_expr_p is true,
1566 potential_constant_expression_1 has not recursed into the arguments
1567 of the builtin, verify it here. */
1568 if (!builtin_valid_in_constant_expr_p (fun)
1569 || potential_constant_expression (arg))
1571 bool dummy1 = false, dummy2 = false;
1572 arg = cxx_eval_constant_expression (&new_ctx, arg, vc_prvalue,
1573 &dummy1, &dummy2);
1576 if (bi_const_p)
1577 /* For __builtin_constant_p, fold all expressions with constant values
1578 even if they aren't C++ constant-expressions. */
1579 arg = cp_fold_rvalue (arg);
1580 else if (strop)
1582 if (TREE_CODE (arg) == CONSTRUCTOR)
1583 arg = braced_lists_to_strings (TREE_TYPE (arg), arg);
1584 if (TREE_CODE (arg) == STRING_CST)
1585 arg = build_address (arg);
1586 else
1587 arg = oarg;
1590 args[i] = arg;
1593 bool save_ffbcp = force_folding_builtin_constant_p;
1594 force_folding_builtin_constant_p |= ctx->manifestly_const_eval;
1595 tree save_cur_fn = current_function_decl;
1596 /* Return name of ctx->call->fundef->decl for __builtin_FUNCTION (). */
1597 if (fndecl_built_in_p (fun, BUILT_IN_FUNCTION)
1598 && ctx->call
1599 && ctx->call->fundef)
1600 current_function_decl = ctx->call->fundef->decl;
1601 if (fndecl_built_in_p (fun,
1602 CP_BUILT_IN_IS_POINTER_INTERCONVERTIBLE_WITH_CLASS,
1603 BUILT_IN_FRONTEND))
1605 location_t loc = EXPR_LOCATION (t);
1606 if (nargs >= 1)
1607 VERIFY_CONSTANT (args[0]);
1608 new_call
1609 = fold_builtin_is_pointer_inverconvertible_with_class (loc, nargs,
1610 args);
1612 else if (fndecl_built_in_p (fun,
1613 CP_BUILT_IN_IS_CORRESPONDING_MEMBER,
1614 BUILT_IN_FRONTEND))
1616 location_t loc = EXPR_LOCATION (t);
1617 if (nargs >= 2)
1619 VERIFY_CONSTANT (args[0]);
1620 VERIFY_CONSTANT (args[1]);
1622 new_call = fold_builtin_is_corresponding_member (loc, nargs, args);
1624 else
1625 new_call = fold_builtin_call_array (EXPR_LOCATION (t), TREE_TYPE (t),
1626 CALL_EXPR_FN (t), nargs, args);
1627 current_function_decl = save_cur_fn;
1628 force_folding_builtin_constant_p = save_ffbcp;
1629 if (new_call == NULL)
1631 if (!*non_constant_p && !ctx->quiet)
1633 new_call = build_call_array_loc (EXPR_LOCATION (t), TREE_TYPE (t),
1634 CALL_EXPR_FN (t), nargs, args);
1635 error ("%q+E is not a constant expression", new_call);
1637 *non_constant_p = true;
1638 return t;
1641 if (!potential_constant_expression (new_call))
1643 if (!*non_constant_p && !ctx->quiet)
1644 error ("%q+E is not a constant expression", new_call);
1645 *non_constant_p = true;
1646 return t;
1649 if (strret)
1651 /* memchr returns a pointer into the first argument, but we replaced the
1652 argument above with a STRING_CST; put it back it now. */
1653 tree op = CALL_EXPR_ARG (t, strret-1);
1654 STRIP_NOPS (new_call);
1655 if (TREE_CODE (new_call) == POINTER_PLUS_EXPR)
1656 TREE_OPERAND (new_call, 0) = op;
1657 else if (TREE_CODE (new_call) == ADDR_EXPR)
1658 new_call = op;
1661 return cxx_eval_constant_expression (&new_ctx, new_call, lval,
1662 non_constant_p, overflow_p);
1665 /* TEMP is the constant value of a temporary object of type TYPE. Adjust
1666 the type of the value to match. */
1668 static tree
1669 adjust_temp_type (tree type, tree temp)
1671 if (same_type_p (TREE_TYPE (temp), type))
1672 return temp;
1673 /* Avoid wrapping an aggregate value in a NOP_EXPR. */
1674 if (TREE_CODE (temp) == CONSTRUCTOR)
1676 /* build_constructor wouldn't retain various CONSTRUCTOR flags. */
1677 tree t = copy_node (temp);
1678 TREE_TYPE (t) = type;
1679 return t;
1681 if (TREE_CODE (temp) == EMPTY_CLASS_EXPR)
1682 return build0 (EMPTY_CLASS_EXPR, type);
1683 gcc_assert (scalarish_type_p (type));
1684 /* Now we know we're dealing with a scalar, and a prvalue of non-class
1685 type is cv-unqualified. */
1686 return cp_fold_convert (cv_unqualified (type), temp);
1689 /* If T is a CONSTRUCTOR, return an unshared copy of T and any
1690 sub-CONSTRUCTORs. Otherwise return T.
1692 We use this whenever we initialize an object as a whole, whether it's a
1693 parameter, a local variable, or a subobject, so that subsequent
1694 modifications don't affect other places where it was used. */
1696 tree
1697 unshare_constructor (tree t MEM_STAT_DECL)
1699 if (!t || TREE_CODE (t) != CONSTRUCTOR)
1700 return t;
1701 auto_vec <tree*, 4> ptrs;
1702 ptrs.safe_push (&t);
1703 while (!ptrs.is_empty ())
1705 tree *p = ptrs.pop ();
1706 tree n = copy_node (*p PASS_MEM_STAT);
1707 CONSTRUCTOR_ELTS (n) = vec_safe_copy (CONSTRUCTOR_ELTS (*p) PASS_MEM_STAT);
1708 *p = n;
1709 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (n);
1710 constructor_elt *ce;
1711 for (HOST_WIDE_INT i = 0; vec_safe_iterate (v, i, &ce); ++i)
1712 if (ce->value && TREE_CODE (ce->value) == CONSTRUCTOR)
1713 ptrs.safe_push (&ce->value);
1715 return t;
1718 /* If T is a CONSTRUCTOR, ggc_free T and any sub-CONSTRUCTORs. */
1720 static void
1721 free_constructor (tree t)
1723 if (!t || TREE_CODE (t) != CONSTRUCTOR)
1724 return;
1725 releasing_vec ctors;
1726 vec_safe_push (ctors, t);
1727 while (!ctors->is_empty ())
1729 tree c = ctors->pop ();
1730 if (vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (c))
1732 constructor_elt *ce;
1733 for (HOST_WIDE_INT i = 0; vec_safe_iterate (elts, i, &ce); ++i)
1734 if (TREE_CODE (ce->value) == CONSTRUCTOR)
1735 vec_safe_push (ctors, ce->value);
1736 ggc_free (elts);
1738 ggc_free (c);
1742 /* Helper function of cxx_bind_parameters_in_call. Return non-NULL
1743 if *TP is address of a static variable (or part of it) currently being
1744 constructed or of a heap artificial variable. */
1746 static tree
1747 addr_of_non_const_var (tree *tp, int *walk_subtrees, void *data)
1749 if (TREE_CODE (*tp) == ADDR_EXPR)
1750 if (tree var = get_base_address (TREE_OPERAND (*tp, 0)))
1751 if (VAR_P (var) && TREE_STATIC (var))
1753 if (DECL_NAME (var) == heap_uninit_identifier
1754 || DECL_NAME (var) == heap_identifier
1755 || DECL_NAME (var) == heap_vec_uninit_identifier
1756 || DECL_NAME (var) == heap_vec_identifier)
1757 return var;
1759 constexpr_global_ctx *global = (constexpr_global_ctx *) data;
1760 if (global->get_value (var))
1761 return var;
1763 if (TYPE_P (*tp))
1764 *walk_subtrees = false;
1765 return NULL_TREE;
1768 /* Subroutine of cxx_eval_call_expression.
1769 We are processing a call expression (either CALL_EXPR or
1770 AGGR_INIT_EXPR) in the context of CTX. Evaluate
1771 all arguments and bind their values to correspondings
1772 parameters, making up the NEW_CALL context. */
1774 static tree
1775 cxx_bind_parameters_in_call (const constexpr_ctx *ctx, tree t, tree fun,
1776 bool *non_constant_p, bool *overflow_p,
1777 bool *non_constant_args)
1779 const int nargs = call_expr_nargs (t);
1780 tree parms = DECL_ARGUMENTS (fun);
1781 int i;
1782 /* We don't record ellipsis args below. */
1783 int nparms = list_length (parms);
1784 int nbinds = nargs < nparms ? nargs : nparms;
1785 tree binds = make_tree_vec (nbinds);
1786 for (i = 0; i < nargs; ++i)
1788 tree x, arg;
1789 tree type = parms ? TREE_TYPE (parms) : void_type_node;
1790 if (parms && DECL_BY_REFERENCE (parms))
1791 type = TREE_TYPE (type);
1792 x = get_nth_callarg (t, i);
1793 /* For member function, the first argument is a pointer to the implied
1794 object. For a constructor, it might still be a dummy object, in
1795 which case we get the real argument from ctx. */
1796 if (i == 0 && DECL_CONSTRUCTOR_P (fun)
1797 && is_dummy_object (x))
1799 x = ctx->object;
1800 x = build_address (x);
1802 if (TREE_ADDRESSABLE (type))
1803 /* Undo convert_for_arg_passing work here. */
1804 x = convert_from_reference (x);
1805 /* Normally we would strip a TARGET_EXPR in an initialization context
1806 such as this, but here we do the elision differently: we keep the
1807 TARGET_EXPR, and use its CONSTRUCTOR as the value of the parm. */
1808 arg = cxx_eval_constant_expression (ctx, x, vc_prvalue,
1809 non_constant_p, overflow_p);
1810 /* Don't VERIFY_CONSTANT here. */
1811 if (*non_constant_p && ctx->quiet)
1812 break;
1813 /* Just discard ellipsis args after checking their constantitude. */
1814 if (!parms)
1815 continue;
1817 if (!*non_constant_p)
1819 /* Make sure the binding has the same type as the parm. But
1820 only for constant args. */
1821 if (!TYPE_REF_P (type))
1822 arg = adjust_temp_type (type, arg);
1823 if (!TREE_CONSTANT (arg))
1824 *non_constant_args = true;
1825 else if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
1826 /* The destructor needs to see any modifications the callee makes
1827 to the argument. */
1828 *non_constant_args = true;
1829 /* If arg is or contains address of a heap artificial variable or
1830 of a static variable being constructed, avoid caching the
1831 function call, as those variables might be modified by the
1832 function, or might be modified by the callers in between
1833 the cached function and just read by the function. */
1834 else if (!*non_constant_args
1835 && cp_walk_tree (&arg, addr_of_non_const_var, ctx->global,
1836 NULL))
1837 *non_constant_args = true;
1839 /* For virtual calls, adjust the this argument, so that it is
1840 the object on which the method is called, rather than
1841 one of its bases. */
1842 if (i == 0 && DECL_VIRTUAL_P (fun))
1844 tree addr = arg;
1845 STRIP_NOPS (addr);
1846 if (TREE_CODE (addr) == ADDR_EXPR)
1848 tree obj = TREE_OPERAND (addr, 0);
1849 while (TREE_CODE (obj) == COMPONENT_REF
1850 && DECL_FIELD_IS_BASE (TREE_OPERAND (obj, 1))
1851 && !same_type_ignoring_top_level_qualifiers_p
1852 (TREE_TYPE (obj), DECL_CONTEXT (fun)))
1853 obj = TREE_OPERAND (obj, 0);
1854 if (obj != TREE_OPERAND (addr, 0))
1855 arg = build_fold_addr_expr_with_type (obj,
1856 TREE_TYPE (arg));
1859 TREE_VEC_ELT (binds, i) = arg;
1861 parms = TREE_CHAIN (parms);
1864 return binds;
1867 /* Variables and functions to manage constexpr call expansion context.
1868 These do not need to be marked for PCH or GC. */
1870 /* FIXME remember and print actual constant arguments. */
1871 static vec<tree> call_stack;
1872 static int call_stack_tick;
1873 static int last_cx_error_tick;
1875 static int
1876 push_cx_call_context (tree call)
1878 ++call_stack_tick;
1879 if (!EXPR_HAS_LOCATION (call))
1880 SET_EXPR_LOCATION (call, input_location);
1881 call_stack.safe_push (call);
1882 int len = call_stack.length ();
1883 if (len > max_constexpr_depth)
1884 return false;
1885 return len;
1888 static void
1889 pop_cx_call_context (void)
1891 ++call_stack_tick;
1892 call_stack.pop ();
1895 vec<tree>
1896 cx_error_context (void)
1898 vec<tree> r = vNULL;
1899 if (call_stack_tick != last_cx_error_tick
1900 && !call_stack.is_empty ())
1901 r = call_stack;
1902 last_cx_error_tick = call_stack_tick;
1903 return r;
1906 /* E is an operand of a failed assertion, fold it either with or without
1907 constexpr context. */
1909 static tree
1910 fold_operand (tree e, const constexpr_ctx *ctx)
1912 if (ctx)
1914 bool new_non_constant_p = false, new_overflow_p = false;
1915 e = cxx_eval_constant_expression (ctx, e, vc_prvalue,
1916 &new_non_constant_p,
1917 &new_overflow_p);
1919 else
1920 e = fold_non_dependent_expr (e, tf_none, /*manifestly_const_eval=*/true);
1921 return e;
1924 /* If we have a condition in conjunctive normal form (CNF), find the first
1925 failing clause. In other words, given an expression like
1927 true && true && false && true && false
1929 return the first 'false'. EXPR is the expression. */
1931 static tree
1932 find_failing_clause_r (const constexpr_ctx *ctx, tree expr)
1934 if (TREE_CODE (expr) == TRUTH_ANDIF_EXPR)
1936 /* First check the left side... */
1937 tree e = find_failing_clause_r (ctx, TREE_OPERAND (expr, 0));
1938 if (e == NULL_TREE)
1939 /* ...if we didn't find a false clause, check the right side. */
1940 e = find_failing_clause_r (ctx, TREE_OPERAND (expr, 1));
1941 return e;
1943 tree e = contextual_conv_bool (expr, tf_none);
1944 e = fold_operand (e, ctx);
1945 if (integer_zerop (e))
1946 /* This is the failing clause. */
1947 return expr;
1948 return NULL_TREE;
1951 /* Wrapper for find_failing_clause_r. */
1953 tree
1954 find_failing_clause (const constexpr_ctx *ctx, tree expr)
1956 if (TREE_CODE (expr) == TRUTH_ANDIF_EXPR)
1957 if (tree e = find_failing_clause_r (ctx, expr))
1958 expr = e;
1959 return expr;
1962 /* Emit additional diagnostics for failing condition BAD.
1963 Used by finish_static_assert and IFN_ASSUME constexpr diagnostics.
1964 If SHOW_EXPR_P is true, print the condition (because it was
1965 instantiation-dependent). */
1967 void
1968 diagnose_failing_condition (tree bad, location_t cloc, bool show_expr_p,
1969 const constexpr_ctx *ctx /* = nullptr */)
1971 /* Nobody wants to see the artificial (bool) cast. */
1972 bad = tree_strip_nop_conversions (bad);
1973 if (TREE_CODE (bad) == CLEANUP_POINT_EXPR)
1974 bad = TREE_OPERAND (bad, 0);
1976 /* Actually explain the failure if this is a concept check or a
1977 requires-expression. */
1978 if (concept_check_p (bad) || TREE_CODE (bad) == REQUIRES_EXPR)
1979 diagnose_constraints (cloc, bad, NULL_TREE);
1980 else if (COMPARISON_CLASS_P (bad)
1981 && ARITHMETIC_TYPE_P (TREE_TYPE (TREE_OPERAND (bad, 0))))
1983 tree op0 = fold_operand (TREE_OPERAND (bad, 0), ctx);
1984 tree op1 = fold_operand (TREE_OPERAND (bad, 1), ctx);
1985 tree cond = build2 (TREE_CODE (bad), boolean_type_node, op0, op1);
1986 inform (cloc, "the comparison reduces to %qE", cond);
1988 else if (show_expr_p)
1989 inform (cloc, "%qE evaluates to false", bad);
1992 /* Process an assert/assume of ORIG_ARG. If it's not supposed to be evaluated,
1993 do it without changing the current evaluation state. If it evaluates to
1994 false, complain and return false; otherwise, return true. */
1996 static bool
1997 cxx_eval_assert (const constexpr_ctx *ctx, tree arg, const char *msg,
1998 location_t loc, bool evaluated,
1999 bool *non_constant_p, bool *overflow_p)
2001 if (*non_constant_p)
2002 return true;
2004 tree eval;
2005 if (!evaluated)
2007 if (!potential_rvalue_constant_expression (arg))
2008 return true;
2010 constexpr_ctx new_ctx = *ctx;
2011 new_ctx.quiet = true;
2012 bool new_non_constant_p = false, new_overflow_p = false;
2013 /* Avoid modification of existing values. */
2014 modifiable_tracker ms (new_ctx.global);
2015 eval = cxx_eval_constant_expression (&new_ctx, arg, vc_prvalue,
2016 &new_non_constant_p,
2017 &new_overflow_p);
2019 else
2020 eval = cxx_eval_constant_expression (ctx, arg, vc_prvalue,
2021 non_constant_p,
2022 overflow_p);
2023 if (!*non_constant_p && integer_zerop (eval))
2025 if (!ctx->quiet)
2027 /* See if we can find which clause was failing
2028 (for logical AND). */
2029 tree bad = find_failing_clause (ctx, arg);
2030 /* If not, or its location is unusable, fall back to the
2031 previous location. */
2032 location_t cloc = cp_expr_loc_or_loc (bad, loc);
2034 /* Report the error. */
2035 auto_diagnostic_group d;
2036 error_at (cloc, msg);
2037 diagnose_failing_condition (bad, cloc, true, ctx);
2038 return bad;
2040 *non_constant_p = true;
2041 return false;
2044 return true;
2047 /* Evaluate a call T to a GCC internal function when possible and return
2048 the evaluated result or, under the control of CTX, give an error, set
2049 NON_CONSTANT_P, and return the unevaluated call T otherwise. */
2051 static tree
2052 cxx_eval_internal_function (const constexpr_ctx *ctx, tree t,
2053 value_cat lval,
2054 bool *non_constant_p, bool *overflow_p)
2056 enum tree_code opcode = ERROR_MARK;
2058 switch (CALL_EXPR_IFN (t))
2060 case IFN_UBSAN_NULL:
2061 case IFN_UBSAN_BOUNDS:
2062 case IFN_UBSAN_VPTR:
2063 case IFN_FALLTHROUGH:
2064 return void_node;
2066 case IFN_ASSUME:
2067 if (!cxx_eval_assert (ctx, CALL_EXPR_ARG (t, 0),
2068 G_("failed %<assume%> attribute assumption"),
2069 EXPR_LOCATION (t), /*eval*/false,
2070 non_constant_p, overflow_p))
2071 return t;
2072 return void_node;
2074 case IFN_ADD_OVERFLOW:
2075 opcode = PLUS_EXPR;
2076 break;
2077 case IFN_SUB_OVERFLOW:
2078 opcode = MINUS_EXPR;
2079 break;
2080 case IFN_MUL_OVERFLOW:
2081 opcode = MULT_EXPR;
2082 break;
2084 case IFN_LAUNDER:
2085 return cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0),
2086 vc_prvalue, non_constant_p,
2087 overflow_p);
2089 case IFN_VEC_CONVERT:
2091 tree arg = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0),
2092 vc_prvalue, non_constant_p,
2093 overflow_p);
2094 if (TREE_CODE (arg) == VECTOR_CST)
2095 if (tree r = fold_const_call (CFN_VEC_CONVERT, TREE_TYPE (t), arg))
2096 return r;
2098 /* FALLTHRU */
2100 default:
2101 if (!ctx->quiet)
2102 error_at (cp_expr_loc_or_input_loc (t),
2103 "call to internal function %qE", t);
2104 *non_constant_p = true;
2105 return t;
2108 /* Evaluate constant arguments using OPCODE and return a complex
2109 number containing the result and the overflow bit. */
2110 tree arg0 = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0), lval,
2111 non_constant_p, overflow_p);
2112 tree arg1 = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 1), lval,
2113 non_constant_p, overflow_p);
2115 if (TREE_CODE (arg0) == INTEGER_CST && TREE_CODE (arg1) == INTEGER_CST)
2117 location_t loc = cp_expr_loc_or_input_loc (t);
2118 tree type = TREE_TYPE (TREE_TYPE (t));
2119 tree result = fold_binary_loc (loc, opcode, type,
2120 fold_convert_loc (loc, type, arg0),
2121 fold_convert_loc (loc, type, arg1));
2122 tree ovf
2123 = build_int_cst (type, arith_overflowed_p (opcode, type, arg0, arg1));
2124 /* Reset TREE_OVERFLOW to avoid warnings for the overflow. */
2125 if (TREE_OVERFLOW (result))
2126 TREE_OVERFLOW (result) = 0;
2128 return build_complex (TREE_TYPE (t), result, ovf);
2131 *non_constant_p = true;
2132 return t;
2135 /* Clean CONSTRUCTOR_NO_CLEARING from CTOR and its sub-aggregates. */
2137 static void
2138 clear_no_implicit_zero (tree ctor)
2140 if (CONSTRUCTOR_NO_CLEARING (ctor))
2142 CONSTRUCTOR_NO_CLEARING (ctor) = false;
2143 for (auto &e: CONSTRUCTOR_ELTS (ctor))
2144 if (TREE_CODE (e.value) == CONSTRUCTOR)
2145 clear_no_implicit_zero (e.value);
2149 /* Complain about a const object OBJ being modified in a constant expression.
2150 EXPR is the MODIFY_EXPR expression performing the modification. */
2152 static void
2153 modifying_const_object_error (tree expr, tree obj)
2155 location_t loc = cp_expr_loc_or_input_loc (expr);
2156 auto_diagnostic_group d;
2157 error_at (loc, "modifying a const object %qE is not allowed in "
2158 "a constant expression", TREE_OPERAND (expr, 0));
2159 inform (location_of (obj), "originally declared %<const%> here");
2162 /* Return true if FNDECL is a replaceable global allocation function that
2163 should be useable during constant expression evaluation. */
2165 static inline bool
2166 cxx_replaceable_global_alloc_fn (tree fndecl)
2168 return (cxx_dialect >= cxx20
2169 && IDENTIFIER_NEWDEL_OP_P (DECL_NAME (fndecl))
2170 && CP_DECL_CONTEXT (fndecl) == global_namespace
2171 && (DECL_IS_REPLACEABLE_OPERATOR_NEW_P (fndecl)
2172 || DECL_IS_OPERATOR_DELETE_P (fndecl)));
2175 /* Return true if FNDECL is a placement new function that should be
2176 useable during constant expression evaluation of std::construct_at. */
2178 static inline bool
2179 cxx_placement_new_fn (tree fndecl)
2181 if (cxx_dialect >= cxx20
2182 && IDENTIFIER_NEW_OP_P (DECL_NAME (fndecl))
2183 && CP_DECL_CONTEXT (fndecl) == global_namespace
2184 && !DECL_IS_REPLACEABLE_OPERATOR_NEW_P (fndecl)
2185 && TREE_CODE (TREE_TYPE (fndecl)) == FUNCTION_TYPE)
2187 tree first_arg = TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (fndecl)));
2188 if (TREE_VALUE (first_arg) == ptr_type_node
2189 && TREE_CHAIN (first_arg) == void_list_node)
2190 return true;
2192 return false;
2195 /* Return true if FNDECL is std::construct_at. */
2197 static inline bool
2198 is_std_construct_at (tree fndecl)
2200 if (!decl_in_std_namespace_p (fndecl))
2201 return false;
2203 tree name = DECL_NAME (fndecl);
2204 return name && id_equal (name, "construct_at");
2207 /* Overload for the above taking constexpr_call*. */
2209 static inline bool
2210 is_std_construct_at (const constexpr_call *call)
2212 return (call
2213 && call->fundef
2214 && is_std_construct_at (call->fundef->decl));
2217 /* True if CTX is an instance of std::allocator. */
2219 bool
2220 is_std_allocator (tree ctx)
2222 if (ctx == NULL_TREE || !CLASS_TYPE_P (ctx) || !TYPE_MAIN_DECL (ctx))
2223 return false;
2225 tree decl = TYPE_MAIN_DECL (ctx);
2226 tree name = DECL_NAME (decl);
2227 if (name == NULL_TREE || !id_equal (name, "allocator"))
2228 return false;
2230 return decl_in_std_namespace_p (decl);
2233 /* Return true if FNDECL is std::allocator<T>::{,de}allocate. */
2235 static inline bool
2236 is_std_allocator_allocate (tree fndecl)
2238 tree name = DECL_NAME (fndecl);
2239 if (name == NULL_TREE
2240 || !(id_equal (name, "allocate") || id_equal (name, "deallocate")))
2241 return false;
2243 return is_std_allocator (DECL_CONTEXT (fndecl));
2246 /* Overload for the above taking constexpr_call*. */
2248 static inline bool
2249 is_std_allocator_allocate (const constexpr_call *call)
2251 return (call
2252 && call->fundef
2253 && is_std_allocator_allocate (call->fundef->decl));
2256 /* Return true if FNDECL is __dynamic_cast. */
2258 static inline bool
2259 cxx_dynamic_cast_fn_p (tree fndecl)
2261 return (cxx_dialect >= cxx20
2262 && id_equal (DECL_NAME (fndecl), "__dynamic_cast")
2263 && CP_DECL_CONTEXT (fndecl) == abi_node);
2266 /* Often, we have an expression in the form of address + offset, e.g.
2267 "&_ZTV1A + 16". Extract the object from it, i.e. "_ZTV1A". */
2269 static tree
2270 extract_obj_from_addr_offset (tree expr)
2272 if (TREE_CODE (expr) == POINTER_PLUS_EXPR)
2273 expr = TREE_OPERAND (expr, 0);
2274 STRIP_NOPS (expr);
2275 if (TREE_CODE (expr) == ADDR_EXPR)
2276 expr = TREE_OPERAND (expr, 0);
2277 return expr;
2280 /* Given a PATH like
2282 g.D.2181.D.2154.D.2102.D.2093
2284 find a component with type TYPE. Return NULL_TREE if not found, and
2285 error_mark_node if the component is not accessible. If STOP is non-null,
2286 this function will return NULL_TREE if STOP is found before TYPE. */
2288 static tree
2289 get_component_with_type (tree path, tree type, tree stop)
2291 while (true)
2293 if (same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (path), type))
2294 /* Found it. */
2295 return path;
2296 else if (stop
2297 && (same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (path),
2298 stop)))
2299 return NULL_TREE;
2300 else if (TREE_CODE (path) == COMPONENT_REF
2301 && DECL_FIELD_IS_BASE (TREE_OPERAND (path, 1)))
2303 /* We need to check that the component we're accessing is in fact
2304 accessible. */
2305 if (TREE_PRIVATE (TREE_OPERAND (path, 1))
2306 || TREE_PROTECTED (TREE_OPERAND (path, 1)))
2307 return error_mark_node;
2308 path = TREE_OPERAND (path, 0);
2310 else
2311 return NULL_TREE;
2315 /* Evaluate a call to __dynamic_cast (permitted by P1327R1).
2317 The declaration of __dynamic_cast is:
2319 void* __dynamic_cast (const void* __src_ptr,
2320 const __class_type_info* __src_type,
2321 const __class_type_info* __dst_type,
2322 ptrdiff_t __src2dst);
2324 where src2dst has the following possible values
2326 >-1: src_type is a unique public non-virtual base of dst_type
2327 dst_ptr + src2dst == src_ptr
2328 -1: unspecified relationship
2329 -2: src_type is not a public base of dst_type
2330 -3: src_type is a multiple public non-virtual base of dst_type
2332 Since literal types can't have virtual bases, we only expect hint >=0,
2333 -2, or -3. */
2335 static tree
2336 cxx_eval_dynamic_cast_fn (const constexpr_ctx *ctx, tree call,
2337 bool *non_constant_p, bool *overflow_p)
2339 /* T will be something like
2340 __dynamic_cast ((B*) b, &_ZTI1B, &_ZTI1D, 8)
2341 dismantle it. */
2342 gcc_assert (call_expr_nargs (call) == 4);
2343 tsubst_flags_t complain = ctx->quiet ? tf_none : tf_warning_or_error;
2344 tree obj = CALL_EXPR_ARG (call, 0);
2345 tree type = CALL_EXPR_ARG (call, 2);
2346 HOST_WIDE_INT hint = int_cst_value (CALL_EXPR_ARG (call, 3));
2347 location_t loc = cp_expr_loc_or_input_loc (call);
2349 /* Get the target type of the dynamic_cast. */
2350 gcc_assert (TREE_CODE (type) == ADDR_EXPR);
2351 type = TREE_OPERAND (type, 0);
2352 type = TREE_TYPE (DECL_NAME (type));
2354 /* TYPE can only be either T* or T&. We can't know which of these it
2355 is by looking at TYPE, but OBJ will be "(T*) x" in the first case,
2356 and something like "(T*)(T&)(T*) x" in the second case. */
2357 bool reference_p = false;
2358 while (CONVERT_EXPR_P (obj) || TREE_CODE (obj) == SAVE_EXPR)
2360 reference_p |= TYPE_REF_P (TREE_TYPE (obj));
2361 obj = TREE_OPERAND (obj, 0);
2364 /* Evaluate the object so that we know its dynamic type. */
2365 obj = cxx_eval_constant_expression (ctx, obj, vc_prvalue, non_constant_p,
2366 overflow_p);
2367 if (*non_constant_p)
2368 return call;
2370 /* We expect OBJ to be in form of &d.D.2102 when HINT == 0,
2371 but when HINT is > 0, it can also be something like
2372 &d.D.2102 + 18446744073709551608, which includes the BINFO_OFFSET. */
2373 obj = extract_obj_from_addr_offset (obj);
2374 const tree objtype = TREE_TYPE (obj);
2375 /* If OBJ doesn't refer to a base field, we're done. */
2376 if (tree t = (TREE_CODE (obj) == COMPONENT_REF
2377 ? TREE_OPERAND (obj, 1) : obj))
2378 if (TREE_CODE (t) != FIELD_DECL || !DECL_FIELD_IS_BASE (t))
2380 if (reference_p)
2382 if (!ctx->quiet)
2384 error_at (loc, "reference %<dynamic_cast%> failed");
2385 inform (loc, "dynamic type %qT of its operand does "
2386 "not have a base class of type %qT",
2387 objtype, type);
2389 *non_constant_p = true;
2391 return integer_zero_node;
2394 /* [class.cdtor] When a dynamic_cast is used in a constructor ...
2395 or in a destructor ... if the operand of the dynamic_cast refers
2396 to the object under construction or destruction, this object is
2397 considered to be a most derived object that has the type of the
2398 constructor or destructor's class. */
2399 tree vtable = build_vfield_ref (obj, objtype);
2400 vtable = cxx_eval_constant_expression (ctx, vtable, vc_prvalue,
2401 non_constant_p, overflow_p);
2402 if (*non_constant_p)
2403 return call;
2404 /* With -fsanitize=vptr, we initialize all vtable pointers to null,
2405 so it's possible that we got a null pointer now. */
2406 if (integer_zerop (vtable))
2408 if (!ctx->quiet)
2409 error_at (loc, "virtual table pointer is used uninitialized");
2410 *non_constant_p = true;
2411 return integer_zero_node;
2413 /* VTABLE will be &_ZTV1A + 16 or similar, get _ZTV1A. */
2414 vtable = extract_obj_from_addr_offset (vtable);
2415 const tree mdtype = DECL_CONTEXT (vtable);
2417 /* Given dynamic_cast<T>(v),
2419 [expr.dynamic.cast] If C is the class type to which T points or refers,
2420 the runtime check logically executes as follows:
2422 If, in the most derived object pointed (referred) to by v, v points
2423 (refers) to a public base class subobject of a C object, and if only
2424 one object of type C is derived from the subobject pointed (referred)
2425 to by v the result points (refers) to that C object.
2427 In this case, HINT >= 0 or -3. */
2428 if (hint >= 0 || hint == -3)
2430 /* Look for a component with type TYPE. */
2431 tree t = get_component_with_type (obj, type, mdtype);
2432 /* If not accessible, give an error. */
2433 if (t == error_mark_node)
2435 if (reference_p)
2437 if (!ctx->quiet)
2439 error_at (loc, "reference %<dynamic_cast%> failed");
2440 inform (loc, "static type %qT of its operand is a "
2441 "non-public base class of dynamic type %qT",
2442 objtype, type);
2445 *non_constant_p = true;
2447 return integer_zero_node;
2449 else if (t)
2450 /* The result points to the TYPE object. */
2451 return cp_build_addr_expr (t, complain);
2452 /* Else, TYPE was not found, because the HINT turned out to be wrong.
2453 Fall through to the normal processing. */
2456 /* Otherwise, if v points (refers) to a public base class subobject of the
2457 most derived object, and the type of the most derived object has a base
2458 class, of type C, that is unambiguous and public, the result points
2459 (refers) to the C subobject of the most derived object.
2461 But it can also be an invalid case. */
2463 /* Get the most derived object. */
2464 obj = get_component_with_type (obj, mdtype, NULL_TREE);
2465 if (obj == error_mark_node)
2467 if (reference_p)
2469 if (!ctx->quiet)
2471 error_at (loc, "reference %<dynamic_cast%> failed");
2472 inform (loc, "static type %qT of its operand is a non-public"
2473 " base class of dynamic type %qT", objtype, mdtype);
2475 *non_constant_p = true;
2477 return integer_zero_node;
2479 else
2480 gcc_assert (obj);
2482 /* Check that the type of the most derived object has a base class
2483 of type TYPE that is unambiguous and public. */
2484 base_kind b_kind;
2485 tree binfo = lookup_base (mdtype, type, ba_check, &b_kind, tf_none);
2486 if (!binfo || binfo == error_mark_node)
2488 if (reference_p)
2490 if (!ctx->quiet)
2492 error_at (loc, "reference %<dynamic_cast%> failed");
2493 if (b_kind == bk_ambig)
2494 inform (loc, "%qT is an ambiguous base class of dynamic "
2495 "type %qT of its operand", type, mdtype);
2496 else
2497 inform (loc, "dynamic type %qT of its operand does not "
2498 "have an unambiguous public base class %qT",
2499 mdtype, type);
2501 *non_constant_p = true;
2503 return integer_zero_node;
2505 /* If so, return the TYPE subobject of the most derived object. */
2506 obj = convert_to_base_statically (obj, binfo);
2507 return cp_build_addr_expr (obj, complain);
2510 /* Data structure used by replace_decl and replace_decl_r. */
2512 struct replace_decl_data
2514 /* The _DECL we want to replace. */
2515 tree decl;
2516 /* The replacement for DECL. */
2517 tree replacement;
2518 /* Trees we've visited. */
2519 hash_set<tree> *pset;
2520 /* Whether we've performed any replacements. */
2521 bool changed;
2524 /* Helper function for replace_decl, called through cp_walk_tree. */
2526 static tree
2527 replace_decl_r (tree *tp, int *walk_subtrees, void *data)
2529 replace_decl_data *d = (replace_decl_data *) data;
2531 if (*tp == d->decl)
2533 *tp = unshare_expr (d->replacement);
2534 d->changed = true;
2535 *walk_subtrees = 0;
2537 else if (TYPE_P (*tp)
2538 || d->pset->add (*tp))
2539 *walk_subtrees = 0;
2541 return NULL_TREE;
2544 /* Replace every occurrence of DECL with (an unshared copy of)
2545 REPLACEMENT within the expression *TP. Returns true iff a
2546 replacement was performed. */
2548 bool
2549 replace_decl (tree *tp, tree decl, tree replacement)
2551 gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
2552 (TREE_TYPE (decl), TREE_TYPE (replacement)));
2553 hash_set<tree> pset;
2554 replace_decl_data data = { decl, replacement, &pset, false };
2555 cp_walk_tree (tp, replace_decl_r, &data, NULL);
2556 return data.changed;
2559 /* Evaluate the call T to virtual function thunk THUNK_FNDECL. */
2561 static tree
2562 cxx_eval_thunk_call (const constexpr_ctx *ctx, tree t, tree thunk_fndecl,
2563 value_cat lval,
2564 bool *non_constant_p, bool *overflow_p)
2566 tree function = THUNK_TARGET (thunk_fndecl);
2568 if (THUNK_VIRTUAL_OFFSET (thunk_fndecl))
2570 if (!ctx->quiet)
2572 if (!DECL_DECLARED_CONSTEXPR_P (function))
2574 error ("call to non-%<constexpr%> function %qD", function);
2575 explain_invalid_constexpr_fn (function);
2577 else
2578 /* virtual_offset is only set for virtual bases, which make the
2579 class non-literal, so we don't need to handle it here. */
2580 error ("calling constexpr member function %qD through virtual "
2581 "base subobject", function);
2583 *non_constant_p = true;
2584 return t;
2587 tree new_call = copy_node (t);
2588 CALL_EXPR_FN (new_call) = function;
2589 TREE_TYPE (new_call) = TREE_TYPE (TREE_TYPE (function));
2591 tree offset = size_int (THUNK_FIXED_OFFSET (thunk_fndecl));
2593 if (DECL_THIS_THUNK_P (thunk_fndecl))
2595 /* 'this'-adjusting thunk. */
2596 tree this_arg = CALL_EXPR_ARG (t, 0);
2597 this_arg = build2 (POINTER_PLUS_EXPR, TREE_TYPE (this_arg),
2598 this_arg, offset);
2599 CALL_EXPR_ARG (new_call, 0) = this_arg;
2601 else
2602 /* Return-adjusting thunk. */
2603 new_call = build2 (POINTER_PLUS_EXPR, TREE_TYPE (new_call),
2604 new_call, offset);
2606 return cxx_eval_constant_expression (ctx, new_call, lval,
2607 non_constant_p, overflow_p);
2610 /* If OBJECT is of const class type, evaluate it to a CONSTRUCTOR and set
2611 its TREE_READONLY flag according to READONLY_P. Used for constexpr
2612 'tors to detect modifying const objects in a constexpr context. */
2614 static void
2615 cxx_set_object_constness (const constexpr_ctx *ctx, tree object,
2616 bool readonly_p, bool *non_constant_p,
2617 bool *overflow_p)
2619 if (CLASS_TYPE_P (TREE_TYPE (object))
2620 && CP_TYPE_CONST_P (TREE_TYPE (object)))
2622 /* Subobjects might not be stored in ctx->global->values but we
2623 can get its CONSTRUCTOR by evaluating *this. */
2624 tree e = cxx_eval_constant_expression (ctx, object, vc_prvalue,
2625 non_constant_p, overflow_p);
2626 if (TREE_CODE (e) == CONSTRUCTOR && !*non_constant_p)
2627 TREE_READONLY (e) = readonly_p;
2631 /* Subroutine of cxx_eval_constant_expression.
2632 Evaluate the call expression tree T in the context of OLD_CALL expression
2633 evaluation. */
2635 static tree
2636 cxx_eval_call_expression (const constexpr_ctx *ctx, tree t,
2637 value_cat lval,
2638 bool *non_constant_p, bool *overflow_p)
2640 /* Handle concept checks separately. */
2641 if (concept_check_p (t))
2642 return evaluate_concept_check (t);
2644 location_t loc = cp_expr_loc_or_input_loc (t);
2645 tree fun = get_function_named_in_call (t);
2646 constexpr_call new_call
2647 = { NULL, NULL, NULL, 0, ctx->manifestly_const_eval };
2648 int depth_ok;
2650 if (fun == NULL_TREE)
2651 return cxx_eval_internal_function (ctx, t, lval,
2652 non_constant_p, overflow_p);
2654 if (TREE_CODE (fun) != FUNCTION_DECL)
2656 /* Might be a constexpr function pointer. */
2657 fun = cxx_eval_constant_expression (ctx, fun, vc_prvalue,
2658 non_constant_p, overflow_p);
2659 STRIP_NOPS (fun);
2660 if (TREE_CODE (fun) == ADDR_EXPR)
2661 fun = TREE_OPERAND (fun, 0);
2662 /* For TARGET_VTABLE_USES_DESCRIPTORS targets, there is no
2663 indirection, the called expression is a pointer into the
2664 virtual table which should contain FDESC_EXPR. Extract the
2665 FUNCTION_DECL from there. */
2666 else if (TARGET_VTABLE_USES_DESCRIPTORS
2667 && TREE_CODE (fun) == POINTER_PLUS_EXPR
2668 && TREE_CODE (TREE_OPERAND (fun, 0)) == ADDR_EXPR
2669 && TREE_CODE (TREE_OPERAND (fun, 1)) == INTEGER_CST)
2671 tree d = TREE_OPERAND (TREE_OPERAND (fun, 0), 0);
2672 if (VAR_P (d)
2673 && DECL_VTABLE_OR_VTT_P (d)
2674 && TREE_CODE (TREE_TYPE (d)) == ARRAY_TYPE
2675 && TREE_TYPE (TREE_TYPE (d)) == vtable_entry_type
2676 && DECL_INITIAL (d)
2677 && TREE_CODE (DECL_INITIAL (d)) == CONSTRUCTOR)
2679 tree i = int_const_binop (TRUNC_DIV_EXPR, TREE_OPERAND (fun, 1),
2680 TYPE_SIZE_UNIT (vtable_entry_type));
2681 HOST_WIDE_INT idx = find_array_ctor_elt (DECL_INITIAL (d), i);
2682 if (idx >= 0)
2684 tree fdesc
2685 = (*CONSTRUCTOR_ELTS (DECL_INITIAL (d)))[idx].value;
2686 if (TREE_CODE (fdesc) == FDESC_EXPR
2687 && integer_zerop (TREE_OPERAND (fdesc, 1)))
2688 fun = TREE_OPERAND (fdesc, 0);
2693 if (TREE_CODE (fun) != FUNCTION_DECL)
2695 if (!ctx->quiet && !*non_constant_p)
2696 error_at (loc, "expression %qE does not designate a %<constexpr%> "
2697 "function", fun);
2698 *non_constant_p = true;
2699 return t;
2701 if (DECL_CLONED_FUNCTION_P (fun) && !DECL_DELETING_DESTRUCTOR_P (fun))
2702 fun = DECL_CLONED_FUNCTION (fun);
2704 if (is_ubsan_builtin_p (fun))
2705 return void_node;
2707 if (fndecl_built_in_p (fun))
2708 return cxx_eval_builtin_function_call (ctx, t, fun,
2709 lval, non_constant_p, overflow_p);
2710 if (DECL_THUNK_P (fun))
2711 return cxx_eval_thunk_call (ctx, t, fun, lval, non_constant_p, overflow_p);
2712 if (!maybe_constexpr_fn (fun))
2714 if (TREE_CODE (t) == CALL_EXPR
2715 && cxx_replaceable_global_alloc_fn (fun)
2716 && (CALL_FROM_NEW_OR_DELETE_P (t)
2717 || is_std_allocator_allocate (ctx->call)))
2719 const int nargs = call_expr_nargs (t);
2720 tree arg0 = NULL_TREE;
2721 for (int i = 0; i < nargs; ++i)
2723 tree arg = CALL_EXPR_ARG (t, i);
2724 arg = cxx_eval_constant_expression (ctx, arg, vc_prvalue,
2725 non_constant_p, overflow_p);
2726 VERIFY_CONSTANT (arg);
2727 if (i == 0)
2728 arg0 = arg;
2730 gcc_assert (arg0);
2731 if (IDENTIFIER_NEW_OP_P (DECL_NAME (fun)))
2733 tree type = build_array_type_nelts (char_type_node,
2734 tree_to_uhwi (arg0));
2735 tree var = build_decl (loc, VAR_DECL,
2736 (IDENTIFIER_OVL_OP_FLAGS (DECL_NAME (fun))
2737 & OVL_OP_FLAG_VEC)
2738 ? heap_vec_uninit_identifier
2739 : heap_uninit_identifier,
2740 type);
2741 DECL_ARTIFICIAL (var) = 1;
2742 TREE_STATIC (var) = 1;
2743 // Temporarily register the artificial var in varpool,
2744 // so that comparisons of its address against NULL are folded
2745 // through nonzero_address even with
2746 // -fno-delete-null-pointer-checks or that comparison of
2747 // addresses of different heap artificial vars is folded too.
2748 // See PR98988 and PR99031.
2749 varpool_node::finalize_decl (var);
2750 ctx->global->heap_vars.safe_push (var);
2751 ctx->global->put_value (var, NULL_TREE);
2752 return fold_convert (ptr_type_node, build_address (var));
2754 else
2756 STRIP_NOPS (arg0);
2757 if (TREE_CODE (arg0) == ADDR_EXPR
2758 && VAR_P (TREE_OPERAND (arg0, 0)))
2760 tree var = TREE_OPERAND (arg0, 0);
2761 if (DECL_NAME (var) == heap_uninit_identifier
2762 || DECL_NAME (var) == heap_identifier)
2764 if (IDENTIFIER_OVL_OP_FLAGS (DECL_NAME (fun))
2765 & OVL_OP_FLAG_VEC)
2767 if (!ctx->quiet)
2769 error_at (loc, "array deallocation of object "
2770 "allocated with non-array "
2771 "allocation");
2772 inform (DECL_SOURCE_LOCATION (var),
2773 "allocation performed here");
2775 *non_constant_p = true;
2776 return t;
2778 DECL_NAME (var) = heap_deleted_identifier;
2779 ctx->global->remove_value (var);
2780 ctx->global->heap_dealloc_count++;
2781 return void_node;
2783 else if (DECL_NAME (var) == heap_vec_uninit_identifier
2784 || DECL_NAME (var) == heap_vec_identifier)
2786 if ((IDENTIFIER_OVL_OP_FLAGS (DECL_NAME (fun))
2787 & OVL_OP_FLAG_VEC) == 0)
2789 if (!ctx->quiet)
2791 error_at (loc, "non-array deallocation of "
2792 "object allocated with array "
2793 "allocation");
2794 inform (DECL_SOURCE_LOCATION (var),
2795 "allocation performed here");
2797 *non_constant_p = true;
2798 return t;
2800 DECL_NAME (var) = heap_deleted_identifier;
2801 ctx->global->remove_value (var);
2802 ctx->global->heap_dealloc_count++;
2803 return void_node;
2805 else if (DECL_NAME (var) == heap_deleted_identifier)
2807 if (!ctx->quiet)
2808 error_at (loc, "deallocation of already deallocated "
2809 "storage");
2810 *non_constant_p = true;
2811 return t;
2814 if (!ctx->quiet)
2815 error_at (loc, "deallocation of storage that was "
2816 "not previously allocated");
2817 *non_constant_p = true;
2818 return t;
2821 /* Allow placement new in std::construct_at, just return the second
2822 argument. */
2823 if (TREE_CODE (t) == CALL_EXPR
2824 && cxx_placement_new_fn (fun)
2825 && is_std_construct_at (ctx->call))
2827 const int nargs = call_expr_nargs (t);
2828 tree arg1 = NULL_TREE;
2829 for (int i = 0; i < nargs; ++i)
2831 tree arg = CALL_EXPR_ARG (t, i);
2832 arg = cxx_eval_constant_expression (ctx, arg, vc_prvalue,
2833 non_constant_p, overflow_p);
2834 if (i == 1)
2835 arg1 = arg;
2836 else
2837 VERIFY_CONSTANT (arg);
2839 gcc_assert (arg1);
2840 return arg1;
2842 else if (cxx_dynamic_cast_fn_p (fun))
2843 return cxx_eval_dynamic_cast_fn (ctx, t, non_constant_p, overflow_p);
2845 if (!ctx->quiet)
2847 if (!lambda_static_thunk_p (fun))
2848 error_at (loc, "call to non-%<constexpr%> function %qD", fun);
2849 explain_invalid_constexpr_fn (fun);
2851 *non_constant_p = true;
2852 return t;
2855 constexpr_ctx new_ctx = *ctx;
2856 if (DECL_CONSTRUCTOR_P (fun) && !ctx->object
2857 && TREE_CODE (t) == AGGR_INIT_EXPR)
2859 /* We want to have an initialization target for an AGGR_INIT_EXPR.
2860 If we don't already have one in CTX, use the AGGR_INIT_EXPR_SLOT. */
2861 new_ctx.object = AGGR_INIT_EXPR_SLOT (t);
2862 tree ctor = new_ctx.ctor = build_constructor (DECL_CONTEXT (fun), NULL);
2863 CONSTRUCTOR_NO_CLEARING (ctor) = true;
2864 ctx->global->put_value (new_ctx.object, ctor);
2865 ctx = &new_ctx;
2868 /* Shortcut trivial constructor/op=. */
2869 if (trivial_fn_p (fun))
2871 tree init = NULL_TREE;
2872 if (call_expr_nargs (t) == 2)
2873 init = convert_from_reference (get_nth_callarg (t, 1));
2874 else if (TREE_CODE (t) == AGGR_INIT_EXPR
2875 && AGGR_INIT_ZERO_FIRST (t))
2876 init = build_zero_init (DECL_CONTEXT (fun), NULL_TREE, false);
2877 if (init)
2879 tree op = get_nth_callarg (t, 0);
2880 if (is_dummy_object (op))
2881 op = ctx->object;
2882 else
2883 op = build1 (INDIRECT_REF, TREE_TYPE (TREE_TYPE (op)), op);
2884 tree set = build2 (MODIFY_EXPR, TREE_TYPE (op), op, init);
2885 new_ctx.call = &new_call;
2886 return cxx_eval_constant_expression (&new_ctx, set, lval,
2887 non_constant_p, overflow_p);
2891 bool non_constant_args = false;
2892 new_call.bindings
2893 = cxx_bind_parameters_in_call (ctx, t, fun, non_constant_p,
2894 overflow_p, &non_constant_args);
2896 /* We build up the bindings list before we know whether we already have this
2897 call cached. If we don't end up saving these bindings, ggc_free them when
2898 this function exits. */
2899 class free_bindings
2901 tree *bindings;
2902 public:
2903 free_bindings (tree &b): bindings (&b) { }
2904 ~free_bindings () { if (bindings) ggc_free (*bindings); }
2905 void preserve () { bindings = NULL; }
2906 } fb (new_call.bindings);
2908 if (*non_constant_p)
2909 return t;
2911 /* We can't defer instantiating the function any longer. */
2912 if (!DECL_INITIAL (fun)
2913 && DECL_TEMPLOID_INSTANTIATION (fun)
2914 && !uid_sensitive_constexpr_evaluation_p ())
2916 location_t save_loc = input_location;
2917 input_location = loc;
2918 ++function_depth;
2919 if (ctx->manifestly_const_eval)
2920 FNDECL_MANIFESTLY_CONST_EVALUATED (fun) = true;
2921 instantiate_decl (fun, /*defer_ok*/false, /*expl_inst*/false);
2922 --function_depth;
2923 input_location = save_loc;
2926 /* If in direct recursive call, optimize definition search. */
2927 if (ctx && ctx->call && ctx->call->fundef && ctx->call->fundef->decl == fun)
2928 new_call.fundef = ctx->call->fundef;
2929 else
2931 new_call.fundef = retrieve_constexpr_fundef (fun);
2932 if (new_call.fundef == NULL || new_call.fundef->body == NULL
2933 || new_call.fundef->result == error_mark_node
2934 || fun == current_function_decl)
2936 if (!ctx->quiet)
2938 /* We need to check for current_function_decl here in case we're
2939 being called during cp_fold_function, because at that point
2940 DECL_INITIAL is set properly and we have a fundef but we
2941 haven't lowered invisirefs yet (c++/70344). */
2942 if (DECL_INITIAL (fun) == error_mark_node
2943 || fun == current_function_decl)
2944 error_at (loc, "%qD called in a constant expression before its "
2945 "definition is complete", fun);
2946 else if (DECL_INITIAL (fun))
2948 /* The definition of fun was somehow unsuitable. But pretend
2949 that lambda static thunks don't exist. */
2950 if (!lambda_static_thunk_p (fun))
2951 error_at (loc, "%qD called in a constant expression", fun);
2952 explain_invalid_constexpr_fn (fun);
2954 else
2955 error_at (loc, "%qD used before its definition", fun);
2957 *non_constant_p = true;
2958 return t;
2962 depth_ok = push_cx_call_context (t);
2964 /* Remember the object we are constructing or destructing. */
2965 tree new_obj = NULL_TREE;
2966 if (DECL_CONSTRUCTOR_P (fun) || DECL_DESTRUCTOR_P (fun))
2968 /* In a cdtor, it should be the first `this' argument.
2969 At this point it has already been evaluated in the call
2970 to cxx_bind_parameters_in_call. */
2971 new_obj = TREE_VEC_ELT (new_call.bindings, 0);
2972 new_obj = cxx_fold_indirect_ref (ctx, loc, DECL_CONTEXT (fun), new_obj);
2974 if (ctx->call && ctx->call->fundef
2975 && DECL_CONSTRUCTOR_P (ctx->call->fundef->decl))
2977 tree cur_obj = TREE_VEC_ELT (ctx->call->bindings, 0);
2978 STRIP_NOPS (cur_obj);
2979 if (TREE_CODE (cur_obj) == ADDR_EXPR)
2980 cur_obj = TREE_OPERAND (cur_obj, 0);
2981 if (new_obj == cur_obj)
2982 /* We're calling the target constructor of a delegating
2983 constructor, or accessing a base subobject through a
2984 NOP_EXPR as part of a call to a base constructor, so
2985 there is no new (sub)object. */
2986 new_obj = NULL_TREE;
2990 tree result = NULL_TREE;
2992 constexpr_call *entry = NULL;
2993 if (depth_ok && !non_constant_args && ctx->strict)
2995 new_call.hash = constexpr_fundef_hasher::hash (new_call.fundef);
2996 new_call.hash
2997 = iterative_hash_template_arg (new_call.bindings, new_call.hash);
2998 new_call.hash
2999 = iterative_hash_object (ctx->manifestly_const_eval, new_call.hash);
3001 /* If we have seen this call before, we are done. */
3002 maybe_initialize_constexpr_call_table ();
3003 constexpr_call **slot
3004 = constexpr_call_table->find_slot (&new_call, INSERT);
3005 entry = *slot;
3006 if (entry == NULL)
3008 /* Only cache up to constexpr_cache_depth to limit memory use. */
3009 if (depth_ok < constexpr_cache_depth)
3011 /* We need to keep a pointer to the entry, not just the slot, as
3012 the slot can move during evaluation of the body. */
3013 *slot = entry = ggc_alloc<constexpr_call> ();
3014 *entry = new_call;
3015 fb.preserve ();
3018 /* Calls that are in progress have their result set to NULL, so that we
3019 can detect circular dependencies. Now that we only cache up to
3020 constexpr_cache_depth this won't catch circular dependencies that
3021 start deeper, but they'll hit the recursion or ops limit. */
3022 else if (entry->result == NULL)
3024 if (!ctx->quiet)
3025 error ("call has circular dependency");
3026 *non_constant_p = true;
3027 entry->result = result = error_mark_node;
3029 else
3030 result = entry->result;
3033 if (!depth_ok)
3035 if (!ctx->quiet)
3036 error ("%<constexpr%> evaluation depth exceeds maximum of %d (use "
3037 "%<-fconstexpr-depth=%> to increase the maximum)",
3038 max_constexpr_depth);
3039 *non_constant_p = true;
3040 result = error_mark_node;
3042 else
3044 bool cacheable = true;
3045 if (result && result != error_mark_node)
3046 /* OK */;
3047 else if (!DECL_SAVED_TREE (fun))
3049 /* When at_eof >= 2, cgraph has started throwing away
3050 DECL_SAVED_TREE, so fail quietly. FIXME we get here because of
3051 late code generation for VEC_INIT_EXPR, which needs to be
3052 completely reconsidered. */
3053 gcc_assert (at_eof >= 2 && ctx->quiet);
3054 *non_constant_p = true;
3056 else if (tree copy = get_fundef_copy (new_call.fundef))
3058 tree body, parms, res;
3059 releasing_vec ctors;
3061 /* Reuse or create a new unshared copy of this function's body. */
3062 body = TREE_PURPOSE (copy);
3063 parms = TREE_VALUE (copy);
3064 res = TREE_TYPE (copy);
3066 /* Associate the bindings with the remapped parms. */
3067 tree bound = new_call.bindings;
3068 tree remapped = parms;
3069 for (int i = 0; i < TREE_VEC_LENGTH (bound); ++i)
3071 tree arg = TREE_VEC_ELT (bound, i);
3072 if (entry)
3074 /* Unshare args going into the hash table to separate them
3075 from the caller's context, for better GC and to avoid
3076 problems with verify_gimple. */
3077 arg = unshare_expr_without_location (arg);
3078 TREE_VEC_ELT (bound, i) = arg;
3080 /* And then unshare again so the callee doesn't change the
3081 argument values in the hash table. XXX Could we unshare
3082 lazily in cxx_eval_store_expression? */
3083 arg = unshare_constructor (arg);
3084 if (TREE_CODE (arg) == CONSTRUCTOR)
3085 vec_safe_push (ctors, arg);
3087 ctx->global->put_value (remapped, arg);
3088 remapped = DECL_CHAIN (remapped);
3090 /* Add the RESULT_DECL to the values map, too. */
3091 gcc_assert (!DECL_BY_REFERENCE (res));
3092 ctx->global->put_value (res, NULL_TREE);
3094 /* Track the callee's evaluated SAVE_EXPRs and TARGET_EXPRs so that
3095 we can forget their values after the call. */
3096 constexpr_ctx ctx_with_save_exprs = *ctx;
3097 auto_vec<tree, 10> save_exprs;
3098 ctx_with_save_exprs.save_exprs = &save_exprs;
3099 ctx_with_save_exprs.call = &new_call;
3100 unsigned save_heap_alloc_count = ctx->global->heap_vars.length ();
3101 unsigned save_heap_dealloc_count = ctx->global->heap_dealloc_count;
3103 /* If this is a constexpr destructor, the object's const and volatile
3104 semantics are no longer in effect; see [class.dtor]p5. */
3105 if (new_obj && DECL_DESTRUCTOR_P (fun))
3106 cxx_set_object_constness (ctx, new_obj, /*readonly_p=*/false,
3107 non_constant_p, overflow_p);
3109 tree jump_target = NULL_TREE;
3110 cxx_eval_constant_expression (&ctx_with_save_exprs, body,
3111 vc_discard, non_constant_p, overflow_p,
3112 &jump_target);
3114 if (DECL_CONSTRUCTOR_P (fun))
3116 /* This can be null for a subobject constructor call, in
3117 which case what we care about is the initialization
3118 side-effects rather than the value. We could get at the
3119 value by evaluating *this, but we don't bother; there's
3120 no need to put such a call in the hash table. */
3121 result = lval ? ctx->object : ctx->ctor;
3123 /* If we've just evaluated a subobject constructor call for an
3124 empty union member, it might not have produced a side effect
3125 that actually activated the union member. So produce such a
3126 side effect now to ensure the union appears initialized. */
3127 if (!result && new_obj
3128 && TREE_CODE (new_obj) == COMPONENT_REF
3129 && TREE_CODE (TREE_TYPE
3130 (TREE_OPERAND (new_obj, 0))) == UNION_TYPE
3131 && is_really_empty_class (TREE_TYPE (new_obj),
3132 /*ignore_vptr*/false))
3134 tree activate = build2 (MODIFY_EXPR, TREE_TYPE (new_obj),
3135 new_obj,
3136 build_constructor (TREE_TYPE (new_obj),
3137 NULL));
3138 cxx_eval_constant_expression (ctx, activate, lval,
3139 non_constant_p, overflow_p);
3140 ggc_free (activate);
3143 else if (VOID_TYPE_P (TREE_TYPE (res)))
3144 result = void_node;
3145 else
3147 result = ctx->global->get_value (res);
3148 if (result == NULL_TREE && !*non_constant_p
3149 && !DECL_DESTRUCTOR_P (fun))
3151 if (!ctx->quiet)
3152 error ("%<constexpr%> call flows off the end "
3153 "of the function");
3154 *non_constant_p = true;
3158 /* At this point, the object's constructor will have run, so
3159 the object is no longer under construction, and its possible
3160 'const' semantics now apply. Make a note of this fact by
3161 marking the CONSTRUCTOR TREE_READONLY. */
3162 if (new_obj && DECL_CONSTRUCTOR_P (fun))
3163 cxx_set_object_constness (ctx, new_obj, /*readonly_p=*/true,
3164 non_constant_p, overflow_p);
3166 /* Forget the saved values of the callee's SAVE_EXPRs and
3167 TARGET_EXPRs. */
3168 for (tree save_expr : save_exprs)
3169 ctx->global->remove_value (save_expr);
3171 /* Remove the parms/result from the values map. Is it worth
3172 bothering to do this when the map itself is only live for
3173 one constexpr evaluation? If so, maybe also clear out
3174 other vars from call, maybe in BIND_EXPR handling? */
3175 ctx->global->remove_value (res);
3176 for (tree parm = parms; parm; parm = TREE_CHAIN (parm))
3177 ctx->global->remove_value (parm);
3179 /* Free any parameter CONSTRUCTORs we aren't returning directly. */
3180 while (!ctors->is_empty ())
3182 tree c = ctors->pop ();
3183 if (c != result)
3184 free_constructor (c);
3187 /* Make the unshared function copy we used available for re-use. */
3188 save_fundef_copy (fun, copy);
3190 /* If the call allocated some heap object that hasn't been
3191 deallocated during the call, or if it deallocated some heap
3192 object it has not allocated, the call isn't really stateless
3193 for the constexpr evaluation and should not be cached.
3194 It is fine if the call allocates something and deallocates it
3195 too. */
3196 if (entry
3197 && (save_heap_alloc_count != ctx->global->heap_vars.length ()
3198 || (save_heap_dealloc_count
3199 != ctx->global->heap_dealloc_count)))
3201 tree heap_var;
3202 unsigned int i;
3203 if ((ctx->global->heap_vars.length ()
3204 - ctx->global->heap_dealloc_count)
3205 != save_heap_alloc_count - save_heap_dealloc_count)
3206 cacheable = false;
3207 else
3208 FOR_EACH_VEC_ELT_FROM (ctx->global->heap_vars, i, heap_var,
3209 save_heap_alloc_count)
3210 if (DECL_NAME (heap_var) != heap_deleted_identifier)
3212 cacheable = false;
3213 break;
3215 /* Also don't cache a call that returns a deallocated pointer. */
3216 if (cacheable && (cp_walk_tree_without_duplicates
3217 (&result, find_heap_var_refs, NULL)))
3218 cacheable = false;
3221 /* Rewrite all occurrences of the function's RESULT_DECL with the
3222 current object under construction. */
3223 if (!*non_constant_p && ctx->object
3224 && CLASS_TYPE_P (TREE_TYPE (res))
3225 && !is_empty_class (TREE_TYPE (res)))
3226 if (replace_decl (&result, res, ctx->object))
3227 cacheable = false;
3229 else
3230 /* Couldn't get a function copy to evaluate. */
3231 *non_constant_p = true;
3233 if (result == error_mark_node)
3234 *non_constant_p = true;
3235 if (*non_constant_p || *overflow_p)
3236 result = error_mark_node;
3237 else if (!result)
3238 result = void_node;
3239 if (entry)
3240 entry->result = cacheable ? result : error_mark_node;
3243 /* The result of a constexpr function must be completely initialized.
3245 However, in C++20, a constexpr constructor doesn't necessarily have
3246 to initialize all the fields, so we don't clear CONSTRUCTOR_NO_CLEARING
3247 in order to detect reading an unitialized object in constexpr instead
3248 of value-initializing it. (reduced_constant_expression_p is expected to
3249 take care of clearing the flag.) */
3250 if (TREE_CODE (result) == CONSTRUCTOR
3251 && (cxx_dialect < cxx20
3252 || !DECL_CONSTRUCTOR_P (fun)))
3253 clear_no_implicit_zero (result);
3255 pop_cx_call_context ();
3256 return result;
3259 /* Return true if T is a valid constant initializer. If a CONSTRUCTOR
3260 initializes all the members, the CONSTRUCTOR_NO_CLEARING flag will be
3261 cleared.
3262 FIXME speed this up, it's taking 16% of compile time on sieve testcase. */
3264 bool
3265 reduced_constant_expression_p (tree t)
3267 if (t == NULL_TREE)
3268 return false;
3270 switch (TREE_CODE (t))
3272 case PTRMEM_CST:
3273 /* Even if we can't lower this yet, it's constant. */
3274 return true;
3276 case CONSTRUCTOR:
3277 /* And we need to handle PTRMEM_CST wrapped in a CONSTRUCTOR. */
3278 tree field;
3279 if (TREE_CODE (TREE_TYPE (t)) == VECTOR_TYPE)
3280 /* An initialized vector would have a VECTOR_CST. */
3281 return false;
3282 if (CONSTRUCTOR_NO_CLEARING (t))
3284 if (TREE_CODE (TREE_TYPE (t)) == ARRAY_TYPE)
3286 /* There must be a valid constant initializer at every array
3287 index. */
3288 tree min = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (t)));
3289 tree max = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (t)));
3290 tree cursor = min;
3291 for (auto &e: CONSTRUCTOR_ELTS (t))
3293 if (!reduced_constant_expression_p (e.value))
3294 return false;
3295 if (array_index_cmp (cursor, e.index) != 0)
3296 return false;
3297 if (TREE_CODE (e.index) == RANGE_EXPR)
3298 cursor = TREE_OPERAND (e.index, 1);
3299 cursor = int_const_binop (PLUS_EXPR, cursor, size_one_node);
3301 if (find_array_ctor_elt (t, max) == -1)
3302 return false;
3303 goto ok;
3305 else if (cxx_dialect >= cxx20
3306 && TREE_CODE (TREE_TYPE (t)) == UNION_TYPE)
3308 if (CONSTRUCTOR_NELTS (t) == 0)
3309 /* An initialized union has a constructor element. */
3310 return false;
3311 /* And it only initializes one member. */
3312 field = NULL_TREE;
3314 else
3315 field = next_subobject_field (TYPE_FIELDS (TREE_TYPE (t)));
3317 else
3318 field = NULL_TREE;
3319 for (auto &e: CONSTRUCTOR_ELTS (t))
3321 /* If VAL is null, we're in the middle of initializing this
3322 element. */
3323 if (!reduced_constant_expression_p (e.value))
3324 return false;
3325 /* We want to remove initializers for empty fields in a struct to
3326 avoid confusing output_constructor. */
3327 if (is_empty_field (e.index)
3328 && TREE_CODE (TREE_TYPE (t)) == RECORD_TYPE)
3329 return false;
3330 /* Check for non-empty fields between initialized fields when
3331 CONSTRUCTOR_NO_CLEARING. */
3332 for (; field && e.index != field;
3333 field = next_subobject_field (DECL_CHAIN (field)))
3334 if (!is_really_empty_class (TREE_TYPE (field),
3335 /*ignore_vptr*/false))
3336 return false;
3337 if (field)
3338 field = next_subobject_field (DECL_CHAIN (field));
3340 /* There could be a non-empty field at the end. */
3341 for (; field; field = next_subobject_field (DECL_CHAIN (field)))
3342 if (!is_really_empty_class (TREE_TYPE (field), /*ignore_vptr*/false))
3343 return false;
3345 if (CONSTRUCTOR_NO_CLEARING (t))
3346 /* All the fields are initialized. */
3347 CONSTRUCTOR_NO_CLEARING (t) = false;
3348 return true;
3350 default:
3351 /* FIXME are we calling this too much? */
3352 return initializer_constant_valid_p (t, TREE_TYPE (t)) != NULL_TREE;
3356 /* Some expressions may have constant operands but are not constant
3357 themselves, such as 1/0. Call this function to check for that
3358 condition.
3360 We only call this in places that require an arithmetic constant, not in
3361 places where we might have a non-constant expression that can be a
3362 component of a constant expression, such as the address of a constexpr
3363 variable that might be dereferenced later. */
3365 static bool
3366 verify_constant (tree t, bool allow_non_constant, bool *non_constant_p,
3367 bool *overflow_p)
3369 if (!*non_constant_p && !reduced_constant_expression_p (t)
3370 && t != void_node)
3372 if (!allow_non_constant)
3373 error ("%q+E is not a constant expression", t);
3374 *non_constant_p = true;
3376 if (TREE_OVERFLOW_P (t))
3378 if (!allow_non_constant)
3380 permerror (input_location, "overflow in constant expression");
3381 /* If we're being permissive (and are in an enforcing
3382 context), ignore the overflow. */
3383 if (flag_permissive)
3384 return *non_constant_p;
3386 *overflow_p = true;
3388 return *non_constant_p;
3391 /* Check whether the shift operation with code CODE and type TYPE on LHS
3392 and RHS is undefined. If it is, give an error with an explanation,
3393 and return true; return false otherwise. */
3395 static bool
3396 cxx_eval_check_shift_p (location_t loc, const constexpr_ctx *ctx,
3397 enum tree_code code, tree type, tree lhs, tree rhs)
3399 if ((code != LSHIFT_EXPR && code != RSHIFT_EXPR)
3400 || TREE_CODE (lhs) != INTEGER_CST
3401 || TREE_CODE (rhs) != INTEGER_CST)
3402 return false;
3404 tree lhstype = TREE_TYPE (lhs);
3405 unsigned HOST_WIDE_INT uprec = TYPE_PRECISION (TREE_TYPE (lhs));
3407 /* [expr.shift] The behavior is undefined if the right operand
3408 is negative, or greater than or equal to the length in bits
3409 of the promoted left operand. */
3410 if (tree_int_cst_sgn (rhs) == -1)
3412 if (!ctx->quiet)
3413 permerror (loc, "right operand of shift expression %q+E is negative",
3414 build2_loc (loc, code, type, lhs, rhs));
3415 return (!flag_permissive || ctx->quiet);
3417 if (compare_tree_int (rhs, uprec) >= 0)
3419 if (!ctx->quiet)
3420 permerror (loc, "right operand of shift expression %q+E is greater "
3421 "than or equal to the precision %wu of the left operand",
3422 build2_loc (loc, code, type, lhs, rhs), uprec);
3423 return (!flag_permissive || ctx->quiet);
3426 /* The value of E1 << E2 is E1 left-shifted E2 bit positions; [...]
3427 if E1 has a signed type and non-negative value, and E1x2^E2 is
3428 representable in the corresponding unsigned type of the result type,
3429 then that value, converted to the result type, is the resulting value;
3430 otherwise, the behavior is undefined.
3431 For C++20:
3432 The value of E1 << E2 is the unique value congruent to E1 x 2^E2 modulo
3433 2^N, where N is the range exponent of the type of the result. */
3434 if (code == LSHIFT_EXPR
3435 && !TYPE_OVERFLOW_WRAPS (lhstype)
3436 && cxx_dialect >= cxx11
3437 && cxx_dialect < cxx20)
3439 if (tree_int_cst_sgn (lhs) == -1)
3441 if (!ctx->quiet)
3442 permerror (loc,
3443 "left operand of shift expression %q+E is negative",
3444 build2_loc (loc, code, type, lhs, rhs));
3445 return (!flag_permissive || ctx->quiet);
3447 /* For signed x << y the following:
3448 (unsigned) x >> ((prec (lhs) - 1) - y)
3449 if > 1, is undefined. The right-hand side of this formula
3450 is the highest bit of the LHS that can be set (starting from 0),
3451 so that the shift doesn't overflow. We then right-shift the LHS
3452 to see whether any other bit is set making the original shift
3453 undefined -- the result is not representable in the corresponding
3454 unsigned type. */
3455 tree t = build_int_cst (unsigned_type_node, uprec - 1);
3456 t = fold_build2 (MINUS_EXPR, unsigned_type_node, t, rhs);
3457 tree ulhs = fold_convert (unsigned_type_for (lhstype), lhs);
3458 t = fold_build2 (RSHIFT_EXPR, TREE_TYPE (ulhs), ulhs, t);
3459 if (tree_int_cst_lt (integer_one_node, t))
3461 if (!ctx->quiet)
3462 permerror (loc, "shift expression %q+E overflows",
3463 build2_loc (loc, code, type, lhs, rhs));
3464 return (!flag_permissive || ctx->quiet);
3467 return false;
3470 /* Subroutine of cxx_eval_constant_expression.
3471 Attempt to reduce the unary expression tree T to a compile time value.
3472 If successful, return the value. Otherwise issue a diagnostic
3473 and return error_mark_node. */
3475 static tree
3476 cxx_eval_unary_expression (const constexpr_ctx *ctx, tree t,
3477 bool /*lval*/,
3478 bool *non_constant_p, bool *overflow_p)
3480 tree r;
3481 tree orig_arg = TREE_OPERAND (t, 0);
3482 tree arg = cxx_eval_constant_expression (ctx, orig_arg, vc_prvalue,
3483 non_constant_p, overflow_p);
3484 VERIFY_CONSTANT (arg);
3485 location_t loc = EXPR_LOCATION (t);
3486 enum tree_code code = TREE_CODE (t);
3487 tree type = TREE_TYPE (t);
3488 r = fold_unary_loc (loc, code, type, arg);
3489 if (r == NULL_TREE)
3491 if (arg == orig_arg)
3492 r = t;
3493 else
3494 r = build1_loc (loc, code, type, arg);
3496 VERIFY_CONSTANT (r);
3497 return r;
3500 /* Helper function for cxx_eval_binary_expression. Try to optimize
3501 original POINTER_PLUS_EXPR T, LHS p+ RHS, return NULL_TREE if the
3502 generic folding should be used. */
3504 static tree
3505 cxx_fold_pointer_plus_expression (const constexpr_ctx *ctx, tree t,
3506 tree lhs, tree rhs, bool *non_constant_p,
3507 bool *overflow_p)
3509 STRIP_NOPS (lhs);
3510 if (TREE_CODE (lhs) != ADDR_EXPR)
3511 return NULL_TREE;
3513 lhs = TREE_OPERAND (lhs, 0);
3515 /* &A[i] p+ j => &A[i + j] */
3516 if (TREE_CODE (lhs) == ARRAY_REF
3517 && TREE_CODE (TREE_OPERAND (lhs, 1)) == INTEGER_CST
3518 && TREE_CODE (rhs) == INTEGER_CST
3519 && TYPE_SIZE_UNIT (TREE_TYPE (lhs))
3520 && TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (lhs))) == INTEGER_CST)
3522 tree orig_type = TREE_TYPE (t);
3523 location_t loc = EXPR_LOCATION (t);
3524 tree type = TREE_TYPE (lhs);
3526 t = fold_convert_loc (loc, ssizetype, TREE_OPERAND (lhs, 1));
3527 tree nelts = array_type_nelts_top (TREE_TYPE (TREE_OPERAND (lhs, 0)));
3528 nelts = cxx_eval_constant_expression (ctx, nelts, vc_prvalue,
3529 non_constant_p, overflow_p);
3530 if (*non_constant_p)
3531 return NULL_TREE;
3532 /* Don't fold an out-of-bound access. */
3533 if (!tree_int_cst_le (t, nelts))
3534 return NULL_TREE;
3535 rhs = cp_fold_convert (ssizetype, rhs);
3536 /* Don't fold if rhs can't be divided exactly by TYPE_SIZE_UNIT.
3537 constexpr int A[1]; ... (char *)&A[0] + 1 */
3538 if (!integer_zerop (fold_build2_loc (loc, TRUNC_MOD_EXPR, sizetype,
3539 rhs, TYPE_SIZE_UNIT (type))))
3540 return NULL_TREE;
3541 /* Make sure to treat the second operand of POINTER_PLUS_EXPR
3542 as signed. */
3543 rhs = fold_build2_loc (loc, EXACT_DIV_EXPR, ssizetype, rhs,
3544 TYPE_SIZE_UNIT (type));
3545 t = size_binop_loc (loc, PLUS_EXPR, rhs, t);
3546 t = build4_loc (loc, ARRAY_REF, type, TREE_OPERAND (lhs, 0),
3547 t, NULL_TREE, NULL_TREE);
3548 t = cp_build_addr_expr (t, tf_warning_or_error);
3549 t = cp_fold_convert (orig_type, t);
3550 return cxx_eval_constant_expression (ctx, t, vc_prvalue,
3551 non_constant_p, overflow_p);
3554 return NULL_TREE;
3557 /* Try to fold expressions like
3558 (struct S *) (&a[0].D.2378 + 12)
3559 into
3560 &MEM <struct T> [(void *)&a + 12B]
3561 This is something normally done by gimple_fold_stmt_to_constant_1
3562 on GIMPLE, but is undesirable on GENERIC if we are e.g. going to
3563 dereference the address because some details are lost.
3564 For pointer comparisons we want such folding though so that
3565 match.pd address_compare optimization works. */
3567 static tree
3568 cxx_maybe_fold_addr_pointer_plus (tree t)
3570 while (CONVERT_EXPR_P (t)
3571 && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (t, 0))))
3572 t = TREE_OPERAND (t, 0);
3573 if (TREE_CODE (t) != POINTER_PLUS_EXPR)
3574 return NULL_TREE;
3575 tree op0 = TREE_OPERAND (t, 0);
3576 tree op1 = TREE_OPERAND (t, 1);
3577 if (TREE_CODE (op1) != INTEGER_CST)
3578 return NULL_TREE;
3579 while (CONVERT_EXPR_P (op0)
3580 && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (op0, 0))))
3581 op0 = TREE_OPERAND (op0, 0);
3582 if (TREE_CODE (op0) != ADDR_EXPR)
3583 return NULL_TREE;
3584 op1 = fold_convert (ptr_type_node, op1);
3585 tree r = fold_build2 (MEM_REF, TREE_TYPE (TREE_TYPE (op0)), op0, op1);
3586 return build1_loc (EXPR_LOCATION (t), ADDR_EXPR, TREE_TYPE (op0), r);
3589 /* Subroutine of cxx_eval_constant_expression.
3590 Like cxx_eval_unary_expression, except for binary expressions. */
3592 static tree
3593 cxx_eval_binary_expression (const constexpr_ctx *ctx, tree t,
3594 value_cat lval,
3595 bool *non_constant_p, bool *overflow_p)
3597 tree r = NULL_TREE;
3598 tree orig_lhs = TREE_OPERAND (t, 0);
3599 tree orig_rhs = TREE_OPERAND (t, 1);
3600 tree lhs, rhs;
3601 lhs = cxx_eval_constant_expression (ctx, orig_lhs, vc_prvalue,
3602 non_constant_p, overflow_p);
3603 /* Don't VERIFY_CONSTANT here, it's unnecessary and will break pointer
3604 subtraction. */
3605 if (*non_constant_p)
3606 return t;
3607 rhs = cxx_eval_constant_expression (ctx, orig_rhs, vc_prvalue,
3608 non_constant_p, overflow_p);
3609 if (*non_constant_p)
3610 return t;
3612 location_t loc = EXPR_LOCATION (t);
3613 enum tree_code code = TREE_CODE (t);
3614 tree type = TREE_TYPE (t);
3616 if (code == EQ_EXPR || code == NE_EXPR)
3618 bool is_code_eq = (code == EQ_EXPR);
3620 if (TREE_CODE (lhs) == PTRMEM_CST
3621 && TREE_CODE (rhs) == PTRMEM_CST)
3623 tree lmem = PTRMEM_CST_MEMBER (lhs);
3624 tree rmem = PTRMEM_CST_MEMBER (rhs);
3625 bool eq;
3626 if (TREE_CODE (lmem) == TREE_CODE (rmem)
3627 && TREE_CODE (lmem) == FIELD_DECL
3628 && TREE_CODE (DECL_CONTEXT (lmem)) == UNION_TYPE
3629 && same_type_p (DECL_CONTEXT (lmem),
3630 DECL_CONTEXT (rmem)))
3631 /* If both refer to (possibly different) members of the same union
3632 (12.3), they compare equal. */
3633 eq = true;
3634 else
3635 eq = cp_tree_equal (lhs, rhs);
3636 r = constant_boolean_node (eq == is_code_eq, type);
3638 else if ((TREE_CODE (lhs) == PTRMEM_CST
3639 || TREE_CODE (rhs) == PTRMEM_CST)
3640 && (null_member_pointer_value_p (lhs)
3641 || null_member_pointer_value_p (rhs)))
3642 r = constant_boolean_node (!is_code_eq, type);
3643 else if (TREE_CODE (lhs) == PTRMEM_CST)
3644 lhs = cplus_expand_constant (lhs);
3645 else if (TREE_CODE (rhs) == PTRMEM_CST)
3646 rhs = cplus_expand_constant (rhs);
3648 if (r == NULL_TREE
3649 && TREE_CODE_CLASS (code) == tcc_comparison
3650 && POINTER_TYPE_P (TREE_TYPE (lhs)))
3652 if (tree lhso = cxx_maybe_fold_addr_pointer_plus (lhs))
3653 lhs = fold_convert (TREE_TYPE (lhs), lhso);
3654 if (tree rhso = cxx_maybe_fold_addr_pointer_plus (rhs))
3655 rhs = fold_convert (TREE_TYPE (rhs), rhso);
3657 if (code == POINTER_PLUS_EXPR && !*non_constant_p
3658 && integer_zerop (lhs) && !integer_zerop (rhs))
3660 if (!ctx->quiet)
3661 error ("arithmetic involving a null pointer in %qE", lhs);
3662 *non_constant_p = true;
3663 return t;
3665 else if (code == POINTER_PLUS_EXPR)
3666 r = cxx_fold_pointer_plus_expression (ctx, t, lhs, rhs, non_constant_p,
3667 overflow_p);
3668 else if (code == SPACESHIP_EXPR)
3670 r = genericize_spaceship (loc, type, lhs, rhs);
3671 return cxx_eval_constant_expression (ctx, r, lval, non_constant_p,
3672 overflow_p);
3675 if (r == NULL_TREE)
3677 if (ctx->manifestly_const_eval
3678 && (flag_constexpr_fp_except
3679 || TREE_CODE (type) != REAL_TYPE))
3681 auto ofcc = make_temp_override (folding_cxx_constexpr, true);
3682 r = fold_binary_initializer_loc (loc, code, type, lhs, rhs);
3684 else
3685 r = fold_binary_loc (loc, code, type, lhs, rhs);
3688 if (r == NULL_TREE
3689 && (code == LSHIFT_EXPR || code == RSHIFT_EXPR)
3690 && TREE_CODE (lhs) == INTEGER_CST
3691 && TREE_CODE (rhs) == INTEGER_CST
3692 && wi::neg_p (wi::to_wide (rhs)))
3694 /* For diagnostics and -fpermissive emulate previous behavior of
3695 handling shifts by negative amount. */
3696 tree nrhs = const_unop (NEGATE_EXPR, TREE_TYPE (rhs), rhs);
3697 if (nrhs)
3698 r = fold_binary_loc (loc,
3699 code == LSHIFT_EXPR ? RSHIFT_EXPR : LSHIFT_EXPR,
3700 type, lhs, nrhs);
3703 if (r == NULL_TREE)
3705 if (lhs == orig_lhs && rhs == orig_rhs)
3706 r = t;
3707 else
3708 r = build2_loc (loc, code, type, lhs, rhs);
3710 else if (cxx_eval_check_shift_p (loc, ctx, code, type, lhs, rhs))
3711 *non_constant_p = true;
3712 /* Don't VERIFY_CONSTANT if this might be dealing with a pointer to
3713 a local array in a constexpr function. */
3714 bool ptr = INDIRECT_TYPE_P (TREE_TYPE (lhs));
3715 if (!ptr)
3716 VERIFY_CONSTANT (r);
3717 return r;
3720 /* Subroutine of cxx_eval_constant_expression.
3721 Attempt to evaluate condition expressions. Dead branches are not
3722 looked into. */
3724 static tree
3725 cxx_eval_conditional_expression (const constexpr_ctx *ctx, tree t,
3726 value_cat lval,
3727 bool *non_constant_p, bool *overflow_p,
3728 tree *jump_target)
3730 tree val = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
3731 vc_prvalue,
3732 non_constant_p, overflow_p);
3733 VERIFY_CONSTANT (val);
3734 if (TREE_CODE (t) == IF_STMT && IF_STMT_CONSTEVAL_P (t))
3736 /* Evaluate the condition as if it was
3737 if (__builtin_is_constant_evaluated ()), i.e. defer it if not
3738 ctx->manifestly_const_eval (as sometimes we try to constant evaluate
3739 without manifestly_const_eval even expressions or parts thereof which
3740 will later be manifestly const_eval evaluated), otherwise fold it to
3741 true. */
3742 if (ctx->manifestly_const_eval)
3743 val = boolean_true_node;
3744 else
3746 *non_constant_p = true;
3747 return t;
3750 /* Don't VERIFY_CONSTANT the other operands. */
3751 if (integer_zerop (val))
3752 val = TREE_OPERAND (t, 2);
3753 else
3754 val = TREE_OPERAND (t, 1);
3755 if (TREE_CODE (t) == IF_STMT && !val)
3756 val = void_node;
3757 /* A TARGET_EXPR may be nested inside another TARGET_EXPR, but still
3758 serve as the initializer for the same object as the outer TARGET_EXPR,
3759 as in
3760 A a = true ? A{} : A{};
3761 so strip the inner TARGET_EXPR so we don't materialize a temporary. */
3762 if (TREE_CODE (val) == TARGET_EXPR)
3763 val = TARGET_EXPR_INITIAL (val);
3764 return cxx_eval_constant_expression (ctx, val, lval, non_constant_p,
3765 overflow_p, jump_target);
3768 /* Subroutine of cxx_eval_constant_expression.
3769 Attempt to evaluate vector condition expressions. Unlike
3770 cxx_eval_conditional_expression, VEC_COND_EXPR acts like a normal
3771 ternary arithmetics operation, where all 3 arguments have to be
3772 evaluated as constants and then folding computes the result from
3773 them. */
3775 static tree
3776 cxx_eval_vector_conditional_expression (const constexpr_ctx *ctx, tree t,
3777 bool *non_constant_p, bool *overflow_p)
3779 tree arg1 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
3780 vc_prvalue,
3781 non_constant_p, overflow_p);
3782 VERIFY_CONSTANT (arg1);
3783 tree arg2 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
3784 vc_prvalue,
3785 non_constant_p, overflow_p);
3786 VERIFY_CONSTANT (arg2);
3787 tree arg3 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 2),
3788 vc_prvalue,
3789 non_constant_p, overflow_p);
3790 VERIFY_CONSTANT (arg3);
3791 location_t loc = EXPR_LOCATION (t);
3792 tree type = TREE_TYPE (t);
3793 tree r = fold_ternary_loc (loc, VEC_COND_EXPR, type, arg1, arg2, arg3);
3794 if (r == NULL_TREE)
3796 if (arg1 == TREE_OPERAND (t, 0)
3797 && arg2 == TREE_OPERAND (t, 1)
3798 && arg3 == TREE_OPERAND (t, 2))
3799 r = t;
3800 else
3801 r = build3_loc (loc, VEC_COND_EXPR, type, arg1, arg2, arg3);
3803 VERIFY_CONSTANT (r);
3804 return r;
3807 /* Returns less than, equal to, or greater than zero if KEY is found to be
3808 less than, to match, or to be greater than the constructor_elt's INDEX. */
3810 static int
3811 array_index_cmp (tree key, tree index)
3813 gcc_assert (TREE_CODE (key) == INTEGER_CST);
3815 switch (TREE_CODE (index))
3817 case INTEGER_CST:
3818 return tree_int_cst_compare (key, index);
3819 case RANGE_EXPR:
3821 tree lo = TREE_OPERAND (index, 0);
3822 tree hi = TREE_OPERAND (index, 1);
3823 if (tree_int_cst_lt (key, lo))
3824 return -1;
3825 else if (tree_int_cst_lt (hi, key))
3826 return 1;
3827 else
3828 return 0;
3830 default:
3831 gcc_unreachable ();
3835 /* Returns the index of the constructor_elt of ARY which matches DINDEX, or -1
3836 if none. If INSERT is true, insert a matching element rather than fail. */
3838 static HOST_WIDE_INT
3839 find_array_ctor_elt (tree ary, tree dindex, bool insert)
3841 if (tree_int_cst_sgn (dindex) < 0)
3842 return -1;
3844 unsigned HOST_WIDE_INT i = tree_to_uhwi (dindex);
3845 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ary);
3846 unsigned HOST_WIDE_INT len = vec_safe_length (elts);
3848 unsigned HOST_WIDE_INT end = len;
3849 unsigned HOST_WIDE_INT begin = 0;
3851 /* If the last element of the CONSTRUCTOR has its own index, we can assume
3852 that the same is true of the other elements and index directly. */
3853 if (end > 0)
3855 tree cindex = (*elts)[end - 1].index;
3856 if (cindex == NULL_TREE)
3858 /* Verify that if the last index is missing, all indexes
3859 are missing. */
3860 if (flag_checking)
3861 for (unsigned int j = 0; j < len - 1; ++j)
3862 gcc_assert ((*elts)[j].index == NULL_TREE);
3863 if (i < end)
3864 return i;
3865 else
3867 begin = end;
3868 if (i == end)
3869 /* If the element is to be added right at the end,
3870 make sure it is added with cleared index too. */
3871 dindex = NULL_TREE;
3872 else if (insert)
3873 /* Otherwise, in order not to break the assumption
3874 that CONSTRUCTOR either has all indexes or none,
3875 we need to add indexes to all elements. */
3876 for (unsigned int j = 0; j < len; ++j)
3877 (*elts)[j].index = build_int_cst (TREE_TYPE (dindex), j);
3880 else if (TREE_CODE (cindex) == INTEGER_CST
3881 && compare_tree_int (cindex, end - 1) == 0)
3883 if (i < end)
3884 return i;
3885 else
3886 begin = end;
3890 /* Otherwise, find a matching index by means of a binary search. */
3891 while (begin != end)
3893 unsigned HOST_WIDE_INT middle = (begin + end) / 2;
3894 constructor_elt &elt = (*elts)[middle];
3895 tree idx = elt.index;
3897 int cmp = array_index_cmp (dindex, idx);
3898 if (cmp < 0)
3899 end = middle;
3900 else if (cmp > 0)
3901 begin = middle + 1;
3902 else
3904 if (insert && TREE_CODE (idx) == RANGE_EXPR)
3906 /* We need to split the range. */
3907 constructor_elt e;
3908 tree lo = TREE_OPERAND (idx, 0);
3909 tree hi = TREE_OPERAND (idx, 1);
3910 tree value = elt.value;
3911 dindex = fold_convert (sizetype, dindex);
3912 if (tree_int_cst_lt (lo, dindex))
3914 /* There are still some lower elts; shorten the range. */
3915 tree new_hi = int_const_binop (MINUS_EXPR, dindex,
3916 size_one_node);
3917 if (tree_int_cst_equal (lo, new_hi))
3918 /* Only one element left, no longer a range. */
3919 elt.index = lo;
3920 else
3921 TREE_OPERAND (idx, 1) = new_hi;
3922 /* Append the element we want to insert. */
3923 ++middle;
3924 e.index = dindex;
3925 e.value = unshare_constructor (value);
3926 vec_safe_insert (CONSTRUCTOR_ELTS (ary), middle, e);
3928 else
3929 /* No lower elts, the range elt is now ours. */
3930 elt.index = dindex;
3932 if (tree_int_cst_lt (dindex, hi))
3934 /* There are still some higher elts; append a range. */
3935 tree new_lo = int_const_binop (PLUS_EXPR, dindex,
3936 size_one_node);
3937 if (tree_int_cst_equal (new_lo, hi))
3938 e.index = hi;
3939 else
3940 e.index = build2 (RANGE_EXPR, sizetype, new_lo, hi);
3941 e.value = unshare_constructor (value);
3942 vec_safe_insert (CONSTRUCTOR_ELTS (ary), middle + 1, e);
3945 return middle;
3949 if (insert)
3951 constructor_elt e = { dindex, NULL_TREE };
3952 vec_safe_insert (CONSTRUCTOR_ELTS (ary), end, e);
3953 return end;
3956 return -1;
3959 /* Return a pointer to the constructor_elt of CTOR which matches INDEX. If no
3960 matching constructor_elt exists, then add one to CTOR.
3962 As an optimization, if POS_HINT is non-negative then it is used as a guess
3963 for the (integer) index of the matching constructor_elt within CTOR. */
3965 static constructor_elt *
3966 get_or_insert_ctor_field (tree ctor, tree index, int pos_hint = -1)
3968 /* Check the hint first. */
3969 if (pos_hint >= 0 && (unsigned)pos_hint < CONSTRUCTOR_NELTS (ctor)
3970 && CONSTRUCTOR_ELT (ctor, pos_hint)->index == index)
3971 return CONSTRUCTOR_ELT (ctor, pos_hint);
3973 tree type = TREE_TYPE (ctor);
3974 if (TREE_CODE (type) == VECTOR_TYPE && index == NULL_TREE)
3976 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (ctor), index, NULL_TREE);
3977 return &CONSTRUCTOR_ELTS (ctor)->last();
3979 else if (TREE_CODE (type) == ARRAY_TYPE || TREE_CODE (type) == VECTOR_TYPE)
3981 if (TREE_CODE (index) == RANGE_EXPR)
3983 /* Support for RANGE_EXPR index lookups is currently limited to
3984 accessing an existing element via POS_HINT, or appending a new
3985 element to the end of CTOR. ??? Support for other access
3986 patterns may also be needed. */
3987 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ctor);
3988 if (vec_safe_length (elts))
3990 tree lo = TREE_OPERAND (index, 0);
3991 gcc_assert (array_index_cmp (elts->last().index, lo) < 0);
3993 CONSTRUCTOR_APPEND_ELT (elts, index, NULL_TREE);
3994 return &elts->last();
3997 HOST_WIDE_INT i = find_array_ctor_elt (ctor, index, /*insert*/true);
3998 gcc_assert (i >= 0);
3999 constructor_elt *cep = CONSTRUCTOR_ELT (ctor, i);
4000 gcc_assert (cep->index == NULL_TREE
4001 || TREE_CODE (cep->index) != RANGE_EXPR);
4002 return cep;
4004 else
4006 gcc_assert (TREE_CODE (index) == FIELD_DECL
4007 && (same_type_ignoring_top_level_qualifiers_p
4008 (DECL_CONTEXT (index), TREE_TYPE (ctor))));
4010 /* We must keep the CONSTRUCTOR's ELTS in FIELD order.
4011 Usually we meet initializers in that order, but it is
4012 possible for base types to be placed not in program
4013 order. */
4014 tree fields = TYPE_FIELDS (DECL_CONTEXT (index));
4015 unsigned HOST_WIDE_INT idx = 0;
4016 constructor_elt *cep = NULL;
4018 /* Check if we're changing the active member of a union. */
4019 if (TREE_CODE (type) == UNION_TYPE && CONSTRUCTOR_NELTS (ctor)
4020 && CONSTRUCTOR_ELT (ctor, 0)->index != index)
4021 vec_safe_truncate (CONSTRUCTOR_ELTS (ctor), 0);
4022 /* If the bit offset of INDEX is larger than that of the last
4023 constructor_elt, then we can just immediately append a new
4024 constructor_elt to the end of CTOR. */
4025 else if (CONSTRUCTOR_NELTS (ctor)
4026 && tree_int_cst_compare (bit_position (index),
4027 bit_position (CONSTRUCTOR_ELTS (ctor)
4028 ->last().index)) > 0)
4030 idx = CONSTRUCTOR_NELTS (ctor);
4031 goto insert;
4034 /* Otherwise, we need to iterate over CTOR to find or insert INDEX
4035 appropriately. */
4037 for (; vec_safe_iterate (CONSTRUCTOR_ELTS (ctor), idx, &cep);
4038 idx++, fields = DECL_CHAIN (fields))
4040 if (index == cep->index)
4041 goto found;
4043 /* The field we're initializing must be on the field
4044 list. Look to see if it is present before the
4045 field the current ELT initializes. */
4046 for (; fields != cep->index; fields = DECL_CHAIN (fields))
4047 if (index == fields)
4048 goto insert;
4050 /* We fell off the end of the CONSTRUCTOR, so insert a new
4051 entry at the end. */
4053 insert:
4055 constructor_elt ce = { index, NULL_TREE };
4057 vec_safe_insert (CONSTRUCTOR_ELTS (ctor), idx, ce);
4058 cep = CONSTRUCTOR_ELT (ctor, idx);
4060 found:;
4062 return cep;
4066 /* Under the control of CTX, issue a detailed diagnostic for
4067 an out-of-bounds subscript INDEX into the expression ARRAY. */
4069 static void
4070 diag_array_subscript (location_t loc, const constexpr_ctx *ctx, tree array, tree index)
4072 if (!ctx->quiet)
4074 tree arraytype = TREE_TYPE (array);
4076 /* Convert the unsigned array subscript to a signed integer to avoid
4077 printing huge numbers for small negative values. */
4078 tree sidx = fold_convert (ssizetype, index);
4079 STRIP_ANY_LOCATION_WRAPPER (array);
4080 if (DECL_P (array))
4082 if (TYPE_DOMAIN (arraytype))
4083 error_at (loc, "array subscript value %qE is outside the bounds "
4084 "of array %qD of type %qT", sidx, array, arraytype);
4085 else
4086 error_at (loc, "nonzero array subscript %qE is used with array %qD of "
4087 "type %qT with unknown bounds", sidx, array, arraytype);
4088 inform (DECL_SOURCE_LOCATION (array), "declared here");
4090 else if (TYPE_DOMAIN (arraytype))
4091 error_at (loc, "array subscript value %qE is outside the bounds "
4092 "of array type %qT", sidx, arraytype);
4093 else
4094 error_at (loc, "nonzero array subscript %qE is used with array of type %qT "
4095 "with unknown bounds", sidx, arraytype);
4099 /* Return the number of elements for TYPE (which is an ARRAY_TYPE or
4100 a VECTOR_TYPE). */
4102 static tree
4103 get_array_or_vector_nelts (const constexpr_ctx *ctx, tree type,
4104 bool *non_constant_p, bool *overflow_p)
4106 tree nelts;
4107 if (TREE_CODE (type) == ARRAY_TYPE)
4109 if (TYPE_DOMAIN (type))
4110 nelts = array_type_nelts_top (type);
4111 else
4112 nelts = size_zero_node;
4114 else if (VECTOR_TYPE_P (type))
4115 nelts = size_int (TYPE_VECTOR_SUBPARTS (type));
4116 else
4117 gcc_unreachable ();
4119 /* For VLAs, the number of elements won't be an integer constant. */
4120 nelts = cxx_eval_constant_expression (ctx, nelts, vc_prvalue,
4121 non_constant_p, overflow_p);
4122 return nelts;
4125 /* Extract element INDEX consisting of CHARS_PER_ELT chars from
4126 STRING_CST STRING. */
4128 static tree
4129 extract_string_elt (tree string, unsigned chars_per_elt, unsigned index)
4131 tree type = cv_unqualified (TREE_TYPE (TREE_TYPE (string)));
4132 tree r;
4134 if (chars_per_elt == 1)
4135 r = build_int_cst (type, TREE_STRING_POINTER (string)[index]);
4136 else
4138 const unsigned char *ptr
4139 = ((const unsigned char *)TREE_STRING_POINTER (string)
4140 + index * chars_per_elt);
4141 r = native_interpret_expr (type, ptr, chars_per_elt);
4143 return r;
4146 /* Subroutine of cxx_eval_array_reference. T is an ARRAY_REF; evaluate the
4147 subscript, diagnose any problems with it, and return the result. */
4149 static tree
4150 eval_and_check_array_index (const constexpr_ctx *ctx,
4151 tree t, bool allow_one_past,
4152 bool *non_constant_p, bool *overflow_p)
4154 location_t loc = cp_expr_loc_or_input_loc (t);
4155 tree ary = TREE_OPERAND (t, 0);
4156 t = TREE_OPERAND (t, 1);
4157 tree index = cxx_eval_constant_expression (ctx, t, vc_prvalue,
4158 non_constant_p, overflow_p);
4159 VERIFY_CONSTANT (index);
4161 if (!tree_fits_shwi_p (index)
4162 || tree_int_cst_sgn (index) < 0)
4164 diag_array_subscript (loc, ctx, ary, index);
4165 *non_constant_p = true;
4166 return t;
4169 tree nelts = get_array_or_vector_nelts (ctx, TREE_TYPE (ary), non_constant_p,
4170 overflow_p);
4171 VERIFY_CONSTANT (nelts);
4172 if (allow_one_past
4173 ? !tree_int_cst_le (index, nelts)
4174 : !tree_int_cst_lt (index, nelts))
4176 diag_array_subscript (loc, ctx, ary, index);
4177 *non_constant_p = true;
4178 return t;
4181 return index;
4184 /* Subroutine of cxx_eval_constant_expression.
4185 Attempt to reduce a reference to an array slot. */
4187 static tree
4188 cxx_eval_array_reference (const constexpr_ctx *ctx, tree t,
4189 value_cat lval,
4190 bool *non_constant_p, bool *overflow_p)
4192 tree oldary = TREE_OPERAND (t, 0);
4193 tree ary = cxx_eval_constant_expression (ctx, oldary,
4194 lval,
4195 non_constant_p, overflow_p);
4196 if (*non_constant_p)
4197 return t;
4198 if (!lval
4199 && TREE_CODE (ary) == VIEW_CONVERT_EXPR
4200 && VECTOR_TYPE_P (TREE_TYPE (TREE_OPERAND (ary, 0)))
4201 && TREE_TYPE (t) == TREE_TYPE (TREE_TYPE (TREE_OPERAND (ary, 0))))
4202 ary = TREE_OPERAND (ary, 0);
4204 tree oldidx = TREE_OPERAND (t, 1);
4205 tree index = eval_and_check_array_index (ctx, t, lval,
4206 non_constant_p, overflow_p);
4207 if (*non_constant_p)
4208 return t;
4210 if (lval && ary == oldary && index == oldidx)
4211 return t;
4212 else if (lval == vc_discard)
4213 return t;
4214 else if (lval)
4215 return build4 (ARRAY_REF, TREE_TYPE (t), ary, index, NULL, NULL);
4217 unsigned len = 0, elem_nchars = 1;
4218 tree elem_type = TREE_TYPE (TREE_TYPE (ary));
4219 if (TREE_CODE (ary) == CONSTRUCTOR)
4220 len = CONSTRUCTOR_NELTS (ary);
4221 else if (TREE_CODE (ary) == STRING_CST)
4223 elem_nchars = (TYPE_PRECISION (elem_type)
4224 / TYPE_PRECISION (char_type_node));
4225 len = (unsigned) TREE_STRING_LENGTH (ary) / elem_nchars;
4227 else if (TREE_CODE (ary) == VECTOR_CST)
4228 /* We don't create variable-length VECTOR_CSTs. */
4229 len = VECTOR_CST_NELTS (ary).to_constant ();
4230 else
4232 /* We can't do anything with other tree codes, so use
4233 VERIFY_CONSTANT to complain and fail. */
4234 VERIFY_CONSTANT (ary);
4235 gcc_unreachable ();
4238 bool found;
4239 HOST_WIDE_INT i = 0;
4240 if (TREE_CODE (ary) == CONSTRUCTOR)
4242 HOST_WIDE_INT ix = find_array_ctor_elt (ary, index);
4243 found = (ix >= 0);
4244 if (found)
4245 i = ix;
4247 else
4249 i = tree_to_shwi (index);
4250 found = (i < len);
4253 if (found)
4255 tree r;
4256 if (TREE_CODE (ary) == CONSTRUCTOR)
4257 r = (*CONSTRUCTOR_ELTS (ary))[i].value;
4258 else if (TREE_CODE (ary) == VECTOR_CST)
4259 r = VECTOR_CST_ELT (ary, i);
4260 else
4261 r = extract_string_elt (ary, elem_nchars, i);
4263 if (r)
4264 /* Don't VERIFY_CONSTANT here. */
4265 return r;
4267 /* Otherwise the element doesn't have a value yet. */
4270 /* Not found. */
4272 if (TREE_CODE (ary) == CONSTRUCTOR
4273 && CONSTRUCTOR_NO_CLEARING (ary))
4275 /* 'ary' is part of the aggregate initializer we're currently
4276 building; if there's no initializer for this element yet,
4277 that's an error. */
4278 if (!ctx->quiet)
4279 error ("accessing uninitialized array element");
4280 *non_constant_p = true;
4281 return t;
4284 /* If it's within the array bounds but doesn't have an explicit
4285 initializer, it's initialized from {}. But use build_value_init
4286 directly for non-aggregates to avoid creating a garbage CONSTRUCTOR. */
4287 tree val;
4288 constexpr_ctx new_ctx;
4289 if (is_really_empty_class (elem_type, /*ignore_vptr*/false))
4290 return build_constructor (elem_type, NULL);
4291 else if (CP_AGGREGATE_TYPE_P (elem_type))
4293 tree empty_ctor = build_constructor (init_list_type_node, NULL);
4294 val = digest_init (elem_type, empty_ctor, tf_warning_or_error);
4296 else
4297 val = build_value_init (elem_type, tf_warning_or_error);
4299 if (!SCALAR_TYPE_P (elem_type))
4301 new_ctx = *ctx;
4302 if (ctx->object)
4303 /* If there was no object, don't add one: it could confuse us
4304 into thinking we're modifying a const object. */
4305 new_ctx.object = t;
4306 new_ctx.ctor = build_constructor (elem_type, NULL);
4307 ctx = &new_ctx;
4309 t = cxx_eval_constant_expression (ctx, val, lval, non_constant_p,
4310 overflow_p);
4311 if (!SCALAR_TYPE_P (elem_type) && t != ctx->ctor)
4312 free_constructor (ctx->ctor);
4313 return t;
4316 /* Subroutine of cxx_eval_constant_expression.
4317 Attempt to reduce a field access of a value of class type. */
4319 static tree
4320 cxx_eval_component_reference (const constexpr_ctx *ctx, tree t,
4321 value_cat lval,
4322 bool *non_constant_p, bool *overflow_p)
4324 unsigned HOST_WIDE_INT i;
4325 tree field;
4326 tree value;
4327 tree part = TREE_OPERAND (t, 1);
4328 tree orig_whole = TREE_OPERAND (t, 0);
4329 tree whole = cxx_eval_constant_expression (ctx, orig_whole,
4330 lval,
4331 non_constant_p, overflow_p);
4332 if (*non_constant_p)
4333 return t;
4334 if (INDIRECT_REF_P (whole)
4335 && integer_zerop (TREE_OPERAND (whole, 0)))
4337 if (!ctx->quiet)
4338 error ("dereferencing a null pointer in %qE", orig_whole);
4339 *non_constant_p = true;
4340 return t;
4343 if (TREE_CODE (whole) == PTRMEM_CST)
4344 whole = cplus_expand_constant (whole);
4345 if (whole == orig_whole)
4346 return t;
4347 if (lval == vc_discard)
4348 return t;
4349 if (lval)
4350 return fold_build3 (COMPONENT_REF, TREE_TYPE (t),
4351 whole, part, NULL_TREE);
4352 /* Don't VERIFY_CONSTANT here; we only want to check that we got a
4353 CONSTRUCTOR. */
4354 if (TREE_CODE (whole) != CONSTRUCTOR)
4356 if (!ctx->quiet)
4357 error ("%qE is not a constant expression", orig_whole);
4358 *non_constant_p = true;
4359 return t;
4361 if ((cxx_dialect < cxx14 || CONSTRUCTOR_MUTABLE_POISON (whole))
4362 && DECL_MUTABLE_P (part))
4364 if (!ctx->quiet)
4365 error ("mutable %qD is not usable in a constant expression", part);
4366 *non_constant_p = true;
4367 return t;
4369 bool pmf = TYPE_PTRMEMFUNC_P (TREE_TYPE (whole));
4370 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
4372 /* Use name match for PMF fields, as a variant will have a
4373 different FIELD_DECL with a different type. */
4374 if (pmf ? DECL_NAME (field) == DECL_NAME (part)
4375 : field == part)
4377 if (value)
4379 STRIP_ANY_LOCATION_WRAPPER (value);
4380 return value;
4382 else
4383 /* We're in the middle of initializing it. */
4384 break;
4387 if (TREE_CODE (TREE_TYPE (whole)) == UNION_TYPE
4388 && CONSTRUCTOR_NELTS (whole) > 0)
4390 /* DR 1188 says we don't have to deal with this. */
4391 if (!ctx->quiet)
4393 constructor_elt *cep = CONSTRUCTOR_ELT (whole, 0);
4394 if (cep->value == NULL_TREE)
4395 error ("accessing uninitialized member %qD", part);
4396 else
4397 error ("accessing %qD member instead of initialized %qD member in "
4398 "constant expression", part, cep->index);
4400 *non_constant_p = true;
4401 return t;
4404 /* We only create a CONSTRUCTOR for a subobject when we modify it, so empty
4405 classes never get represented; throw together a value now. */
4406 if (is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
4407 return build_constructor (TREE_TYPE (t), NULL);
4409 gcc_assert (DECL_CONTEXT (part) == TYPE_MAIN_VARIANT (TREE_TYPE (whole)));
4411 if (CONSTRUCTOR_NO_CLEARING (whole))
4413 /* 'whole' is part of the aggregate initializer we're currently
4414 building; if there's no initializer for this member yet, that's an
4415 error. */
4416 if (!ctx->quiet)
4417 error ("accessing uninitialized member %qD", part);
4418 *non_constant_p = true;
4419 return t;
4422 /* If there's no explicit init for this field, it's value-initialized. */
4423 value = build_value_init (TREE_TYPE (t), tf_warning_or_error);
4424 return cxx_eval_constant_expression (ctx, value,
4425 lval,
4426 non_constant_p, overflow_p);
4429 /* Subroutine of cxx_eval_constant_expression.
4430 Attempt to reduce a field access of a value of class type that is
4431 expressed as a BIT_FIELD_REF. */
4433 static tree
4434 cxx_eval_bit_field_ref (const constexpr_ctx *ctx, tree t,
4435 value_cat lval,
4436 bool *non_constant_p, bool *overflow_p)
4438 tree orig_whole = TREE_OPERAND (t, 0);
4439 tree retval, fldval, utype, mask;
4440 bool fld_seen = false;
4441 HOST_WIDE_INT istart, isize;
4442 tree whole = cxx_eval_constant_expression (ctx, orig_whole,
4443 lval,
4444 non_constant_p, overflow_p);
4445 tree start, field, value;
4446 unsigned HOST_WIDE_INT i;
4448 if (whole == orig_whole)
4449 return t;
4450 /* Don't VERIFY_CONSTANT here; we only want to check that we got a
4451 CONSTRUCTOR. */
4452 if (!*non_constant_p
4453 && TREE_CODE (whole) != VECTOR_CST
4454 && TREE_CODE (whole) != CONSTRUCTOR)
4456 if (!ctx->quiet)
4457 error ("%qE is not a constant expression", orig_whole);
4458 *non_constant_p = true;
4460 if (*non_constant_p)
4461 return t;
4463 if (TREE_CODE (whole) == VECTOR_CST || !INTEGRAL_TYPE_P (TREE_TYPE (t)))
4465 if (tree r = fold_ternary (BIT_FIELD_REF, TREE_TYPE (t), whole,
4466 TREE_OPERAND (t, 1), TREE_OPERAND (t, 2)))
4467 return r;
4468 if (!ctx->quiet)
4469 error ("%qE is not a constant expression", orig_whole);
4470 *non_constant_p = true;
4471 return t;
4474 start = TREE_OPERAND (t, 2);
4475 istart = tree_to_shwi (start);
4476 isize = tree_to_shwi (TREE_OPERAND (t, 1));
4477 utype = TREE_TYPE (t);
4478 if (!TYPE_UNSIGNED (utype))
4479 utype = build_nonstandard_integer_type (TYPE_PRECISION (utype), 1);
4480 retval = build_int_cst (utype, 0);
4481 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
4483 tree bitpos = bit_position (field);
4484 STRIP_ANY_LOCATION_WRAPPER (value);
4485 if (bitpos == start && DECL_SIZE (field) == TREE_OPERAND (t, 1))
4486 return value;
4487 if (TREE_CODE (TREE_TYPE (field)) == INTEGER_TYPE
4488 && TREE_CODE (value) == INTEGER_CST
4489 && tree_fits_shwi_p (bitpos)
4490 && tree_fits_shwi_p (DECL_SIZE (field)))
4492 HOST_WIDE_INT bit = tree_to_shwi (bitpos);
4493 HOST_WIDE_INT sz = tree_to_shwi (DECL_SIZE (field));
4494 HOST_WIDE_INT shift;
4495 if (bit >= istart && bit + sz <= istart + isize)
4497 fldval = fold_convert (utype, value);
4498 mask = build_int_cst_type (utype, -1);
4499 mask = fold_build2 (LSHIFT_EXPR, utype, mask,
4500 size_int (TYPE_PRECISION (utype) - sz));
4501 mask = fold_build2 (RSHIFT_EXPR, utype, mask,
4502 size_int (TYPE_PRECISION (utype) - sz));
4503 fldval = fold_build2 (BIT_AND_EXPR, utype, fldval, mask);
4504 shift = bit - istart;
4505 if (BYTES_BIG_ENDIAN)
4506 shift = TYPE_PRECISION (utype) - shift - sz;
4507 fldval = fold_build2 (LSHIFT_EXPR, utype, fldval,
4508 size_int (shift));
4509 retval = fold_build2 (BIT_IOR_EXPR, utype, retval, fldval);
4510 fld_seen = true;
4514 if (fld_seen)
4515 return fold_convert (TREE_TYPE (t), retval);
4516 gcc_unreachable ();
4517 return error_mark_node;
4520 /* Helper for cxx_eval_bit_cast.
4521 Check [bit.cast]/3 rules, bit_cast is constexpr only if the To and From
4522 types and types of all subobjects have is_union_v<T>, is_pointer_v<T>,
4523 is_member_pointer_v<T>, is_volatile_v<T> false and has no non-static
4524 data members of reference type. */
4526 static bool
4527 check_bit_cast_type (const constexpr_ctx *ctx, location_t loc, tree type,
4528 tree orig_type)
4530 if (TREE_CODE (type) == UNION_TYPE)
4532 if (!ctx->quiet)
4534 if (type == orig_type)
4535 error_at (loc, "%qs is not a constant expression because %qT is "
4536 "a union type", "__builtin_bit_cast", type);
4537 else
4538 error_at (loc, "%qs is not a constant expression because %qT "
4539 "contains a union type", "__builtin_bit_cast",
4540 orig_type);
4542 return true;
4544 if (TREE_CODE (type) == POINTER_TYPE)
4546 if (!ctx->quiet)
4548 if (type == orig_type)
4549 error_at (loc, "%qs is not a constant expression because %qT is "
4550 "a pointer type", "__builtin_bit_cast", type);
4551 else
4552 error_at (loc, "%qs is not a constant expression because %qT "
4553 "contains a pointer type", "__builtin_bit_cast",
4554 orig_type);
4556 return true;
4558 if (TREE_CODE (type) == REFERENCE_TYPE)
4560 if (!ctx->quiet)
4562 if (type == orig_type)
4563 error_at (loc, "%qs is not a constant expression because %qT is "
4564 "a reference type", "__builtin_bit_cast", type);
4565 else
4566 error_at (loc, "%qs is not a constant expression because %qT "
4567 "contains a reference type", "__builtin_bit_cast",
4568 orig_type);
4570 return true;
4572 if (TYPE_PTRMEM_P (type))
4574 if (!ctx->quiet)
4576 if (type == orig_type)
4577 error_at (loc, "%qs is not a constant expression because %qT is "
4578 "a pointer to member type", "__builtin_bit_cast",
4579 type);
4580 else
4581 error_at (loc, "%qs is not a constant expression because %qT "
4582 "contains a pointer to member type",
4583 "__builtin_bit_cast", orig_type);
4585 return true;
4587 if (TYPE_VOLATILE (type))
4589 if (!ctx->quiet)
4591 if (type == orig_type)
4592 error_at (loc, "%qs is not a constant expression because %qT is "
4593 "volatile", "__builtin_bit_cast", type);
4594 else
4595 error_at (loc, "%qs is not a constant expression because %qT "
4596 "contains a volatile subobject",
4597 "__builtin_bit_cast", orig_type);
4599 return true;
4601 if (TREE_CODE (type) == RECORD_TYPE)
4602 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
4603 if (TREE_CODE (field) == FIELD_DECL
4604 && check_bit_cast_type (ctx, loc, TREE_TYPE (field), orig_type))
4605 return true;
4606 return false;
4609 /* Helper function for cxx_eval_bit_cast. For unsigned char or
4610 std::byte members of CONSTRUCTOR (recursively) if they contain
4611 some indeterminate bits (as set in MASK), remove the ctor elts,
4612 mark the CONSTRUCTOR as CONSTRUCTOR_NO_CLEARING and clear the
4613 bits in MASK. */
4615 static void
4616 clear_uchar_or_std_byte_in_mask (location_t loc, tree t, unsigned char *mask)
4618 if (TREE_CODE (t) != CONSTRUCTOR)
4619 return;
4621 unsigned i, j = 0;
4622 tree index, value;
4623 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (t), i, index, value)
4625 tree type = TREE_TYPE (value);
4626 if (TREE_CODE (TREE_TYPE (t)) != ARRAY_TYPE
4627 && DECL_BIT_FIELD_TYPE (index) != NULL_TREE)
4629 if (is_byte_access_type_not_plain_char (DECL_BIT_FIELD_TYPE (index)))
4631 HOST_WIDE_INT fldsz = TYPE_PRECISION (TREE_TYPE (index));
4632 gcc_assert (fldsz != 0);
4633 HOST_WIDE_INT pos = int_byte_position (index);
4634 HOST_WIDE_INT bpos
4635 = tree_to_uhwi (DECL_FIELD_BIT_OFFSET (index));
4636 bpos %= BITS_PER_UNIT;
4637 HOST_WIDE_INT end
4638 = ROUND_UP (bpos + fldsz, BITS_PER_UNIT) / BITS_PER_UNIT;
4639 gcc_assert (end == 1 || end == 2);
4640 unsigned char *p = mask + pos;
4641 unsigned char mask_save[2];
4642 mask_save[0] = mask[pos];
4643 mask_save[1] = end == 2 ? mask[pos + 1] : 0;
4644 if (BYTES_BIG_ENDIAN != WORDS_BIG_ENDIAN)
4645 sorry_at (loc, "PDP11 bit-field handling unsupported"
4646 " in %qs", "__builtin_bit_cast");
4647 else if (BYTES_BIG_ENDIAN)
4649 /* Big endian. */
4650 if (bpos + fldsz <= BITS_PER_UNIT)
4651 *p &= ~(((1 << fldsz) - 1)
4652 << (BITS_PER_UNIT - bpos - fldsz));
4653 else
4655 gcc_assert (bpos);
4656 *p &= ~(((1U << BITS_PER_UNIT) - 1) >> bpos);
4657 p++;
4658 fldsz -= BITS_PER_UNIT - bpos;
4659 gcc_assert (fldsz && fldsz < BITS_PER_UNIT);
4660 *p &= ((1U << BITS_PER_UNIT) - 1) >> fldsz;
4663 else
4665 /* Little endian. */
4666 if (bpos + fldsz <= BITS_PER_UNIT)
4667 *p &= ~(((1 << fldsz) - 1) << bpos);
4668 else
4670 gcc_assert (bpos);
4671 *p &= ~(((1 << BITS_PER_UNIT) - 1) << bpos);
4672 p++;
4673 fldsz -= BITS_PER_UNIT - bpos;
4674 gcc_assert (fldsz && fldsz < BITS_PER_UNIT);
4675 *p &= ~((1 << fldsz) - 1);
4678 if (mask_save[0] != mask[pos]
4679 || (end == 2 && mask_save[1] != mask[pos + 1]))
4681 CONSTRUCTOR_NO_CLEARING (t) = 1;
4682 continue;
4686 else if (is_byte_access_type_not_plain_char (type))
4688 HOST_WIDE_INT pos;
4689 if (TREE_CODE (TREE_TYPE (t)) == ARRAY_TYPE)
4690 pos = tree_to_shwi (index);
4691 else
4692 pos = int_byte_position (index);
4693 if (mask[pos])
4695 CONSTRUCTOR_NO_CLEARING (t) = 1;
4696 mask[pos] = 0;
4697 continue;
4700 if (TREE_CODE (value) == CONSTRUCTOR)
4702 HOST_WIDE_INT pos;
4703 if (TREE_CODE (TREE_TYPE (t)) == ARRAY_TYPE)
4704 pos = tree_to_shwi (index)
4705 * tree_to_shwi (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (t))));
4706 else
4707 pos = int_byte_position (index);
4708 clear_uchar_or_std_byte_in_mask (loc, value, mask + pos);
4710 if (i != j)
4712 CONSTRUCTOR_ELT (t, j)->index = index;
4713 CONSTRUCTOR_ELT (t, j)->value = value;
4715 ++j;
4717 if (CONSTRUCTOR_NELTS (t) != j)
4718 vec_safe_truncate (CONSTRUCTOR_ELTS (t), j);
4721 /* Subroutine of cxx_eval_constant_expression.
4722 Attempt to evaluate a BIT_CAST_EXPR. */
4724 static tree
4725 cxx_eval_bit_cast (const constexpr_ctx *ctx, tree t, bool *non_constant_p,
4726 bool *overflow_p)
4728 if (check_bit_cast_type (ctx, EXPR_LOCATION (t), TREE_TYPE (t),
4729 TREE_TYPE (t))
4730 || check_bit_cast_type (ctx, cp_expr_loc_or_loc (TREE_OPERAND (t, 0),
4731 EXPR_LOCATION (t)),
4732 TREE_TYPE (TREE_OPERAND (t, 0)),
4733 TREE_TYPE (TREE_OPERAND (t, 0))))
4735 *non_constant_p = true;
4736 return t;
4739 tree op = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), vc_prvalue,
4740 non_constant_p, overflow_p);
4741 if (*non_constant_p)
4742 return t;
4744 location_t loc = EXPR_LOCATION (t);
4745 if (BITS_PER_UNIT != 8 || CHAR_BIT != 8)
4747 if (!ctx->quiet)
4748 sorry_at (loc, "%qs cannot be constant evaluated on the target",
4749 "__builtin_bit_cast");
4750 *non_constant_p = true;
4751 return t;
4754 if (!tree_fits_shwi_p (TYPE_SIZE_UNIT (TREE_TYPE (t))))
4756 if (!ctx->quiet)
4757 sorry_at (loc, "%qs cannot be constant evaluated because the "
4758 "type is too large", "__builtin_bit_cast");
4759 *non_constant_p = true;
4760 return t;
4763 HOST_WIDE_INT len = tree_to_shwi (TYPE_SIZE_UNIT (TREE_TYPE (t)));
4764 if (len < 0 || (int) len != len)
4766 if (!ctx->quiet)
4767 sorry_at (loc, "%qs cannot be constant evaluated because the "
4768 "type is too large", "__builtin_bit_cast");
4769 *non_constant_p = true;
4770 return t;
4773 unsigned char buf[64];
4774 unsigned char *ptr, *mask;
4775 size_t alen = (size_t) len * 2;
4776 if (alen <= sizeof (buf))
4777 ptr = buf;
4778 else
4779 ptr = XNEWVEC (unsigned char, alen);
4780 mask = ptr + (size_t) len;
4781 /* At the beginning consider everything indeterminate. */
4782 memset (mask, ~0, (size_t) len);
4784 if (native_encode_initializer (op, ptr, len, 0, mask) != len)
4786 if (!ctx->quiet)
4787 sorry_at (loc, "%qs cannot be constant evaluated because the "
4788 "argument cannot be encoded", "__builtin_bit_cast");
4789 *non_constant_p = true;
4790 if (ptr != buf)
4791 XDELETE (ptr);
4792 return t;
4795 tree r = NULL_TREE;
4796 if (can_native_interpret_type_p (TREE_TYPE (t)))
4798 r = native_interpret_expr (TREE_TYPE (t), ptr, len);
4799 if (is_byte_access_type_not_plain_char (TREE_TYPE (t)))
4801 gcc_assert (len == 1);
4802 if (mask[0])
4804 memset (mask, 0, len);
4805 r = build_constructor (TREE_TYPE (r), NULL);
4806 CONSTRUCTOR_NO_CLEARING (r) = 1;
4810 else if (TREE_CODE (TREE_TYPE (t)) == RECORD_TYPE)
4812 r = native_interpret_aggregate (TREE_TYPE (t), ptr, 0, len);
4813 if (r != NULL_TREE)
4815 clear_type_padding_in_mask (TREE_TYPE (t), mask);
4816 clear_uchar_or_std_byte_in_mask (loc, r, mask);
4820 if (r != NULL_TREE)
4822 for (int i = 0; i < len; i++)
4823 if (mask[i])
4825 if (!ctx->quiet)
4826 error_at (loc, "%qs accessing uninitialized byte at offset %d",
4827 "__builtin_bit_cast", i);
4828 *non_constant_p = true;
4829 r = t;
4830 break;
4832 if (ptr != buf)
4833 XDELETE (ptr);
4834 return r;
4837 if (!ctx->quiet)
4838 sorry_at (loc, "%qs cannot be constant evaluated because the "
4839 "argument cannot be interpreted", "__builtin_bit_cast");
4840 *non_constant_p = true;
4841 if (ptr != buf)
4842 XDELETE (ptr);
4843 return t;
4846 /* Subroutine of cxx_eval_constant_expression.
4847 Evaluate a short-circuited logical expression T in the context
4848 of a given constexpr CALL. BAILOUT_VALUE is the value for
4849 early return. CONTINUE_VALUE is used here purely for
4850 sanity check purposes. */
4852 static tree
4853 cxx_eval_logical_expression (const constexpr_ctx *ctx, tree t,
4854 tree bailout_value, tree continue_value,
4855 bool *non_constant_p, bool *overflow_p)
4857 tree r;
4858 tree lhs = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
4859 vc_prvalue, non_constant_p,
4860 overflow_p);
4861 VERIFY_CONSTANT (lhs);
4862 if (tree_int_cst_equal (lhs, bailout_value))
4863 return lhs;
4864 gcc_assert (tree_int_cst_equal (lhs, continue_value));
4865 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
4866 vc_prvalue, non_constant_p,
4867 overflow_p);
4868 VERIFY_CONSTANT (r);
4869 return r;
4872 /* REF is a COMPONENT_REF designating a particular field. V is a vector of
4873 CONSTRUCTOR elements to initialize (part of) an object containing that
4874 field. Return a pointer to the constructor_elt corresponding to the
4875 initialization of the field. */
4877 static constructor_elt *
4878 base_field_constructor_elt (vec<constructor_elt, va_gc> *v, tree ref)
4880 tree aggr = TREE_OPERAND (ref, 0);
4881 tree field = TREE_OPERAND (ref, 1);
4882 HOST_WIDE_INT i;
4883 constructor_elt *ce;
4885 gcc_assert (TREE_CODE (ref) == COMPONENT_REF);
4887 if (TREE_CODE (aggr) == COMPONENT_REF)
4889 constructor_elt *base_ce
4890 = base_field_constructor_elt (v, aggr);
4891 v = CONSTRUCTOR_ELTS (base_ce->value);
4894 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
4895 if (ce->index == field)
4896 return ce;
4898 gcc_unreachable ();
4899 return NULL;
4902 /* Some of the expressions fed to the constexpr mechanism are calls to
4903 constructors, which have type void. In that case, return the type being
4904 initialized by the constructor. */
4906 static tree
4907 initialized_type (tree t)
4909 if (TYPE_P (t))
4910 return t;
4911 tree type = TREE_TYPE (t);
4912 if (TREE_CODE (t) == CALL_EXPR)
4914 /* A constructor call has void type, so we need to look deeper. */
4915 tree fn = get_function_named_in_call (t);
4916 if (fn && TREE_CODE (fn) == FUNCTION_DECL
4917 && DECL_CXX_CONSTRUCTOR_P (fn))
4918 type = DECL_CONTEXT (fn);
4920 else if (TREE_CODE (t) == COMPOUND_EXPR)
4921 return initialized_type (TREE_OPERAND (t, 1));
4922 else if (TREE_CODE (t) == AGGR_INIT_EXPR)
4923 type = TREE_TYPE (AGGR_INIT_EXPR_SLOT (t));
4924 return cv_unqualified (type);
4927 /* We're about to initialize element INDEX of an array or class from VALUE.
4928 Set up NEW_CTX appropriately by adjusting .object to refer to the
4929 subobject and creating a new CONSTRUCTOR if the element is itself
4930 a class or array. */
4932 static void
4933 init_subob_ctx (const constexpr_ctx *ctx, constexpr_ctx &new_ctx,
4934 tree index, tree &value)
4936 new_ctx = *ctx;
4938 if (index && TREE_CODE (index) != INTEGER_CST
4939 && TREE_CODE (index) != FIELD_DECL
4940 && TREE_CODE (index) != RANGE_EXPR)
4941 /* This won't have an element in the new CONSTRUCTOR. */
4942 return;
4944 tree type = initialized_type (value);
4945 if (!AGGREGATE_TYPE_P (type) && !VECTOR_TYPE_P (type))
4946 /* A non-aggregate member doesn't get its own CONSTRUCTOR. */
4947 return;
4948 if (VECTOR_TYPE_P (type)
4949 && VECTOR_TYPE_P (TREE_TYPE (ctx->ctor))
4950 && index == NULL_TREE)
4951 /* A vector inside of a vector CONSTRUCTOR, e.g. when a larger
4952 vector is constructed from smaller vectors, doesn't get its own
4953 CONSTRUCTOR either. */
4954 return;
4956 /* The sub-aggregate initializer might contain a placeholder;
4957 update object to refer to the subobject and ctor to refer to
4958 the (newly created) sub-initializer. */
4959 if (ctx->object)
4961 if (index == NULL_TREE || TREE_CODE (index) == RANGE_EXPR)
4962 /* There's no well-defined subobject for this index. */
4963 new_ctx.object = NULL_TREE;
4964 else
4965 new_ctx.object = build_ctor_subob_ref (index, type, ctx->object);
4968 if (is_empty_class (type))
4969 /* Leave ctor null for an empty subobject, they aren't represented in the
4970 result of evaluation. */
4971 new_ctx.ctor = NULL_TREE;
4972 else
4974 tree elt = build_constructor (type, NULL);
4975 CONSTRUCTOR_NO_CLEARING (elt) = true;
4976 new_ctx.ctor = elt;
4979 if (TREE_CODE (value) == TARGET_EXPR)
4980 /* Avoid creating another CONSTRUCTOR when we expand the TARGET_EXPR. */
4981 value = TARGET_EXPR_INITIAL (value);
4984 /* We're about to process an initializer for a class or array TYPE. Make
4985 sure that CTX is set up appropriately. */
4987 static void
4988 verify_ctor_sanity (const constexpr_ctx *ctx, tree type)
4990 /* We don't bother building a ctor for an empty base subobject. */
4991 if (is_empty_class (type))
4992 return;
4994 /* We're in the middle of an initializer that might involve placeholders;
4995 our caller should have created a CONSTRUCTOR for us to put the
4996 initializer into. We will either return that constructor or T. */
4997 gcc_assert (ctx->ctor);
4998 gcc_assert (same_type_ignoring_top_level_qualifiers_p
4999 (type, TREE_TYPE (ctx->ctor)));
5000 /* We used to check that ctx->ctor was empty, but that isn't the case when
5001 the object is zero-initialized before calling the constructor. */
5002 if (ctx->object)
5004 tree otype = TREE_TYPE (ctx->object);
5005 gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, otype)
5006 /* Handle flexible array members. */
5007 || (TREE_CODE (otype) == ARRAY_TYPE
5008 && TYPE_DOMAIN (otype) == NULL_TREE
5009 && TREE_CODE (type) == ARRAY_TYPE
5010 && (same_type_ignoring_top_level_qualifiers_p
5011 (TREE_TYPE (type), TREE_TYPE (otype)))));
5013 gcc_assert (!ctx->object || !DECL_P (ctx->object)
5014 || ctx->global->get_value (ctx->object) == ctx->ctor);
5017 /* Subroutine of cxx_eval_constant_expression.
5018 The expression tree T denotes a C-style array or a C-style
5019 aggregate. Reduce it to a constant expression. */
5021 static tree
5022 cxx_eval_bare_aggregate (const constexpr_ctx *ctx, tree t,
5023 value_cat lval,
5024 bool *non_constant_p, bool *overflow_p)
5026 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
5027 bool changed = false;
5028 gcc_assert (!BRACE_ENCLOSED_INITIALIZER_P (t));
5029 tree type = TREE_TYPE (t);
5031 constexpr_ctx new_ctx;
5032 if (TYPE_PTRMEMFUNC_P (type) || VECTOR_TYPE_P (type))
5034 /* We don't really need the ctx->ctor business for a PMF or
5035 vector, but it's simpler to use the same code. */
5036 new_ctx = *ctx;
5037 new_ctx.ctor = build_constructor (type, NULL);
5038 new_ctx.object = NULL_TREE;
5039 ctx = &new_ctx;
5041 verify_ctor_sanity (ctx, type);
5042 vec<constructor_elt, va_gc> **p = nullptr;
5043 if (ctx->ctor)
5045 p = &CONSTRUCTOR_ELTS (ctx->ctor);
5046 vec_alloc (*p, vec_safe_length (v));
5047 if (CONSTRUCTOR_PLACEHOLDER_BOUNDARY (t))
5048 CONSTRUCTOR_PLACEHOLDER_BOUNDARY (ctx->ctor) = 1;
5051 unsigned i;
5052 tree index, value;
5053 bool constant_p = true;
5054 bool side_effects_p = false;
5055 FOR_EACH_CONSTRUCTOR_ELT (v, i, index, value)
5057 tree orig_value = value;
5058 /* Like in cxx_eval_store_expression, omit entries for empty fields. */
5059 bool no_slot = TREE_CODE (type) == RECORD_TYPE && is_empty_field (index);
5060 init_subob_ctx (ctx, new_ctx, index, value);
5061 int pos_hint = -1;
5062 if (new_ctx.ctor != ctx->ctor && !no_slot)
5064 /* If we built a new CONSTRUCTOR, attach it now so that other
5065 initializers can refer to it. */
5066 constructor_elt *cep = get_or_insert_ctor_field (ctx->ctor, index);
5067 cep->value = new_ctx.ctor;
5068 pos_hint = cep - (*p)->begin();
5070 else if (TREE_CODE (type) == UNION_TYPE)
5071 /* Otherwise if we're constructing a non-aggregate union member, set
5072 the active union member now so that we can later detect and diagnose
5073 if its initializer attempts to activate another member. */
5074 get_or_insert_ctor_field (ctx->ctor, index);
5075 tree elt = cxx_eval_constant_expression (&new_ctx, value,
5076 lval,
5077 non_constant_p, overflow_p);
5078 /* Don't VERIFY_CONSTANT here. */
5079 if (ctx->quiet && *non_constant_p)
5080 break;
5081 if (elt != orig_value)
5082 changed = true;
5084 if (!TREE_CONSTANT (elt))
5085 constant_p = false;
5086 if (TREE_SIDE_EFFECTS (elt))
5087 side_effects_p = true;
5088 if (index && TREE_CODE (index) == COMPONENT_REF)
5090 /* This is an initialization of a vfield inside a base
5091 subaggregate that we already initialized; push this
5092 initialization into the previous initialization. */
5093 constructor_elt *inner = base_field_constructor_elt (*p, index);
5094 inner->value = elt;
5095 changed = true;
5097 else if (no_slot)
5098 /* This is an initializer for an empty field; now that we've
5099 checked that it's constant, we can ignore it. */
5100 changed = true;
5101 else if (index
5102 && (TREE_CODE (index) == NOP_EXPR
5103 || TREE_CODE (index) == POINTER_PLUS_EXPR))
5105 /* Old representation of empty bases. FIXME remove. */
5106 gcc_checking_assert (false);
5107 gcc_assert (is_empty_class (TREE_TYPE (TREE_TYPE (index))));
5108 changed = true;
5110 else
5112 if (TREE_CODE (type) == UNION_TYPE
5113 && (*p)->last().index != index)
5114 /* The initializer erroneously changed the active union member that
5115 we're initializing. */
5116 gcc_assert (*non_constant_p);
5117 else
5119 /* The initializer might have mutated the underlying CONSTRUCTOR,
5120 so recompute the location of the target constructer_elt. */
5121 constructor_elt *cep
5122 = get_or_insert_ctor_field (ctx->ctor, index, pos_hint);
5123 cep->value = elt;
5126 /* Adding or replacing an element might change the ctor's flags. */
5127 TREE_CONSTANT (ctx->ctor) = constant_p;
5128 TREE_SIDE_EFFECTS (ctx->ctor) = side_effects_p;
5131 if (*non_constant_p)
5132 return t;
5133 if (!changed)
5135 if (VECTOR_TYPE_P (type))
5136 t = fold (t);
5137 return t;
5139 t = ctx->ctor;
5140 if (!t)
5141 t = build_constructor (type, NULL);
5142 /* We're done building this CONSTRUCTOR, so now we can interpret an
5143 element without an explicit initializer as value-initialized. */
5144 CONSTRUCTOR_NO_CLEARING (t) = false;
5145 TREE_CONSTANT (t) = constant_p;
5146 TREE_SIDE_EFFECTS (t) = side_effects_p;
5147 if (VECTOR_TYPE_P (type))
5148 t = fold (t);
5149 return t;
5152 /* Subroutine of cxx_eval_constant_expression.
5153 The expression tree T is a VEC_INIT_EXPR which denotes the desired
5154 initialization of a non-static data member of array type. Reduce it to a
5155 CONSTRUCTOR.
5157 Note that apart from value-initialization (when VALUE_INIT is true),
5158 this is only intended to support value-initialization and the
5159 initializations done by defaulted constructors for classes with
5160 non-static data members of array type. In this case, VEC_INIT_EXPR_INIT
5161 will either be NULL_TREE for the default constructor, or a COMPONENT_REF
5162 for the copy/move constructor. */
5164 static tree
5165 cxx_eval_vec_init_1 (const constexpr_ctx *ctx, tree atype, tree init,
5166 bool value_init, value_cat lval,
5167 bool *non_constant_p, bool *overflow_p)
5169 tree elttype = TREE_TYPE (atype);
5170 verify_ctor_sanity (ctx, atype);
5171 vec<constructor_elt, va_gc> **p = &CONSTRUCTOR_ELTS (ctx->ctor);
5172 bool pre_init = false;
5173 unsigned HOST_WIDE_INT i;
5174 tsubst_flags_t complain = ctx->quiet ? tf_none : tf_warning_or_error;
5176 if (init && TREE_CODE (init) == CONSTRUCTOR)
5177 return cxx_eval_bare_aggregate (ctx, init, lval,
5178 non_constant_p, overflow_p);
5180 /* For the default constructor, build up a call to the default
5181 constructor of the element type. We only need to handle class types
5182 here, as for a constructor to be constexpr, all members must be
5183 initialized, which for a defaulted default constructor means they must
5184 be of a class type with a constexpr default constructor. */
5185 if (TREE_CODE (elttype) == ARRAY_TYPE)
5186 /* We only do this at the lowest level. */;
5187 else if (value_init)
5189 init = build_value_init (elttype, complain);
5190 pre_init = true;
5192 else if (!init)
5194 releasing_vec argvec;
5195 init = build_special_member_call (NULL_TREE, complete_ctor_identifier,
5196 &argvec, elttype, LOOKUP_NORMAL,
5197 complain);
5198 init = build_aggr_init_expr (elttype, init);
5199 pre_init = true;
5202 bool zeroed_out = false;
5203 if (!CONSTRUCTOR_NO_CLEARING (ctx->ctor))
5205 /* We're initializing an array object that had been zero-initialized
5206 earlier. Truncate ctx->ctor, and propagate its zeroed state by
5207 clearing CONSTRUCTOR_NO_CLEARING on each of the aggregate element
5208 initializers we append to it. */
5209 gcc_checking_assert (initializer_zerop (ctx->ctor));
5210 zeroed_out = true;
5211 vec_safe_truncate (*p, 0);
5214 tree nelts = get_array_or_vector_nelts (ctx, atype, non_constant_p,
5215 overflow_p);
5216 unsigned HOST_WIDE_INT max = tree_to_uhwi (nelts);
5217 for (i = 0; i < max; ++i)
5219 tree idx = build_int_cst (size_type_node, i);
5220 tree eltinit;
5221 bool reuse = false;
5222 constexpr_ctx new_ctx;
5223 init_subob_ctx (ctx, new_ctx, idx, pre_init ? init : elttype);
5224 if (new_ctx.ctor != ctx->ctor)
5226 if (zeroed_out)
5227 CONSTRUCTOR_NO_CLEARING (new_ctx.ctor) = false;
5228 CONSTRUCTOR_APPEND_ELT (*p, idx, new_ctx.ctor);
5230 if (TREE_CODE (elttype) == ARRAY_TYPE)
5232 /* A multidimensional array; recurse. */
5233 if (value_init || init == NULL_TREE)
5235 eltinit = NULL_TREE;
5236 reuse = i == 0;
5238 else
5239 eltinit = cp_build_array_ref (input_location, init, idx, complain);
5240 eltinit = cxx_eval_vec_init_1 (&new_ctx, elttype, eltinit, value_init,
5241 lval,
5242 non_constant_p, overflow_p);
5244 else if (pre_init)
5246 /* Initializing an element using value or default initialization
5247 we just pre-built above. */
5248 if (init == void_node)
5249 /* Trivial default-init, don't do anything to the CONSTRUCTOR. */
5250 return ctx->ctor;
5251 eltinit = cxx_eval_constant_expression (&new_ctx, init, lval,
5252 non_constant_p, overflow_p);
5253 reuse = i == 0;
5255 else
5257 /* Copying an element. */
5258 eltinit = cp_build_array_ref (input_location, init, idx, complain);
5259 if (!lvalue_p (init))
5260 eltinit = move (eltinit);
5261 eltinit = (perform_implicit_conversion_flags
5262 (elttype, eltinit, complain,
5263 LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING));
5264 eltinit = cxx_eval_constant_expression (&new_ctx, eltinit, lval,
5265 non_constant_p, overflow_p);
5267 if (*non_constant_p)
5268 break;
5269 if (new_ctx.ctor != ctx->ctor)
5271 /* We appended this element above; update the value. */
5272 gcc_assert ((*p)->last().index == idx);
5273 (*p)->last().value = eltinit;
5275 else
5276 CONSTRUCTOR_APPEND_ELT (*p, idx, eltinit);
5277 /* Reuse the result of cxx_eval_constant_expression call
5278 from the first iteration to all others if it is a constant
5279 initializer that doesn't require relocations. */
5280 if (reuse
5281 && max > 1
5282 && (eltinit == NULL_TREE
5283 || (initializer_constant_valid_p (eltinit, TREE_TYPE (eltinit))
5284 == null_pointer_node)))
5286 if (new_ctx.ctor != ctx->ctor)
5287 eltinit = new_ctx.ctor;
5288 tree range = build2 (RANGE_EXPR, size_type_node,
5289 build_int_cst (size_type_node, 1),
5290 build_int_cst (size_type_node, max - 1));
5291 CONSTRUCTOR_APPEND_ELT (*p, range, unshare_constructor (eltinit));
5292 break;
5294 else if (i == 0)
5295 vec_safe_reserve (*p, max);
5298 if (!*non_constant_p)
5300 init = ctx->ctor;
5301 CONSTRUCTOR_NO_CLEARING (init) = false;
5303 return init;
5306 static tree
5307 cxx_eval_vec_init (const constexpr_ctx *ctx, tree t,
5308 value_cat lval,
5309 bool *non_constant_p, bool *overflow_p)
5311 tree atype = TREE_TYPE (t);
5312 tree init = VEC_INIT_EXPR_INIT (t);
5313 bool value_init = VEC_INIT_EXPR_VALUE_INIT (t);
5314 if (!init || !BRACE_ENCLOSED_INITIALIZER_P (init))
5316 else if (CONSTRUCTOR_NELTS (init) == 0
5317 && !CP_AGGREGATE_TYPE_P (strip_array_types (atype)))
5319 /* Handle {} as value-init. */
5320 init = NULL_TREE;
5321 value_init = true;
5323 else
5325 /* This is a more complicated case, like needing to loop over trailing
5326 elements; call build_vec_init and evaluate the result. */
5327 tsubst_flags_t complain = ctx->quiet ? tf_none : tf_warning_or_error;
5328 constexpr_ctx new_ctx = *ctx;
5329 if (!ctx->object)
5331 /* We want to have an initialization target for an VEC_INIT_EXPR.
5332 If we don't already have one in CTX, use the VEC_INIT_EXPR_SLOT. */
5333 new_ctx.object = VEC_INIT_EXPR_SLOT (t);
5334 tree ctor = new_ctx.ctor = build_constructor (atype, NULL);
5335 CONSTRUCTOR_NO_CLEARING (ctor) = true;
5336 ctx->global->put_value (new_ctx.object, ctor);
5337 ctx = &new_ctx;
5339 init = expand_vec_init_expr (ctx->object, t, complain);
5340 return cxx_eval_constant_expression (ctx, init, lval, non_constant_p,
5341 overflow_p);
5343 tree r = cxx_eval_vec_init_1 (ctx, atype, init, value_init,
5344 lval, non_constant_p, overflow_p);
5345 if (*non_constant_p)
5346 return t;
5347 else
5348 return r;
5351 /* Like same_type_ignoring_top_level_qualifiers_p, but also handle the case
5352 where the desired type is an array of unknown bounds because the variable
5353 has had its bounds deduced since the wrapping expression was created. */
5355 static bool
5356 same_type_ignoring_tlq_and_bounds_p (tree type1, tree type2)
5358 while (TREE_CODE (type1) == ARRAY_TYPE
5359 && TREE_CODE (type2) == ARRAY_TYPE
5360 && (!TYPE_DOMAIN (type1) || !TYPE_DOMAIN (type2)))
5362 type1 = TREE_TYPE (type1);
5363 type2 = TREE_TYPE (type2);
5365 return same_type_ignoring_top_level_qualifiers_p (type1, type2);
5368 /* Try to determine the currently active union member for an expression
5369 with UNION_TYPE. If it can be determined, return the FIELD_DECL,
5370 otherwise return NULL_TREE. */
5372 static tree
5373 cxx_union_active_member (const constexpr_ctx *ctx, tree t)
5375 constexpr_ctx new_ctx = *ctx;
5376 new_ctx.quiet = true;
5377 bool non_constant_p = false, overflow_p = false;
5378 tree ctor = cxx_eval_constant_expression (&new_ctx, t, vc_prvalue,
5379 &non_constant_p,
5380 &overflow_p);
5381 if (TREE_CODE (ctor) == CONSTRUCTOR
5382 && CONSTRUCTOR_NELTS (ctor) == 1
5383 && CONSTRUCTOR_ELT (ctor, 0)->index
5384 && TREE_CODE (CONSTRUCTOR_ELT (ctor, 0)->index) == FIELD_DECL)
5385 return CONSTRUCTOR_ELT (ctor, 0)->index;
5386 return NULL_TREE;
5389 /* Helper function for cxx_fold_indirect_ref_1, called recursively. */
5391 static tree
5392 cxx_fold_indirect_ref_1 (const constexpr_ctx *ctx, location_t loc, tree type,
5393 tree op, unsigned HOST_WIDE_INT off, bool *empty_base)
5395 tree optype = TREE_TYPE (op);
5396 unsigned HOST_WIDE_INT const_nunits;
5397 if (off == 0 && similar_type_p (optype, type))
5398 return op;
5399 else if (TREE_CODE (optype) == COMPLEX_TYPE
5400 && similar_type_p (type, TREE_TYPE (optype)))
5402 /* *(foo *)&complexfoo => __real__ complexfoo */
5403 if (off == 0)
5404 return build1_loc (loc, REALPART_EXPR, type, op);
5405 /* ((foo*)&complexfoo)[1] => __imag__ complexfoo */
5406 else if (tree_to_uhwi (TYPE_SIZE_UNIT (type)) == off)
5407 return build1_loc (loc, IMAGPART_EXPR, type, op);
5409 /* ((foo*)&vectorfoo)[x] => BIT_FIELD_REF<vectorfoo,...> */
5410 else if (VECTOR_TYPE_P (optype)
5411 && similar_type_p (type, TREE_TYPE (optype))
5412 && TYPE_VECTOR_SUBPARTS (optype).is_constant (&const_nunits))
5414 unsigned HOST_WIDE_INT part_width = tree_to_uhwi (TYPE_SIZE_UNIT (type));
5415 unsigned HOST_WIDE_INT max_offset = part_width * const_nunits;
5416 if (off < max_offset && off % part_width == 0)
5418 tree index = bitsize_int (off * BITS_PER_UNIT);
5419 return build3_loc (loc, BIT_FIELD_REF, type, op,
5420 TYPE_SIZE (type), index);
5423 /* ((foo *)&fooarray)[x] => fooarray[x] */
5424 else if (TREE_CODE (optype) == ARRAY_TYPE
5425 && tree_fits_uhwi_p (TYPE_SIZE_UNIT (TREE_TYPE (optype)))
5426 && !integer_zerop (TYPE_SIZE_UNIT (TREE_TYPE (optype))))
5428 tree type_domain = TYPE_DOMAIN (optype);
5429 tree min_val = size_zero_node;
5430 if (type_domain && TYPE_MIN_VALUE (type_domain))
5431 min_val = TYPE_MIN_VALUE (type_domain);
5432 unsigned HOST_WIDE_INT el_sz
5433 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (optype)));
5434 unsigned HOST_WIDE_INT idx = off / el_sz;
5435 unsigned HOST_WIDE_INT rem = off % el_sz;
5436 if (tree_fits_uhwi_p (min_val))
5438 tree index = size_int (idx + tree_to_uhwi (min_val));
5439 op = build4_loc (loc, ARRAY_REF, TREE_TYPE (optype), op, index,
5440 NULL_TREE, NULL_TREE);
5441 return cxx_fold_indirect_ref_1 (ctx, loc, type, op, rem,
5442 empty_base);
5445 /* ((foo *)&struct_with_foo_field)[x] => COMPONENT_REF */
5446 else if (TREE_CODE (optype) == RECORD_TYPE
5447 || TREE_CODE (optype) == UNION_TYPE)
5449 if (TREE_CODE (optype) == UNION_TYPE)
5450 /* For unions prefer the currently active member. */
5451 if (tree field = cxx_union_active_member (ctx, op))
5453 unsigned HOST_WIDE_INT el_sz
5454 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (field)));
5455 if (off < el_sz)
5457 tree cop = build3 (COMPONENT_REF, TREE_TYPE (field),
5458 op, field, NULL_TREE);
5459 if (tree ret = cxx_fold_indirect_ref_1 (ctx, loc, type, cop,
5460 off, empty_base))
5461 return ret;
5464 for (tree field = TYPE_FIELDS (optype);
5465 field; field = DECL_CHAIN (field))
5466 if (TREE_CODE (field) == FIELD_DECL
5467 && TREE_TYPE (field) != error_mark_node
5468 && tree_fits_uhwi_p (TYPE_SIZE_UNIT (TREE_TYPE (field))))
5470 tree pos = byte_position (field);
5471 if (!tree_fits_uhwi_p (pos))
5472 continue;
5473 unsigned HOST_WIDE_INT upos = tree_to_uhwi (pos);
5474 unsigned HOST_WIDE_INT el_sz
5475 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (field)));
5476 if (upos <= off && off < upos + el_sz)
5478 tree cop = build3 (COMPONENT_REF, TREE_TYPE (field),
5479 op, field, NULL_TREE);
5480 if (tree ret = cxx_fold_indirect_ref_1 (ctx, loc, type, cop,
5481 off - upos,
5482 empty_base))
5483 return ret;
5486 /* Also handle conversion to an empty base class, which
5487 is represented with a NOP_EXPR. */
5488 if (is_empty_class (type)
5489 && CLASS_TYPE_P (optype)
5490 && DERIVED_FROM_P (type, optype))
5492 if (empty_base)
5493 *empty_base = true;
5494 return op;
5498 return NULL_TREE;
5501 /* A less strict version of fold_indirect_ref_1, which requires cv-quals to
5502 match. We want to be less strict for simple *& folding; if we have a
5503 non-const temporary that we access through a const pointer, that should
5504 work. We handle this here rather than change fold_indirect_ref_1
5505 because we're dealing with things like ADDR_EXPR of INTEGER_CST which
5506 don't really make sense outside of constant expression evaluation. Also
5507 we want to allow folding to COMPONENT_REF, which could cause trouble
5508 with TBAA in fold_indirect_ref_1. */
5510 static tree
5511 cxx_fold_indirect_ref (const constexpr_ctx *ctx, location_t loc, tree type,
5512 tree op0, bool *empty_base /* = NULL*/)
5514 tree sub = op0;
5515 tree subtype;
5516 poly_uint64 const_op01;
5518 /* STRIP_NOPS, but stop if REINTERPRET_CAST_P. */
5519 while (CONVERT_EXPR_P (sub) || TREE_CODE (sub) == NON_LVALUE_EXPR
5520 || TREE_CODE (sub) == VIEW_CONVERT_EXPR)
5522 if (TREE_CODE (sub) == NOP_EXPR
5523 && REINTERPRET_CAST_P (sub))
5524 return NULL_TREE;
5525 sub = TREE_OPERAND (sub, 0);
5528 subtype = TREE_TYPE (sub);
5529 if (!INDIRECT_TYPE_P (subtype))
5530 return NULL_TREE;
5532 /* Canonicalizes the given OBJ/OFF pair by iteratively absorbing
5533 the innermost component into the offset until it would make the
5534 offset positive, so that cxx_fold_indirect_ref_1 can identify
5535 more folding opportunities. */
5536 auto canonicalize_obj_off = [] (tree& obj, tree& off) {
5537 while (TREE_CODE (obj) == COMPONENT_REF
5538 && (tree_int_cst_sign_bit (off) || integer_zerop (off)))
5540 tree field = TREE_OPERAND (obj, 1);
5541 tree pos = byte_position (field);
5542 if (integer_zerop (off) && integer_nonzerop (pos))
5543 /* If the offset is already 0, keep going as long as the
5544 component is at position 0. */
5545 break;
5546 off = int_const_binop (PLUS_EXPR, off, pos);
5547 obj = TREE_OPERAND (obj, 0);
5551 if (TREE_CODE (sub) == ADDR_EXPR)
5553 tree op = TREE_OPERAND (sub, 0);
5554 tree optype = TREE_TYPE (op);
5556 /* *&CONST_DECL -> to the value of the const decl. */
5557 if (TREE_CODE (op) == CONST_DECL)
5558 return DECL_INITIAL (op);
5559 /* *&p => p; make sure to handle *&"str"[cst] here. */
5560 if (similar_type_p (optype, type))
5562 tree fop = fold_read_from_constant_string (op);
5563 if (fop)
5564 return fop;
5565 else
5566 return op;
5568 else
5570 tree off = integer_zero_node;
5571 canonicalize_obj_off (op, off);
5572 gcc_assert (integer_zerop (off));
5573 return cxx_fold_indirect_ref_1 (ctx, loc, type, op, 0, empty_base);
5576 else if (TREE_CODE (sub) == POINTER_PLUS_EXPR
5577 && tree_fits_uhwi_p (TREE_OPERAND (sub, 1)))
5579 tree op00 = TREE_OPERAND (sub, 0);
5580 tree off = TREE_OPERAND (sub, 1);
5582 STRIP_NOPS (op00);
5583 if (TREE_CODE (op00) == ADDR_EXPR)
5585 tree obj = TREE_OPERAND (op00, 0);
5586 canonicalize_obj_off (obj, off);
5587 return cxx_fold_indirect_ref_1 (ctx, loc, type, obj,
5588 tree_to_uhwi (off), empty_base);
5591 /* *(foo *)fooarrptr => (*fooarrptr)[0] */
5592 else if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
5593 && similar_type_p (type, TREE_TYPE (TREE_TYPE (subtype))))
5595 tree type_domain;
5596 tree min_val = size_zero_node;
5597 tree newsub
5598 = cxx_fold_indirect_ref (ctx, loc, TREE_TYPE (subtype), sub, NULL);
5599 if (newsub)
5600 sub = newsub;
5601 else
5602 sub = build1_loc (loc, INDIRECT_REF, TREE_TYPE (subtype), sub);
5603 type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
5604 if (type_domain && TYPE_MIN_VALUE (type_domain))
5605 min_val = TYPE_MIN_VALUE (type_domain);
5606 return build4_loc (loc, ARRAY_REF, type, sub, min_val, NULL_TREE,
5607 NULL_TREE);
5610 return NULL_TREE;
5613 static tree
5614 cxx_eval_indirect_ref (const constexpr_ctx *ctx, tree t,
5615 value_cat lval,
5616 bool *non_constant_p, bool *overflow_p)
5618 tree orig_op0 = TREE_OPERAND (t, 0);
5619 bool empty_base = false;
5621 /* We can handle a MEM_REF like an INDIRECT_REF, if MEM_REF's second
5622 operand is an integer-zero. Otherwise reject the MEM_REF for now. */
5624 if (TREE_CODE (t) == MEM_REF
5625 && (!TREE_OPERAND (t, 1) || !integer_zerop (TREE_OPERAND (t, 1))))
5627 gcc_assert (ctx->quiet);
5628 *non_constant_p = true;
5629 return t;
5632 /* First try to simplify it directly. */
5633 tree r = cxx_fold_indirect_ref (ctx, EXPR_LOCATION (t), TREE_TYPE (t),
5634 orig_op0, &empty_base);
5635 if (!r)
5637 /* If that didn't work, evaluate the operand first. */
5638 tree op0 = cxx_eval_constant_expression (ctx, orig_op0,
5639 vc_prvalue, non_constant_p,
5640 overflow_p);
5641 /* Don't VERIFY_CONSTANT here. */
5642 if (*non_constant_p)
5643 return t;
5645 if (!lval && integer_zerop (op0))
5647 if (!ctx->quiet)
5648 error ("dereferencing a null pointer");
5649 *non_constant_p = true;
5650 return t;
5653 r = cxx_fold_indirect_ref (ctx, EXPR_LOCATION (t), TREE_TYPE (t), op0,
5654 &empty_base);
5655 if (r == NULL_TREE)
5657 /* We couldn't fold to a constant value. Make sure it's not
5658 something we should have been able to fold. */
5659 tree sub = op0;
5660 STRIP_NOPS (sub);
5661 if (TREE_CODE (sub) == ADDR_EXPR)
5663 gcc_assert (!similar_type_p
5664 (TREE_TYPE (TREE_TYPE (sub)), TREE_TYPE (t)));
5665 /* DR 1188 says we don't have to deal with this. */
5666 if (!ctx->quiet)
5667 error_at (cp_expr_loc_or_input_loc (t),
5668 "accessing value of %qE through a %qT glvalue in a "
5669 "constant expression", build_fold_indirect_ref (sub),
5670 TREE_TYPE (t));
5671 *non_constant_p = true;
5672 return t;
5675 if (lval == vc_glvalue && op0 != orig_op0)
5676 return build1 (INDIRECT_REF, TREE_TYPE (t), op0);
5677 if (!lval)
5678 VERIFY_CONSTANT (t);
5679 return t;
5683 r = cxx_eval_constant_expression (ctx, r,
5684 lval, non_constant_p, overflow_p);
5685 if (*non_constant_p)
5686 return t;
5688 /* If we're pulling out the value of an empty base, just return an empty
5689 CONSTRUCTOR. */
5690 if (empty_base && !lval)
5692 r = build_constructor (TREE_TYPE (t), NULL);
5693 TREE_CONSTANT (r) = true;
5696 return r;
5699 /* Complain about R, a VAR_DECL, not being usable in a constant expression.
5700 FUNDEF_P is true if we're checking a constexpr function body.
5701 Shared between potential_constant_expression and
5702 cxx_eval_constant_expression. */
5704 static void
5705 non_const_var_error (location_t loc, tree r, bool fundef_p)
5707 auto_diagnostic_group d;
5708 tree type = TREE_TYPE (r);
5709 if (DECL_NAME (r) == heap_uninit_identifier
5710 || DECL_NAME (r) == heap_identifier
5711 || DECL_NAME (r) == heap_vec_uninit_identifier
5712 || DECL_NAME (r) == heap_vec_identifier)
5714 if (constexpr_error (loc, fundef_p, "the content of uninitialized "
5715 "storage is not usable in a constant expression"))
5716 inform (DECL_SOURCE_LOCATION (r), "allocated here");
5717 return;
5719 if (DECL_NAME (r) == heap_deleted_identifier)
5721 if (constexpr_error (loc, fundef_p, "use of allocated storage after "
5722 "deallocation in a constant expression"))
5723 inform (DECL_SOURCE_LOCATION (r), "allocated here");
5724 return;
5726 if (!constexpr_error (loc, fundef_p, "the value of %qD is not usable in "
5727 "a constant expression", r))
5728 return;
5729 /* Avoid error cascade. */
5730 if (DECL_INITIAL (r) == error_mark_node)
5731 return;
5732 if (DECL_DECLARED_CONSTEXPR_P (r))
5733 inform (DECL_SOURCE_LOCATION (r),
5734 "%qD used in its own initializer", r);
5735 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5737 if (!CP_TYPE_CONST_P (type))
5738 inform (DECL_SOURCE_LOCATION (r),
5739 "%q#D is not const", r);
5740 else if (CP_TYPE_VOLATILE_P (type))
5741 inform (DECL_SOURCE_LOCATION (r),
5742 "%q#D is volatile", r);
5743 else if (!DECL_INITIAL (r)
5744 || !TREE_CONSTANT (DECL_INITIAL (r))
5745 || !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r))
5746 inform (DECL_SOURCE_LOCATION (r),
5747 "%qD was not initialized with a constant "
5748 "expression", r);
5749 else
5750 gcc_unreachable ();
5752 else if (TYPE_REF_P (type))
5753 inform (DECL_SOURCE_LOCATION (r),
5754 "%qD was not initialized with a constant "
5755 "expression", r);
5756 else
5758 if (cxx_dialect >= cxx11 && !DECL_DECLARED_CONSTEXPR_P (r))
5759 inform (DECL_SOURCE_LOCATION (r),
5760 "%qD was not declared %<constexpr%>", r);
5761 else
5762 inform (DECL_SOURCE_LOCATION (r),
5763 "%qD does not have integral or enumeration type",
5768 /* Subroutine of cxx_eval_constant_expression.
5769 Like cxx_eval_unary_expression, except for trinary expressions. */
5771 static tree
5772 cxx_eval_trinary_expression (const constexpr_ctx *ctx, tree t,
5773 value_cat lval,
5774 bool *non_constant_p, bool *overflow_p)
5776 int i;
5777 tree args[3];
5778 tree val;
5780 for (i = 0; i < 3; i++)
5782 args[i] = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, i),
5783 lval,
5784 non_constant_p, overflow_p);
5785 VERIFY_CONSTANT (args[i]);
5788 val = fold_ternary_loc (EXPR_LOCATION (t), TREE_CODE (t), TREE_TYPE (t),
5789 args[0], args[1], args[2]);
5790 if (val == NULL_TREE)
5791 return t;
5792 VERIFY_CONSTANT (val);
5793 return val;
5796 /* True if T was declared in a function declared to be constexpr, and
5797 therefore potentially constant in C++14. */
5799 bool
5800 var_in_constexpr_fn (tree t)
5802 tree ctx = DECL_CONTEXT (t);
5803 return (ctx && TREE_CODE (ctx) == FUNCTION_DECL
5804 && DECL_DECLARED_CONSTEXPR_P (ctx));
5807 /* True if a function might be constexpr: either a function that was
5808 declared constexpr, or a C++17 lambda op(). */
5810 bool
5811 maybe_constexpr_fn (tree t)
5813 return (DECL_DECLARED_CONSTEXPR_P (t)
5814 || (cxx_dialect >= cxx17 && LAMBDA_FUNCTION_P (t))
5815 || (flag_implicit_constexpr
5816 && DECL_DECLARED_INLINE_P (STRIP_TEMPLATE (t))));
5819 /* True if T was declared in a function that might be constexpr: either a
5820 function that was declared constexpr, or a C++17 lambda op(). */
5822 bool
5823 var_in_maybe_constexpr_fn (tree t)
5825 return (DECL_FUNCTION_SCOPE_P (t)
5826 && maybe_constexpr_fn (DECL_CONTEXT (t)));
5829 /* We're assigning INIT to TARGET. In do_build_copy_constructor and
5830 build_over_call we implement trivial copy of a class with tail padding using
5831 assignment of character arrays, which is valid in normal code, but not in
5832 constexpr evaluation. We don't need to worry about clobbering tail padding
5833 in constexpr evaluation, so strip the type punning. */
5835 static void
5836 maybe_simplify_trivial_copy (tree &target, tree &init)
5838 if (TREE_CODE (target) == MEM_REF
5839 && TREE_CODE (init) == MEM_REF
5840 && TREE_TYPE (target) == TREE_TYPE (init)
5841 && TREE_CODE (TREE_TYPE (target)) == ARRAY_TYPE
5842 && TREE_TYPE (TREE_TYPE (target)) == unsigned_char_type_node)
5844 target = build_fold_indirect_ref (TREE_OPERAND (target, 0));
5845 init = build_fold_indirect_ref (TREE_OPERAND (init, 0));
5849 /* Returns true if REF, which is a COMPONENT_REF, has any fields
5850 of constant type. This does not check for 'mutable', so the
5851 caller is expected to be mindful of that. */
5853 static bool
5854 cref_has_const_field (tree ref)
5856 while (TREE_CODE (ref) == COMPONENT_REF)
5858 if (CP_TYPE_CONST_P (TREE_TYPE (TREE_OPERAND (ref, 1))))
5859 return true;
5860 ref = TREE_OPERAND (ref, 0);
5862 return false;
5865 /* Return true if we are modifying something that is const during constant
5866 expression evaluation. CODE is the code of the statement, OBJ is the
5867 object in question, MUTABLE_P is true if one of the subobjects were
5868 declared mutable. */
5870 static bool
5871 modifying_const_object_p (tree_code code, tree obj, bool mutable_p)
5873 /* If this is initialization, there's no problem. */
5874 if (code != MODIFY_EXPR)
5875 return false;
5877 /* [basic.type.qualifier] "A const object is an object of type
5878 const T or a non-mutable subobject of a const object." */
5879 if (mutable_p)
5880 return false;
5882 if (TREE_READONLY (obj))
5883 return true;
5885 if (CP_TYPE_CONST_P (TREE_TYPE (obj)))
5887 /* Although a COMPONENT_REF may have a const type, we should
5888 only consider it modifying a const object when any of the
5889 field components is const. This can happen when using
5890 constructs such as const_cast<const T &>(m), making something
5891 const even though it wasn't declared const. */
5892 if (TREE_CODE (obj) == COMPONENT_REF)
5893 return cref_has_const_field (obj);
5894 else
5895 return true;
5898 return false;
5901 /* Evaluate an INIT_EXPR or MODIFY_EXPR. */
5903 static tree
5904 cxx_eval_store_expression (const constexpr_ctx *ctx, tree t,
5905 value_cat lval,
5906 bool *non_constant_p, bool *overflow_p)
5908 constexpr_ctx new_ctx = *ctx;
5910 tree init = TREE_OPERAND (t, 1);
5911 if (TREE_CLOBBER_P (init))
5912 /* Just ignore clobbers. */
5913 return void_node;
5915 /* First we figure out where we're storing to. */
5916 tree target = TREE_OPERAND (t, 0);
5918 maybe_simplify_trivial_copy (target, init);
5920 tree type = TREE_TYPE (target);
5921 bool preeval = SCALAR_TYPE_P (type) || TREE_CODE (t) == MODIFY_EXPR;
5922 if (preeval)
5924 /* Evaluate the value to be stored without knowing what object it will be
5925 stored in, so that any side-effects happen first. */
5926 if (!SCALAR_TYPE_P (type))
5927 new_ctx.ctor = new_ctx.object = NULL_TREE;
5928 init = cxx_eval_constant_expression (&new_ctx, init, vc_prvalue,
5929 non_constant_p, overflow_p);
5930 if (*non_constant_p)
5931 return t;
5934 bool evaluated = false;
5935 if (lval == vc_glvalue)
5937 /* If we want to return a reference to the target, we need to evaluate it
5938 as a whole; otherwise, only evaluate the innermost piece to avoid
5939 building up unnecessary *_REFs. */
5940 target = cxx_eval_constant_expression (ctx, target, lval,
5941 non_constant_p, overflow_p);
5942 evaluated = true;
5943 if (*non_constant_p)
5944 return t;
5947 /* Find the underlying variable. */
5948 releasing_vec refs;
5949 tree object = NULL_TREE;
5950 /* If we're modifying a const object, save it. */
5951 tree const_object_being_modified = NULL_TREE;
5952 bool mutable_p = false;
5953 for (tree probe = target; object == NULL_TREE; )
5955 switch (TREE_CODE (probe))
5957 case BIT_FIELD_REF:
5958 case COMPONENT_REF:
5959 case ARRAY_REF:
5961 tree ob = TREE_OPERAND (probe, 0);
5962 tree elt = TREE_OPERAND (probe, 1);
5963 if (TREE_CODE (elt) == FIELD_DECL && DECL_MUTABLE_P (elt))
5964 mutable_p = true;
5965 if (TREE_CODE (probe) == ARRAY_REF)
5967 elt = eval_and_check_array_index (ctx, probe, false,
5968 non_constant_p, overflow_p);
5969 if (*non_constant_p)
5970 return t;
5972 /* We don't check modifying_const_object_p for ARRAY_REFs. Given
5973 "int a[10]", an ARRAY_REF "a[2]" can be "const int", even though
5974 the array isn't const. Instead, check "a" in the next iteration;
5975 that will detect modifying "const int a[10]". */
5976 else if (evaluated
5977 && modifying_const_object_p (TREE_CODE (t), probe,
5978 mutable_p)
5979 && const_object_being_modified == NULL_TREE)
5980 const_object_being_modified = probe;
5981 vec_safe_push (refs, elt);
5982 vec_safe_push (refs, TREE_TYPE (probe));
5983 probe = ob;
5985 break;
5987 case REALPART_EXPR:
5988 gcc_assert (probe == target);
5989 vec_safe_push (refs, probe);
5990 vec_safe_push (refs, TREE_TYPE (probe));
5991 probe = TREE_OPERAND (probe, 0);
5992 break;
5994 case IMAGPART_EXPR:
5995 gcc_assert (probe == target);
5996 vec_safe_push (refs, probe);
5997 vec_safe_push (refs, TREE_TYPE (probe));
5998 probe = TREE_OPERAND (probe, 0);
5999 break;
6001 default:
6002 if (evaluated)
6003 object = probe;
6004 else
6006 probe = cxx_eval_constant_expression (ctx, probe, vc_glvalue,
6007 non_constant_p, overflow_p);
6008 evaluated = true;
6009 if (*non_constant_p)
6010 return t;
6012 break;
6016 if (modifying_const_object_p (TREE_CODE (t), object, mutable_p)
6017 && const_object_being_modified == NULL_TREE)
6018 const_object_being_modified = object;
6020 /* And then find/build up our initializer for the path to the subobject
6021 we're initializing. */
6022 tree *valp;
6023 if (DECL_P (object))
6024 valp = ctx->global->get_value_ptr (object);
6025 else
6026 valp = NULL;
6027 if (!valp)
6029 /* A constant-expression cannot modify objects from outside the
6030 constant-expression. */
6031 if (!ctx->quiet)
6032 error ("modification of %qE is not a constant expression", object);
6033 *non_constant_p = true;
6034 return t;
6036 type = TREE_TYPE (object);
6037 bool no_zero_init = true;
6039 auto_vec<tree *> ctors;
6040 releasing_vec indexes;
6041 auto_vec<int> index_pos_hints;
6042 bool activated_union_member_p = false;
6043 bool empty_base = false;
6044 while (!refs->is_empty ())
6046 if (*valp == NULL_TREE)
6048 *valp = build_constructor (type, NULL);
6049 CONSTRUCTOR_NO_CLEARING (*valp) = no_zero_init;
6051 else if (TREE_CODE (*valp) == STRING_CST)
6053 /* An array was initialized with a string constant, and now
6054 we're writing into one of its elements. Explode the
6055 single initialization into a set of element
6056 initializations. */
6057 gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
6059 tree string = *valp;
6060 tree elt_type = TREE_TYPE (type);
6061 unsigned chars_per_elt = (TYPE_PRECISION (elt_type)
6062 / TYPE_PRECISION (char_type_node));
6063 unsigned num_elts = TREE_STRING_LENGTH (string) / chars_per_elt;
6064 tree ary_ctor = build_constructor (type, NULL);
6066 vec_safe_reserve (CONSTRUCTOR_ELTS (ary_ctor), num_elts);
6067 for (unsigned ix = 0; ix != num_elts; ix++)
6069 constructor_elt elt =
6071 build_int_cst (size_type_node, ix),
6072 extract_string_elt (string, chars_per_elt, ix)
6074 CONSTRUCTOR_ELTS (ary_ctor)->quick_push (elt);
6077 *valp = ary_ctor;
6080 enum tree_code code = TREE_CODE (type);
6081 tree reftype = refs->pop();
6082 tree index = refs->pop();
6084 if (code == COMPLEX_TYPE)
6086 if (TREE_CODE (*valp) == COMPLEX_CST)
6087 *valp = build2 (COMPLEX_EXPR, type, TREE_REALPART (*valp),
6088 TREE_IMAGPART (*valp));
6089 else if (TREE_CODE (*valp) == CONSTRUCTOR
6090 && CONSTRUCTOR_NELTS (*valp) == 0
6091 && CONSTRUCTOR_NO_CLEARING (*valp))
6093 tree r = build_constructor (reftype, NULL);
6094 CONSTRUCTOR_NO_CLEARING (r) = 1;
6095 *valp = build2 (COMPLEX_EXPR, type, r, r);
6097 gcc_assert (TREE_CODE (*valp) == COMPLEX_EXPR);
6098 ctors.safe_push (valp);
6099 vec_safe_push (indexes, index);
6100 valp = &TREE_OPERAND (*valp, TREE_CODE (index) == IMAGPART_EXPR);
6101 gcc_checking_assert (refs->is_empty ());
6102 type = reftype;
6103 break;
6106 /* If the value of object is already zero-initialized, any new ctors for
6107 subobjects will also be zero-initialized. */
6108 no_zero_init = CONSTRUCTOR_NO_CLEARING (*valp);
6110 if (code == RECORD_TYPE && is_empty_field (index))
6111 /* Don't build a sub-CONSTRUCTOR for an empty base or field, as they
6112 have no data and might have an offset lower than previously declared
6113 fields, which confuses the middle-end. The code below will notice
6114 that we don't have a CONSTRUCTOR for our inner target and just
6115 return init. */
6117 empty_base = true;
6118 break;
6121 type = reftype;
6123 if (code == UNION_TYPE && CONSTRUCTOR_NELTS (*valp)
6124 && CONSTRUCTOR_ELT (*valp, 0)->index != index)
6126 if (cxx_dialect < cxx20)
6128 if (!ctx->quiet)
6129 error_at (cp_expr_loc_or_input_loc (t),
6130 "change of the active member of a union "
6131 "from %qD to %qD",
6132 CONSTRUCTOR_ELT (*valp, 0)->index,
6133 index);
6134 *non_constant_p = true;
6136 else if (TREE_CODE (t) == MODIFY_EXPR
6137 && CONSTRUCTOR_NO_CLEARING (*valp))
6139 /* Diagnose changing the active union member while the union
6140 is in the process of being initialized. */
6141 if (!ctx->quiet)
6142 error_at (cp_expr_loc_or_input_loc (t),
6143 "change of the active member of a union "
6144 "from %qD to %qD during initialization",
6145 CONSTRUCTOR_ELT (*valp, 0)->index,
6146 index);
6147 *non_constant_p = true;
6149 no_zero_init = true;
6152 ctors.safe_push (valp);
6153 vec_safe_push (indexes, index);
6155 constructor_elt *cep
6156 = get_or_insert_ctor_field (*valp, index);
6157 index_pos_hints.safe_push (cep - CONSTRUCTOR_ELTS (*valp)->begin());
6159 if (code == UNION_TYPE)
6160 activated_union_member_p = true;
6162 valp = &cep->value;
6165 /* For initialization of an empty base, the original target will be
6166 *(base*)this, evaluation of which resolves to the object
6167 argument, which has the derived type rather than the base type. */
6168 if (!empty_base && !(same_type_ignoring_top_level_qualifiers_p
6169 (initialized_type (init), type)))
6171 gcc_assert (is_empty_class (TREE_TYPE (target)));
6172 empty_base = true;
6175 /* Detect modifying a constant object in constexpr evaluation.
6176 We have found a const object that is being modified. Figure out
6177 if we need to issue an error. Consider
6179 struct A {
6180 int n;
6181 constexpr A() : n(1) { n = 2; } // #1
6183 struct B {
6184 const A a;
6185 constexpr B() { a.n = 3; } // #2
6187 constexpr B b{};
6189 #1 is OK, since we're modifying an object under construction, but
6190 #2 is wrong, since "a" is const and has been fully constructed.
6191 To track it, we use the TREE_READONLY bit in the object's CONSTRUCTOR
6192 which means that the object is read-only. For the example above, the
6193 *ctors stack at the point of #2 will look like:
6195 ctors[0] = {.a={.n=2}} TREE_READONLY = 0
6196 ctors[1] = {.n=2} TREE_READONLY = 1
6198 and we're modifying "b.a", so we search the stack and see if the
6199 constructor for "b.a" has already run. */
6200 if (const_object_being_modified)
6202 bool fail = false;
6203 tree const_objtype
6204 = strip_array_types (TREE_TYPE (const_object_being_modified));
6205 if (!CLASS_TYPE_P (const_objtype))
6206 fail = true;
6207 else
6209 /* [class.ctor]p5 "A constructor can be invoked for a const,
6210 volatile, or const volatile object. const and volatile
6211 semantics are not applied on an object under construction.
6212 They come into effect when the constructor for the most
6213 derived object ends." */
6214 for (tree *elt : ctors)
6215 if (same_type_ignoring_top_level_qualifiers_p
6216 (TREE_TYPE (const_object_being_modified), TREE_TYPE (*elt)))
6218 fail = TREE_READONLY (*elt);
6219 break;
6222 if (fail)
6224 if (!ctx->quiet)
6225 modifying_const_object_error (t, const_object_being_modified);
6226 *non_constant_p = true;
6227 return t;
6231 if (!preeval)
6233 /* We're handling an INIT_EXPR of class type, so the value of the
6234 initializer can depend on the object it's initializing. */
6236 /* Create a new CONSTRUCTOR in case evaluation of the initializer
6237 wants to modify it. */
6238 if (*valp == NULL_TREE)
6240 *valp = build_constructor (type, NULL);
6241 CONSTRUCTOR_NO_CLEARING (*valp) = no_zero_init;
6243 new_ctx.ctor = empty_base ? NULL_TREE : *valp;
6244 new_ctx.object = target;
6245 /* Avoid temporary materialization when initializing from a TARGET_EXPR.
6246 We don't need to mess with AGGR_EXPR_SLOT/VEC_INIT_EXPR_SLOT because
6247 expansion of those trees uses ctx instead. */
6248 if (TREE_CODE (init) == TARGET_EXPR)
6249 if (tree tinit = TARGET_EXPR_INITIAL (init))
6250 init = tinit;
6251 init = cxx_eval_constant_expression (&new_ctx, init, vc_prvalue,
6252 non_constant_p, overflow_p);
6253 /* The hash table might have moved since the get earlier, and the
6254 initializer might have mutated the underlying CONSTRUCTORs, so we must
6255 recompute VALP. */
6256 valp = ctx->global->get_value_ptr (object);
6257 for (unsigned i = 0; i < vec_safe_length (indexes); i++)
6259 ctors[i] = valp;
6260 constructor_elt *cep
6261 = get_or_insert_ctor_field (*valp, indexes[i], index_pos_hints[i]);
6262 valp = &cep->value;
6266 if (*non_constant_p)
6267 return t;
6269 /* Don't share a CONSTRUCTOR that might be changed later. */
6270 init = unshare_constructor (init);
6272 gcc_checking_assert (!*valp || (same_type_ignoring_top_level_qualifiers_p
6273 (TREE_TYPE (*valp), type)));
6274 if (empty_base)
6276 /* Just evaluate the initializer and return, since there's no actual data
6277 to store, and we didn't build a CONSTRUCTOR. */
6278 if (!*valp)
6280 /* But do make sure we have something in *valp. */
6281 *valp = build_constructor (type, nullptr);
6282 CONSTRUCTOR_NO_CLEARING (*valp) = no_zero_init;
6285 else if (*valp && TREE_CODE (*valp) == CONSTRUCTOR
6286 && TREE_CODE (init) == CONSTRUCTOR)
6288 /* An outer ctx->ctor might be pointing to *valp, so replace
6289 its contents. */
6290 CONSTRUCTOR_ELTS (*valp) = CONSTRUCTOR_ELTS (init);
6291 TREE_CONSTANT (*valp) = TREE_CONSTANT (init);
6292 TREE_SIDE_EFFECTS (*valp) = TREE_SIDE_EFFECTS (init);
6293 CONSTRUCTOR_NO_CLEARING (*valp)
6294 = CONSTRUCTOR_NO_CLEARING (init);
6296 else
6297 *valp = init;
6299 /* After initialization, 'const' semantics apply to the value of the
6300 object. Make a note of this fact by marking the CONSTRUCTOR
6301 TREE_READONLY. */
6302 if (TREE_CODE (t) == INIT_EXPR
6303 && TREE_CODE (*valp) == CONSTRUCTOR
6304 && TYPE_READONLY (type))
6306 if (INDIRECT_REF_P (target)
6307 && (is_this_parameter
6308 (tree_strip_nop_conversions (TREE_OPERAND (target, 0)))))
6309 /* We've just initialized '*this' (perhaps via the target
6310 constructor of a delegating constructor). Leave it up to the
6311 caller that set 'this' to set TREE_READONLY appropriately. */
6312 gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
6313 (TREE_TYPE (target), type) || empty_base);
6314 else
6315 TREE_READONLY (*valp) = true;
6318 /* Update TREE_CONSTANT and TREE_SIDE_EFFECTS on enclosing
6319 CONSTRUCTORs, if any. */
6320 bool c = TREE_CONSTANT (init);
6321 bool s = TREE_SIDE_EFFECTS (init);
6322 if (!indexes->is_empty ())
6324 tree last = indexes->last ();
6325 if (TREE_CODE (last) == REALPART_EXPR
6326 || TREE_CODE (last) == IMAGPART_EXPR)
6328 /* And canonicalize COMPLEX_EXPR into COMPLEX_CST if
6329 possible. */
6330 tree *cexpr = ctors.last ();
6331 if (tree c = const_binop (COMPLEX_EXPR, TREE_TYPE (*cexpr),
6332 TREE_OPERAND (*cexpr, 0),
6333 TREE_OPERAND (*cexpr, 1)))
6334 *cexpr = c;
6335 else
6337 TREE_CONSTANT (*cexpr)
6338 = (TREE_CONSTANT (TREE_OPERAND (*cexpr, 0))
6339 & TREE_CONSTANT (TREE_OPERAND (*cexpr, 1)));
6340 TREE_SIDE_EFFECTS (*cexpr)
6341 = (TREE_SIDE_EFFECTS (TREE_OPERAND (*cexpr, 0))
6342 | TREE_SIDE_EFFECTS (TREE_OPERAND (*cexpr, 1)));
6344 c = TREE_CONSTANT (*cexpr);
6345 s = TREE_SIDE_EFFECTS (*cexpr);
6348 if (!c || s || activated_union_member_p)
6349 for (tree *elt : ctors)
6351 if (TREE_CODE (*elt) != CONSTRUCTOR)
6352 continue;
6353 if (!c)
6354 TREE_CONSTANT (*elt) = false;
6355 if (s)
6356 TREE_SIDE_EFFECTS (*elt) = true;
6357 /* Clear CONSTRUCTOR_NO_CLEARING since we've activated a member of
6358 this union. */
6359 if (TREE_CODE (TREE_TYPE (*elt)) == UNION_TYPE)
6360 CONSTRUCTOR_NO_CLEARING (*elt) = false;
6363 if (lval)
6364 return target;
6365 else
6366 return init;
6369 /* Evaluate a ++ or -- expression. */
6371 static tree
6372 cxx_eval_increment_expression (const constexpr_ctx *ctx, tree t,
6373 value_cat lval,
6374 bool *non_constant_p, bool *overflow_p)
6376 enum tree_code code = TREE_CODE (t);
6377 tree type = TREE_TYPE (t);
6378 tree op = TREE_OPERAND (t, 0);
6379 tree offset = TREE_OPERAND (t, 1);
6380 gcc_assert (TREE_CONSTANT (offset));
6382 /* OFFSET is constant, but perhaps not constant enough. We need to
6383 e.g. bash FLOAT_EXPRs to REAL_CSTs. */
6384 offset = fold_simple (offset);
6386 /* The operand as an lvalue. */
6387 op = cxx_eval_constant_expression (ctx, op, vc_glvalue,
6388 non_constant_p, overflow_p);
6390 /* The operand as an rvalue. */
6391 tree val
6392 = cxx_eval_constant_expression (ctx, op, vc_prvalue,
6393 non_constant_p, overflow_p);
6394 /* Don't VERIFY_CONSTANT if this might be dealing with a pointer to
6395 a local array in a constexpr function. */
6396 bool ptr = INDIRECT_TYPE_P (TREE_TYPE (val));
6397 if (!ptr)
6398 VERIFY_CONSTANT (val);
6400 /* The modified value. */
6401 bool inc = (code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR);
6402 tree mod;
6403 if (INDIRECT_TYPE_P (type))
6405 /* The middle end requires pointers to use POINTER_PLUS_EXPR. */
6406 offset = convert_to_ptrofftype (offset);
6407 if (!inc)
6408 offset = fold_build1 (NEGATE_EXPR, TREE_TYPE (offset), offset);
6409 mod = fold_build2 (POINTER_PLUS_EXPR, type, val, offset);
6411 else if (c_promoting_integer_type_p (type)
6412 && !TYPE_UNSIGNED (type)
6413 && TYPE_PRECISION (type) < TYPE_PRECISION (integer_type_node))
6415 offset = fold_convert (integer_type_node, offset);
6416 mod = fold_convert (integer_type_node, val);
6417 tree t = fold_build2 (inc ? PLUS_EXPR : MINUS_EXPR, integer_type_node,
6418 mod, offset);
6419 mod = fold_convert (type, t);
6420 if (TREE_OVERFLOW_P (mod) && !TREE_OVERFLOW_P (t))
6421 TREE_OVERFLOW (mod) = false;
6423 else
6424 mod = fold_build2 (inc ? PLUS_EXPR : MINUS_EXPR, type, val, offset);
6425 if (!ptr)
6426 VERIFY_CONSTANT (mod);
6428 /* Storing the modified value. */
6429 tree store = build2_loc (cp_expr_loc_or_loc (t, input_location),
6430 MODIFY_EXPR, type, op, mod);
6431 mod = cxx_eval_constant_expression (ctx, store, lval,
6432 non_constant_p, overflow_p);
6433 ggc_free (store);
6434 if (*non_constant_p)
6435 return t;
6437 /* And the value of the expression. */
6438 if (code == PREINCREMENT_EXPR || code == PREDECREMENT_EXPR)
6439 /* Prefix ops are lvalues, but the caller might want an rvalue;
6440 lval has already been taken into account in the store above. */
6441 return mod;
6442 else
6443 /* Postfix ops are rvalues. */
6444 return val;
6447 /* Predicates for the meaning of *jump_target. */
6449 static bool
6450 returns (tree *jump_target)
6452 return *jump_target
6453 && TREE_CODE (*jump_target) == RETURN_EXPR;
6456 static bool
6457 breaks (tree *jump_target)
6459 return *jump_target
6460 && ((TREE_CODE (*jump_target) == LABEL_DECL
6461 && LABEL_DECL_BREAK (*jump_target))
6462 || TREE_CODE (*jump_target) == BREAK_STMT
6463 || TREE_CODE (*jump_target) == EXIT_EXPR);
6466 static bool
6467 continues (tree *jump_target)
6469 return *jump_target
6470 && ((TREE_CODE (*jump_target) == LABEL_DECL
6471 && LABEL_DECL_CONTINUE (*jump_target))
6472 || TREE_CODE (*jump_target) == CONTINUE_STMT);
6476 static bool
6477 switches (tree *jump_target)
6479 return *jump_target
6480 && TREE_CODE (*jump_target) == INTEGER_CST;
6483 /* Subroutine of cxx_eval_statement_list. Determine whether the statement
6484 STMT matches *jump_target. If we're looking for a case label and we see
6485 the default label, note it in ctx->css_state. */
6487 static bool
6488 label_matches (const constexpr_ctx *ctx, tree *jump_target, tree stmt)
6490 switch (TREE_CODE (*jump_target))
6492 case LABEL_DECL:
6493 if (TREE_CODE (stmt) == LABEL_EXPR
6494 && LABEL_EXPR_LABEL (stmt) == *jump_target)
6495 return true;
6496 break;
6498 case INTEGER_CST:
6499 if (TREE_CODE (stmt) == CASE_LABEL_EXPR)
6501 gcc_assert (ctx->css_state != NULL);
6502 if (!CASE_LOW (stmt))
6504 /* default: should appear just once in a SWITCH_EXPR
6505 body (excluding nested SWITCH_EXPR). */
6506 gcc_assert (*ctx->css_state != css_default_seen);
6507 /* When evaluating SWITCH_EXPR body for the second time,
6508 return true for the default: label. */
6509 if (*ctx->css_state == css_default_processing)
6510 return true;
6511 *ctx->css_state = css_default_seen;
6513 else if (CASE_HIGH (stmt))
6515 if (tree_int_cst_le (CASE_LOW (stmt), *jump_target)
6516 && tree_int_cst_le (*jump_target, CASE_HIGH (stmt)))
6517 return true;
6519 else if (tree_int_cst_equal (*jump_target, CASE_LOW (stmt)))
6520 return true;
6522 break;
6524 case BREAK_STMT:
6525 case CONTINUE_STMT:
6526 /* These two are handled directly in cxx_eval_loop_expr by testing
6527 breaks (jump_target) or continues (jump_target). */
6528 break;
6530 default:
6531 gcc_unreachable ();
6533 return false;
6536 /* Evaluate a STATEMENT_LIST for side-effects. Handles various jump
6537 semantics, for switch, break, continue, and return. */
6539 static tree
6540 cxx_eval_statement_list (const constexpr_ctx *ctx, tree t,
6541 bool *non_constant_p, bool *overflow_p,
6542 tree *jump_target)
6544 tree local_target;
6545 /* In a statement-expression we want to return the last value.
6546 For empty statement expression return void_node. */
6547 tree r = void_node;
6548 if (!jump_target)
6550 local_target = NULL_TREE;
6551 jump_target = &local_target;
6553 for (tree_stmt_iterator i = tsi_start (t); !tsi_end_p (i); ++i)
6555 tree stmt = *i;
6557 /* We've found a continue, so skip everything until we reach
6558 the label its jumping to. */
6559 if (continues (jump_target))
6561 if (label_matches (ctx, jump_target, stmt))
6562 /* Found it. */
6563 *jump_target = NULL_TREE;
6564 else
6565 continue;
6567 if (TREE_CODE (stmt) == DEBUG_BEGIN_STMT)
6568 continue;
6570 value_cat lval = vc_discard;
6571 /* The result of a statement-expression is not wrapped in EXPR_STMT. */
6572 if (tsi_one_before_end_p (i) && TREE_CODE (stmt) != EXPR_STMT)
6573 lval = vc_prvalue;
6575 r = cxx_eval_constant_expression (ctx, stmt, lval,
6576 non_constant_p, overflow_p,
6577 jump_target);
6578 if (*non_constant_p)
6579 break;
6580 if (returns (jump_target) || breaks (jump_target))
6581 break;
6583 if (*jump_target && jump_target == &local_target)
6585 /* We aren't communicating the jump to our caller, so give up. We don't
6586 need to support evaluation of jumps out of statement-exprs. */
6587 if (!ctx->quiet)
6588 error_at (cp_expr_loc_or_input_loc (r),
6589 "statement is not a constant expression");
6590 *non_constant_p = true;
6592 return r;
6595 /* Evaluate a LOOP_EXPR for side-effects. Handles break and return
6596 semantics; continue semantics are covered by cxx_eval_statement_list. */
6598 static tree
6599 cxx_eval_loop_expr (const constexpr_ctx *ctx, tree t,
6600 bool *non_constant_p, bool *overflow_p,
6601 tree *jump_target)
6603 constexpr_ctx new_ctx = *ctx;
6604 tree local_target;
6605 if (!jump_target)
6607 local_target = NULL_TREE;
6608 jump_target = &local_target;
6611 tree body, cond = NULL_TREE, expr = NULL_TREE;
6612 int count = 0;
6613 switch (TREE_CODE (t))
6615 case LOOP_EXPR:
6616 body = LOOP_EXPR_BODY (t);
6617 break;
6618 case DO_STMT:
6619 body = DO_BODY (t);
6620 cond = DO_COND (t);
6621 break;
6622 case WHILE_STMT:
6623 body = WHILE_BODY (t);
6624 cond = WHILE_COND (t);
6625 count = -1;
6626 break;
6627 case FOR_STMT:
6628 if (FOR_INIT_STMT (t))
6629 cxx_eval_constant_expression (ctx, FOR_INIT_STMT (t), vc_discard,
6630 non_constant_p, overflow_p, jump_target);
6631 if (*non_constant_p)
6632 return NULL_TREE;
6633 body = FOR_BODY (t);
6634 cond = FOR_COND (t);
6635 expr = FOR_EXPR (t);
6636 count = -1;
6637 break;
6638 default:
6639 gcc_unreachable ();
6641 auto_vec<tree, 10> save_exprs;
6642 new_ctx.save_exprs = &save_exprs;
6645 if (count != -1)
6647 if (body)
6648 cxx_eval_constant_expression (&new_ctx, body, vc_discard,
6649 non_constant_p, overflow_p,
6650 jump_target);
6651 if (breaks (jump_target))
6653 *jump_target = NULL_TREE;
6654 break;
6657 if (TREE_CODE (t) != LOOP_EXPR && continues (jump_target))
6658 *jump_target = NULL_TREE;
6660 if (expr)
6661 cxx_eval_constant_expression (&new_ctx, expr, vc_prvalue,
6662 non_constant_p, overflow_p,
6663 jump_target);
6666 if (cond)
6668 tree res
6669 = cxx_eval_constant_expression (&new_ctx, cond, vc_prvalue,
6670 non_constant_p, overflow_p,
6671 jump_target);
6672 if (res)
6674 if (verify_constant (res, ctx->quiet, non_constant_p,
6675 overflow_p))
6676 break;
6677 if (integer_zerop (res))
6678 break;
6680 else
6681 gcc_assert (*jump_target);
6684 /* Forget saved values of SAVE_EXPRs and TARGET_EXPRs. */
6685 for (tree save_expr : save_exprs)
6686 ctx->global->remove_value (save_expr);
6687 save_exprs.truncate (0);
6689 if (++count >= constexpr_loop_limit)
6691 if (!ctx->quiet)
6692 error_at (cp_expr_loc_or_input_loc (t),
6693 "%<constexpr%> loop iteration count exceeds limit of %d "
6694 "(use %<-fconstexpr-loop-limit=%> to increase the limit)",
6695 constexpr_loop_limit);
6696 *non_constant_p = true;
6697 break;
6700 while (!returns (jump_target)
6701 && !breaks (jump_target)
6702 && !continues (jump_target)
6703 && (!switches (jump_target) || count == 0)
6704 && !*non_constant_p);
6706 /* Forget saved values of SAVE_EXPRs and TARGET_EXPRs. */
6707 for (tree save_expr : save_exprs)
6708 ctx->global->remove_value (save_expr);
6710 return NULL_TREE;
6713 /* Evaluate a SWITCH_EXPR for side-effects. Handles switch and break jump
6714 semantics. */
6716 static tree
6717 cxx_eval_switch_expr (const constexpr_ctx *ctx, tree t,
6718 bool *non_constant_p, bool *overflow_p,
6719 tree *jump_target)
6721 tree cond
6722 = TREE_CODE (t) == SWITCH_STMT ? SWITCH_STMT_COND (t) : SWITCH_COND (t);
6723 cond = cxx_eval_constant_expression (ctx, cond, vc_prvalue,
6724 non_constant_p, overflow_p);
6725 VERIFY_CONSTANT (cond);
6726 *jump_target = cond;
6728 tree body
6729 = TREE_CODE (t) == SWITCH_STMT ? SWITCH_STMT_BODY (t) : SWITCH_BODY (t);
6730 constexpr_ctx new_ctx = *ctx;
6731 constexpr_switch_state css = css_default_not_seen;
6732 new_ctx.css_state = &css;
6733 cxx_eval_constant_expression (&new_ctx, body, vc_discard,
6734 non_constant_p, overflow_p, jump_target);
6735 if (switches (jump_target) && css == css_default_seen)
6737 /* If the SWITCH_EXPR body has default: label, process it once again,
6738 this time instructing label_matches to return true for default:
6739 label on switches (jump_target). */
6740 css = css_default_processing;
6741 cxx_eval_constant_expression (&new_ctx, body, vc_discard,
6742 non_constant_p, overflow_p, jump_target);
6744 if (breaks (jump_target) || switches (jump_target))
6745 *jump_target = NULL_TREE;
6746 return NULL_TREE;
6749 /* Find the object of TYPE under initialization in CTX. */
6751 static tree
6752 lookup_placeholder (const constexpr_ctx *ctx, value_cat lval, tree type)
6754 if (!ctx)
6755 return NULL_TREE;
6757 /* Prefer the outermost matching object, but don't cross
6758 CONSTRUCTOR_PLACEHOLDER_BOUNDARY constructors. */
6759 if (ctx->ctor && !CONSTRUCTOR_PLACEHOLDER_BOUNDARY (ctx->ctor))
6760 if (tree outer_ob = lookup_placeholder (ctx->parent, lval, type))
6761 return outer_ob;
6763 /* We could use ctx->object unconditionally, but using ctx->ctor when we
6764 can is a minor optimization. */
6765 if (!lval && ctx->ctor && same_type_p (TREE_TYPE (ctx->ctor), type))
6766 return ctx->ctor;
6768 if (!ctx->object)
6769 return NULL_TREE;
6771 /* Since an object cannot have a field of its own type, we can search outward
6772 from ctx->object to find the unique containing object of TYPE. */
6773 tree ob = ctx->object;
6774 while (ob)
6776 if (same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (ob), type))
6777 break;
6778 if (handled_component_p (ob))
6779 ob = TREE_OPERAND (ob, 0);
6780 else
6781 ob = NULL_TREE;
6784 return ob;
6787 /* Complain about an attempt to evaluate inline assembly. If FUNDEF_P is
6788 true, we're checking a constexpr function body. */
6790 static void
6791 inline_asm_in_constexpr_error (location_t loc, bool fundef_p)
6793 auto_diagnostic_group d;
6794 if (constexpr_error (loc, fundef_p, "inline assembly is not a "
6795 "constant expression"))
6796 inform (loc, "only unevaluated inline assembly is allowed in a "
6797 "%<constexpr%> function in C++20");
6800 /* We're getting the constant value of DECL in a manifestly constant-evaluated
6801 context; maybe complain about that. */
6803 static void
6804 maybe_warn_about_constant_value (location_t loc, tree decl)
6806 static bool explained = false;
6807 if (cxx_dialect >= cxx17
6808 && warn_interference_size
6809 && !OPTION_SET_P (param_destruct_interfere_size)
6810 && DECL_CONTEXT (decl) == std_node
6811 && id_equal (DECL_NAME (decl), "hardware_destructive_interference_size")
6812 && (LOCATION_FILE (input_location) != main_input_filename
6813 || module_exporting_p ())
6814 && warning_at (loc, OPT_Winterference_size, "use of %qD", decl)
6815 && !explained)
6817 explained = true;
6818 inform (loc, "its value can vary between compiler versions or "
6819 "with different %<-mtune%> or %<-mcpu%> flags");
6820 inform (loc, "if this use is part of a public ABI, change it to "
6821 "instead use a constant variable you define");
6822 inform (loc, "the default value for the current CPU tuning "
6823 "is %d bytes", param_destruct_interfere_size);
6824 inform (loc, "you can stabilize this value with %<--param "
6825 "hardware_destructive_interference_size=%d%>, or disable "
6826 "this warning with %<-Wno-interference-size%>",
6827 param_destruct_interfere_size);
6831 /* For element type ELT_TYPE, return the appropriate type of the heap object
6832 containing such element(s). COOKIE_SIZE is NULL or the size of cookie
6833 in bytes. If COOKIE_SIZE is NULL, return array type
6834 ELT_TYPE[FULL_SIZE / sizeof(ELT_TYPE)], otherwise return
6835 struct { size_t[COOKIE_SIZE/sizeof(size_t)]; ELT_TYPE[N]; }
6836 where N is is computed such that the size of the struct fits into FULL_SIZE.
6837 If ARG_SIZE is non-NULL, it is the first argument to the new operator.
6838 It should be passed if ELT_TYPE is zero sized type in which case FULL_SIZE
6839 will be also 0 and so it is not possible to determine the actual array
6840 size. CTX, NON_CONSTANT_P and OVERFLOW_P are used during constant
6841 expression evaluation of subexpressions of ARG_SIZE. */
6843 static tree
6844 build_new_constexpr_heap_type (const constexpr_ctx *ctx, tree elt_type,
6845 tree cookie_size, tree full_size, tree arg_size,
6846 bool *non_constant_p, bool *overflow_p)
6848 gcc_assert (cookie_size == NULL_TREE || tree_fits_uhwi_p (cookie_size));
6849 gcc_assert (tree_fits_uhwi_p (full_size));
6850 unsigned HOST_WIDE_INT csz = cookie_size ? tree_to_uhwi (cookie_size) : 0;
6851 if (arg_size)
6853 STRIP_NOPS (arg_size);
6854 if (cookie_size)
6856 if (TREE_CODE (arg_size) != PLUS_EXPR)
6857 arg_size = NULL_TREE;
6858 else if (TREE_CODE (TREE_OPERAND (arg_size, 0)) == INTEGER_CST
6859 && tree_int_cst_equal (cookie_size,
6860 TREE_OPERAND (arg_size, 0)))
6862 arg_size = TREE_OPERAND (arg_size, 1);
6863 STRIP_NOPS (arg_size);
6865 else if (TREE_CODE (TREE_OPERAND (arg_size, 1)) == INTEGER_CST
6866 && tree_int_cst_equal (cookie_size,
6867 TREE_OPERAND (arg_size, 1)))
6869 arg_size = TREE_OPERAND (arg_size, 0);
6870 STRIP_NOPS (arg_size);
6872 else
6873 arg_size = NULL_TREE;
6875 if (arg_size && TREE_CODE (arg_size) == MULT_EXPR)
6877 tree op0 = TREE_OPERAND (arg_size, 0);
6878 tree op1 = TREE_OPERAND (arg_size, 1);
6879 if (integer_zerop (op0))
6880 arg_size
6881 = cxx_eval_constant_expression (ctx, op1, vc_prvalue,
6882 non_constant_p, overflow_p);
6883 else if (integer_zerop (op1))
6884 arg_size
6885 = cxx_eval_constant_expression (ctx, op0, vc_prvalue,
6886 non_constant_p, overflow_p);
6887 else
6888 arg_size = NULL_TREE;
6890 else
6891 arg_size = NULL_TREE;
6894 unsigned HOST_WIDE_INT fsz = tree_to_uhwi (arg_size ? arg_size : full_size);
6895 if (!arg_size)
6897 unsigned HOST_WIDE_INT esz = int_size_in_bytes (elt_type);
6898 gcc_assert (fsz >= csz);
6899 fsz -= csz;
6900 if (esz)
6901 fsz /= esz;
6903 tree itype2 = build_index_type (size_int (fsz - 1));
6904 if (!cookie_size)
6905 return build_cplus_array_type (elt_type, itype2);
6906 return build_new_constexpr_heap_type (elt_type, cookie_size, itype2);
6909 /* Attempt to reduce the expression T to a constant value.
6910 On failure, issue diagnostic and return error_mark_node. */
6911 /* FIXME unify with c_fully_fold */
6912 /* FIXME overflow_p is too global */
6914 static tree
6915 cxx_eval_constant_expression (const constexpr_ctx *ctx, tree t,
6916 value_cat lval,
6917 bool *non_constant_p, bool *overflow_p,
6918 tree *jump_target /* = NULL */)
6920 if (jump_target && *jump_target)
6922 /* If we are jumping, ignore all statements/expressions except those
6923 that could have LABEL_EXPR or CASE_LABEL_EXPR in their bodies. */
6924 switch (TREE_CODE (t))
6926 case BIND_EXPR:
6927 case STATEMENT_LIST:
6928 case LOOP_EXPR:
6929 case COND_EXPR:
6930 case IF_STMT:
6931 case DO_STMT:
6932 case WHILE_STMT:
6933 case FOR_STMT:
6934 break;
6935 case LABEL_EXPR:
6936 case CASE_LABEL_EXPR:
6937 if (label_matches (ctx, jump_target, t))
6938 /* Found it. */
6939 *jump_target = NULL_TREE;
6940 return NULL_TREE;
6941 default:
6942 return NULL_TREE;
6945 if (error_operand_p (t))
6947 *non_constant_p = true;
6948 return t;
6951 location_t loc = cp_expr_loc_or_input_loc (t);
6953 STRIP_ANY_LOCATION_WRAPPER (t);
6955 if (CONSTANT_CLASS_P (t))
6957 if (TREE_OVERFLOW (t))
6959 if (!ctx->quiet)
6960 permerror (input_location, "overflow in constant expression");
6961 if (!flag_permissive || ctx->quiet)
6962 *overflow_p = true;
6965 if (TREE_CODE (t) == INTEGER_CST
6966 && TYPE_PTR_P (TREE_TYPE (t))
6967 /* INTEGER_CST with pointer-to-method type is only used
6968 for a virtual method in a pointer to member function.
6969 Don't reject those. */
6970 && TREE_CODE (TREE_TYPE (TREE_TYPE (t))) != METHOD_TYPE
6971 && !integer_zerop (t))
6973 if (!ctx->quiet)
6974 error ("value %qE of type %qT is not a constant expression",
6975 t, TREE_TYPE (t));
6976 *non_constant_p = true;
6979 return t;
6982 /* Avoid excessively long constexpr evaluations. */
6983 if (++ctx->global->constexpr_ops_count >= constexpr_ops_limit)
6985 if (!ctx->quiet)
6986 error_at (loc,
6987 "%<constexpr%> evaluation operation count exceeds limit of "
6988 "%wd (use %<-fconstexpr-ops-limit=%> to increase the limit)",
6989 constexpr_ops_limit);
6990 ctx->global->constexpr_ops_count = INTTYPE_MINIMUM (HOST_WIDE_INT);
6991 *non_constant_p = true;
6992 return t;
6995 constexpr_ctx new_ctx;
6996 tree r = t;
6998 tree_code tcode = TREE_CODE (t);
6999 switch (tcode)
7001 case RESULT_DECL:
7002 if (lval)
7003 return t;
7004 /* We ask for an rvalue for the RESULT_DECL when indirecting
7005 through an invisible reference, or in named return value
7006 optimization. */
7007 if (tree v = ctx->global->get_value (t))
7008 return v;
7009 else
7011 if (!ctx->quiet)
7012 error ("%qE is not a constant expression", t);
7013 *non_constant_p = true;
7015 break;
7017 case VAR_DECL:
7018 if (DECL_HAS_VALUE_EXPR_P (t))
7020 if (is_normal_capture_proxy (t)
7021 && current_function_decl == DECL_CONTEXT (t))
7023 /* Function parms aren't constexpr within the function
7024 definition, so don't try to look at the closure. But if the
7025 captured variable is constant, try to evaluate it directly. */
7026 r = DECL_CAPTURED_VARIABLE (t);
7027 tree type = TREE_TYPE (t);
7028 if (TYPE_REF_P (type) != TYPE_REF_P (TREE_TYPE (r)))
7030 /* Adjust r to match the reference-ness of t. */
7031 if (TYPE_REF_P (type))
7032 r = build_address (r);
7033 else
7034 r = convert_from_reference (r);
7037 else
7038 r = DECL_VALUE_EXPR (t);
7039 return cxx_eval_constant_expression (ctx, r, lval, non_constant_p,
7040 overflow_p);
7042 /* fall through */
7043 case CONST_DECL:
7044 /* We used to not check lval for CONST_DECL, but darwin.cc uses
7045 CONST_DECL for aggregate constants. */
7046 if (lval)
7047 return t;
7048 else if (t == ctx->object)
7049 return ctx->ctor;
7050 if (VAR_P (t))
7051 if (tree v = ctx->global->get_value (t))
7053 r = v;
7054 break;
7056 if (ctx->manifestly_const_eval)
7057 maybe_warn_about_constant_value (loc, t);
7058 if (COMPLETE_TYPE_P (TREE_TYPE (t))
7059 && is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
7061 /* If the class is empty, we aren't actually loading anything. */
7062 r = build_constructor (TREE_TYPE (t), NULL);
7063 TREE_CONSTANT (r) = true;
7065 else if (ctx->strict)
7066 r = decl_really_constant_value (t, /*unshare_p=*/false);
7067 else
7068 r = decl_constant_value (t, /*unshare_p=*/false);
7069 if (TREE_CODE (r) == TARGET_EXPR
7070 && TREE_CODE (TARGET_EXPR_INITIAL (r)) == CONSTRUCTOR)
7071 r = TARGET_EXPR_INITIAL (r);
7072 if (DECL_P (r))
7074 if (!ctx->quiet)
7075 non_const_var_error (loc, r, /*fundef_p*/false);
7076 *non_constant_p = true;
7078 break;
7080 case DEBUG_BEGIN_STMT:
7081 /* ??? It might be nice to retain this information somehow, so
7082 as to be able to step into a constexpr function call. */
7083 /* Fall through. */
7085 case FUNCTION_DECL:
7086 case TEMPLATE_DECL:
7087 case LABEL_DECL:
7088 case LABEL_EXPR:
7089 case CASE_LABEL_EXPR:
7090 case PREDICT_EXPR:
7091 return t;
7093 case PARM_DECL:
7094 if (lval && !TYPE_REF_P (TREE_TYPE (t)))
7095 /* glvalue use. */;
7096 else if (tree v = ctx->global->get_value (r))
7097 r = v;
7098 else if (lval)
7099 /* Defer in case this is only used for its type. */;
7100 else if (COMPLETE_TYPE_P (TREE_TYPE (t))
7101 && is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
7103 /* If the class is empty, we aren't actually loading anything. */
7104 r = build_constructor (TREE_TYPE (t), NULL);
7105 TREE_CONSTANT (r) = true;
7107 else
7109 if (!ctx->quiet)
7110 error ("%qE is not a constant expression", t);
7111 *non_constant_p = true;
7113 break;
7115 case CALL_EXPR:
7116 case AGGR_INIT_EXPR:
7117 r = cxx_eval_call_expression (ctx, t, lval,
7118 non_constant_p, overflow_p);
7119 break;
7121 case DECL_EXPR:
7123 r = DECL_EXPR_DECL (t);
7124 if (TREE_CODE (r) == USING_DECL)
7126 r = void_node;
7127 break;
7130 if (VAR_P (r)
7131 && (TREE_STATIC (r)
7132 || (CP_DECL_THREAD_LOCAL_P (r) && !DECL_REALLY_EXTERN (r)))
7133 /* Allow __FUNCTION__ etc. */
7134 && !DECL_ARTIFICIAL (r)
7135 && !decl_constant_var_p (r))
7137 if (!ctx->quiet)
7139 if (CP_DECL_THREAD_LOCAL_P (r))
7140 error_at (loc, "control passes through definition of %qD "
7141 "with thread storage duration", r);
7142 else
7143 error_at (loc, "control passes through definition of %qD "
7144 "with static storage duration", r);
7146 *non_constant_p = true;
7147 break;
7150 if (AGGREGATE_TYPE_P (TREE_TYPE (r))
7151 || VECTOR_TYPE_P (TREE_TYPE (r)))
7153 new_ctx = *ctx;
7154 new_ctx.object = r;
7155 new_ctx.ctor = build_constructor (TREE_TYPE (r), NULL);
7156 CONSTRUCTOR_NO_CLEARING (new_ctx.ctor) = true;
7157 ctx->global->put_value (r, new_ctx.ctor);
7158 ctx = &new_ctx;
7161 if (tree init = DECL_INITIAL (r))
7163 init = cxx_eval_constant_expression (ctx, init, vc_prvalue,
7164 non_constant_p, overflow_p);
7165 /* Don't share a CONSTRUCTOR that might be changed. */
7166 init = unshare_constructor (init);
7167 /* Remember that a constant object's constructor has already
7168 run. */
7169 if (CLASS_TYPE_P (TREE_TYPE (r))
7170 && CP_TYPE_CONST_P (TREE_TYPE (r)))
7171 TREE_READONLY (init) = true;
7172 ctx->global->put_value (r, init);
7174 else if (ctx == &new_ctx)
7175 /* We gave it a CONSTRUCTOR above. */;
7176 else
7177 ctx->global->put_value (r, NULL_TREE);
7179 break;
7181 case TARGET_EXPR:
7183 tree type = TREE_TYPE (t);
7185 if (!literal_type_p (type))
7187 if (!ctx->quiet)
7189 auto_diagnostic_group d;
7190 error ("temporary of non-literal type %qT in a "
7191 "constant expression", type);
7192 explain_non_literal_class (type);
7194 *non_constant_p = true;
7195 break;
7197 gcc_checking_assert (!TARGET_EXPR_DIRECT_INIT_P (t));
7198 /* Avoid evaluating a TARGET_EXPR more than once. */
7199 tree slot = TARGET_EXPR_SLOT (t);
7200 if (tree v = ctx->global->get_value (slot))
7202 if (lval)
7203 return slot;
7204 r = v;
7205 break;
7207 if ((AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type)))
7209 /* We're being expanded without an explicit target, so start
7210 initializing a new object; expansion with an explicit target
7211 strips the TARGET_EXPR before we get here. */
7212 new_ctx = *ctx;
7213 /* Link CTX to NEW_CTX so that lookup_placeholder can resolve
7214 any PLACEHOLDER_EXPR within the initializer that refers to the
7215 former object under construction. */
7216 new_ctx.parent = ctx;
7217 new_ctx.ctor = build_constructor (type, NULL);
7218 CONSTRUCTOR_NO_CLEARING (new_ctx.ctor) = true;
7219 new_ctx.object = slot;
7220 ctx->global->put_value (new_ctx.object, new_ctx.ctor);
7221 ctx = &new_ctx;
7223 /* Pass vc_prvalue because this indicates
7224 initialization of a temporary. */
7225 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1), vc_prvalue,
7226 non_constant_p, overflow_p);
7227 if (*non_constant_p)
7228 break;
7229 /* Adjust the type of the result to the type of the temporary. */
7230 r = adjust_temp_type (type, r);
7231 if (TARGET_EXPR_CLEANUP (t) && !CLEANUP_EH_ONLY (t))
7232 ctx->global->cleanups->safe_push (TARGET_EXPR_CLEANUP (t));
7233 r = unshare_constructor (r);
7234 ctx->global->put_value (slot, r);
7235 if (ctx->save_exprs)
7236 ctx->save_exprs->safe_push (slot);
7237 if (lval)
7238 return slot;
7240 break;
7242 case INIT_EXPR:
7243 case MODIFY_EXPR:
7244 gcc_assert (jump_target == NULL || *jump_target == NULL_TREE);
7245 r = cxx_eval_store_expression (ctx, t, lval,
7246 non_constant_p, overflow_p);
7247 break;
7249 case SCOPE_REF:
7250 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
7251 lval,
7252 non_constant_p, overflow_p);
7253 break;
7255 case RETURN_EXPR:
7256 if (TREE_OPERAND (t, 0) != NULL_TREE)
7257 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
7258 lval,
7259 non_constant_p, overflow_p);
7260 /* FALLTHRU */
7261 case BREAK_STMT:
7262 case CONTINUE_STMT:
7263 if (jump_target)
7264 *jump_target = t;
7265 else
7267 /* Can happen with ({ return true; }) && false; passed to
7268 maybe_constant_value. There is nothing to jump over in this
7269 case, and the bug will be diagnosed later. */
7270 gcc_assert (ctx->quiet);
7271 *non_constant_p = true;
7273 break;
7275 case SAVE_EXPR:
7276 /* Avoid evaluating a SAVE_EXPR more than once. */
7277 if (tree v = ctx->global->get_value (t))
7278 r = v;
7279 else
7281 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), vc_prvalue,
7282 non_constant_p, overflow_p);
7283 if (*non_constant_p)
7284 break;
7285 ctx->global->put_value (t, r);
7286 if (ctx->save_exprs)
7287 ctx->save_exprs->safe_push (t);
7289 break;
7291 case TRY_CATCH_EXPR:
7292 if (TREE_OPERAND (t, 0) == NULL_TREE)
7294 r = void_node;
7295 break;
7297 /* FALLTHRU */
7298 case NON_LVALUE_EXPR:
7299 case TRY_BLOCK:
7300 case MUST_NOT_THROW_EXPR:
7301 case EXPR_STMT:
7302 case EH_SPEC_BLOCK:
7303 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
7304 lval,
7305 non_constant_p, overflow_p,
7306 jump_target);
7307 break;
7309 case CLEANUP_POINT_EXPR:
7311 auto_vec<tree, 2> cleanups;
7312 vec<tree> *prev_cleanups = ctx->global->cleanups;
7313 ctx->global->cleanups = &cleanups;
7314 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
7315 lval,
7316 non_constant_p, overflow_p,
7317 jump_target);
7318 ctx->global->cleanups = prev_cleanups;
7319 unsigned int i;
7320 tree cleanup;
7321 /* Evaluate the cleanups. */
7322 FOR_EACH_VEC_ELT_REVERSE (cleanups, i, cleanup)
7323 cxx_eval_constant_expression (ctx, cleanup, vc_discard,
7324 non_constant_p, overflow_p);
7326 break;
7328 case TRY_FINALLY_EXPR:
7329 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
7330 non_constant_p, overflow_p,
7331 jump_target);
7332 if (!*non_constant_p)
7333 /* Also evaluate the cleanup. */
7334 cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1), vc_discard,
7335 non_constant_p, overflow_p);
7336 break;
7338 case CLEANUP_STMT:
7339 r = cxx_eval_constant_expression (ctx, CLEANUP_BODY (t), lval,
7340 non_constant_p, overflow_p,
7341 jump_target);
7342 if (!CLEANUP_EH_ONLY (t) && !*non_constant_p)
7344 iloc_sentinel ils (loc);
7345 /* Also evaluate the cleanup. */
7346 cxx_eval_constant_expression (ctx, CLEANUP_EXPR (t), vc_discard,
7347 non_constant_p, overflow_p);
7349 break;
7351 /* These differ from cxx_eval_unary_expression in that this doesn't
7352 check for a constant operand or result; an address can be
7353 constant without its operand being, and vice versa. */
7354 case MEM_REF:
7355 case INDIRECT_REF:
7356 r = cxx_eval_indirect_ref (ctx, t, lval,
7357 non_constant_p, overflow_p);
7358 break;
7360 case ADDR_EXPR:
7362 tree oldop = TREE_OPERAND (t, 0);
7363 tree op = cxx_eval_constant_expression (ctx, oldop, vc_glvalue,
7364 non_constant_p, overflow_p);
7365 /* Don't VERIFY_CONSTANT here. */
7366 if (*non_constant_p)
7367 return t;
7368 gcc_checking_assert (TREE_CODE (op) != CONSTRUCTOR);
7369 /* This function does more aggressive folding than fold itself. */
7370 r = build_fold_addr_expr_with_type (op, TREE_TYPE (t));
7371 if (TREE_CODE (r) == ADDR_EXPR && TREE_OPERAND (r, 0) == oldop)
7373 ggc_free (r);
7374 return t;
7376 break;
7379 case REALPART_EXPR:
7380 case IMAGPART_EXPR:
7381 if (lval)
7383 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
7384 non_constant_p, overflow_p);
7385 if (r == error_mark_node)
7387 else if (r == TREE_OPERAND (t, 0) || lval == vc_discard)
7388 r = t;
7389 else
7390 r = fold_build1 (TREE_CODE (t), TREE_TYPE (t), r);
7391 break;
7393 /* FALLTHRU */
7394 case CONJ_EXPR:
7395 case FIX_TRUNC_EXPR:
7396 case FLOAT_EXPR:
7397 case NEGATE_EXPR:
7398 case ABS_EXPR:
7399 case ABSU_EXPR:
7400 case BIT_NOT_EXPR:
7401 case TRUTH_NOT_EXPR:
7402 case FIXED_CONVERT_EXPR:
7403 r = cxx_eval_unary_expression (ctx, t, lval,
7404 non_constant_p, overflow_p);
7405 break;
7407 case SIZEOF_EXPR:
7408 r = fold_sizeof_expr (t);
7409 /* In a template, fold_sizeof_expr may merely create a new SIZEOF_EXPR,
7410 which could lead to an infinite recursion. */
7411 if (TREE_CODE (r) != SIZEOF_EXPR)
7412 r = cxx_eval_constant_expression (ctx, r, lval,
7413 non_constant_p, overflow_p,
7414 jump_target);
7415 else
7417 *non_constant_p = true;
7418 gcc_assert (ctx->quiet);
7421 break;
7423 case COMPOUND_EXPR:
7425 /* check_return_expr sometimes wraps a TARGET_EXPR in a
7426 COMPOUND_EXPR; don't get confused. Also handle EMPTY_CLASS_EXPR
7427 introduced by build_call_a. */
7428 tree op0 = TREE_OPERAND (t, 0);
7429 tree op1 = TREE_OPERAND (t, 1);
7430 STRIP_NOPS (op1);
7431 if ((TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
7432 || TREE_CODE (op1) == EMPTY_CLASS_EXPR)
7433 r = cxx_eval_constant_expression (ctx, op0,
7434 lval, non_constant_p, overflow_p,
7435 jump_target);
7436 else
7438 /* Check that the LHS is constant and then discard it. */
7439 cxx_eval_constant_expression (ctx, op0, vc_discard,
7440 non_constant_p, overflow_p,
7441 jump_target);
7442 if (*non_constant_p)
7443 return t;
7444 op1 = TREE_OPERAND (t, 1);
7445 r = cxx_eval_constant_expression (ctx, op1,
7446 lval, non_constant_p, overflow_p,
7447 jump_target);
7450 break;
7452 case POINTER_PLUS_EXPR:
7453 case POINTER_DIFF_EXPR:
7454 case PLUS_EXPR:
7455 case MINUS_EXPR:
7456 case MULT_EXPR:
7457 case TRUNC_DIV_EXPR:
7458 case CEIL_DIV_EXPR:
7459 case FLOOR_DIV_EXPR:
7460 case ROUND_DIV_EXPR:
7461 case TRUNC_MOD_EXPR:
7462 case CEIL_MOD_EXPR:
7463 case ROUND_MOD_EXPR:
7464 case RDIV_EXPR:
7465 case EXACT_DIV_EXPR:
7466 case MIN_EXPR:
7467 case MAX_EXPR:
7468 case LSHIFT_EXPR:
7469 case RSHIFT_EXPR:
7470 case LROTATE_EXPR:
7471 case RROTATE_EXPR:
7472 case BIT_IOR_EXPR:
7473 case BIT_XOR_EXPR:
7474 case BIT_AND_EXPR:
7475 case TRUTH_XOR_EXPR:
7476 case LT_EXPR:
7477 case LE_EXPR:
7478 case GT_EXPR:
7479 case GE_EXPR:
7480 case EQ_EXPR:
7481 case NE_EXPR:
7482 case SPACESHIP_EXPR:
7483 case UNORDERED_EXPR:
7484 case ORDERED_EXPR:
7485 case UNLT_EXPR:
7486 case UNLE_EXPR:
7487 case UNGT_EXPR:
7488 case UNGE_EXPR:
7489 case UNEQ_EXPR:
7490 case LTGT_EXPR:
7491 case RANGE_EXPR:
7492 case COMPLEX_EXPR:
7493 r = cxx_eval_binary_expression (ctx, t, lval,
7494 non_constant_p, overflow_p);
7495 break;
7497 /* fold can introduce non-IF versions of these; still treat them as
7498 short-circuiting. */
7499 case TRUTH_AND_EXPR:
7500 case TRUTH_ANDIF_EXPR:
7501 r = cxx_eval_logical_expression (ctx, t, boolean_false_node,
7502 boolean_true_node,
7503 non_constant_p, overflow_p);
7504 break;
7506 case TRUTH_OR_EXPR:
7507 case TRUTH_ORIF_EXPR:
7508 r = cxx_eval_logical_expression (ctx, t, boolean_true_node,
7509 boolean_false_node,
7510 non_constant_p, overflow_p);
7511 break;
7513 case ARRAY_REF:
7514 r = cxx_eval_array_reference (ctx, t, lval,
7515 non_constant_p, overflow_p);
7516 break;
7518 case COMPONENT_REF:
7519 if (is_overloaded_fn (t))
7521 /* We can only get here in checking mode via
7522 build_non_dependent_expr, because any expression that
7523 calls or takes the address of the function will have
7524 pulled a FUNCTION_DECL out of the COMPONENT_REF. */
7525 gcc_checking_assert (ctx->quiet || errorcount);
7526 *non_constant_p = true;
7527 return t;
7529 r = cxx_eval_component_reference (ctx, t, lval,
7530 non_constant_p, overflow_p);
7531 break;
7533 case BIT_FIELD_REF:
7534 r = cxx_eval_bit_field_ref (ctx, t, lval,
7535 non_constant_p, overflow_p);
7536 break;
7538 case COND_EXPR:
7539 case IF_STMT:
7540 if (jump_target && *jump_target)
7542 tree orig_jump = *jump_target;
7543 tree arg = ((TREE_CODE (t) != IF_STMT || TREE_OPERAND (t, 1))
7544 ? TREE_OPERAND (t, 1) : void_node);
7545 /* When jumping to a label, the label might be either in the
7546 then or else blocks, so process then block first in skipping
7547 mode first, and if we are still in the skipping mode at its end,
7548 process the else block too. */
7549 r = cxx_eval_constant_expression (ctx, arg, lval, non_constant_p,
7550 overflow_p, jump_target);
7551 /* It's possible that we found the label in the then block. But
7552 it could have been followed by another jumping statement, e.g.
7553 say we're looking for case 1:
7554 if (cond)
7556 // skipped statements
7557 case 1:; // clears up *jump_target
7558 return 1; // and sets it to a RETURN_EXPR
7560 else { ... }
7561 in which case we need not go looking to the else block.
7562 (goto is not allowed in a constexpr function.) */
7563 if (*jump_target == orig_jump)
7565 arg = ((TREE_CODE (t) != IF_STMT || TREE_OPERAND (t, 2))
7566 ? TREE_OPERAND (t, 2) : void_node);
7567 r = cxx_eval_constant_expression (ctx, arg, lval, non_constant_p,
7568 overflow_p, jump_target);
7570 break;
7572 r = cxx_eval_conditional_expression (ctx, t, lval,
7573 non_constant_p, overflow_p,
7574 jump_target);
7575 break;
7576 case VEC_COND_EXPR:
7577 r = cxx_eval_vector_conditional_expression (ctx, t, non_constant_p,
7578 overflow_p);
7579 break;
7581 case CONSTRUCTOR:
7582 if (TREE_CONSTANT (t) && reduced_constant_expression_p (t))
7584 /* Don't re-process a constant CONSTRUCTOR. */
7585 verify_constructor_flags (t);
7586 if (TREE_CONSTANT (t))
7587 return t;
7589 r = cxx_eval_bare_aggregate (ctx, t, lval,
7590 non_constant_p, overflow_p);
7591 break;
7593 case VEC_INIT_EXPR:
7594 /* We can get this in a defaulted constructor for a class with a
7595 non-static data member of array type. Either the initializer will
7596 be NULL, meaning default-initialization, or it will be an lvalue
7597 or xvalue of the same type, meaning direct-initialization from the
7598 corresponding member. */
7599 r = cxx_eval_vec_init (ctx, t, lval,
7600 non_constant_p, overflow_p);
7601 break;
7603 case VEC_PERM_EXPR:
7604 r = cxx_eval_trinary_expression (ctx, t, lval,
7605 non_constant_p, overflow_p);
7606 break;
7608 case PAREN_EXPR:
7609 gcc_assert (!REF_PARENTHESIZED_P (t));
7610 /* A PAREN_EXPR resulting from __builtin_assoc_barrier has no effect in
7611 constant expressions since it's unaffected by -fassociative-math. */
7612 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
7613 non_constant_p, overflow_p);
7614 break;
7616 case NOP_EXPR:
7617 if (REINTERPRET_CAST_P (t))
7619 if (!ctx->quiet)
7620 error_at (loc,
7621 "%<reinterpret_cast%> is not a constant expression");
7622 *non_constant_p = true;
7623 return t;
7625 /* FALLTHROUGH. */
7626 case CONVERT_EXPR:
7627 case VIEW_CONVERT_EXPR:
7628 case UNARY_PLUS_EXPR:
7630 tree oldop = TREE_OPERAND (t, 0);
7632 tree op = cxx_eval_constant_expression (ctx, oldop,
7633 lval,
7634 non_constant_p, overflow_p);
7635 if (*non_constant_p)
7636 return t;
7637 tree type = TREE_TYPE (t);
7639 if (VOID_TYPE_P (type))
7640 return void_node;
7642 if (TREE_CODE (t) == CONVERT_EXPR
7643 && ARITHMETIC_TYPE_P (type)
7644 && INDIRECT_TYPE_P (TREE_TYPE (op))
7645 && ctx->manifestly_const_eval)
7647 if (!ctx->quiet)
7648 error_at (loc,
7649 "conversion from pointer type %qT to arithmetic type "
7650 "%qT in a constant expression", TREE_TYPE (op), type);
7651 *non_constant_p = true;
7652 return t;
7655 /* [expr.const]: a conversion from type cv void* to a pointer-to-object
7656 type cannot be part of a core constant expression as a resolution to
7657 DR 1312. */
7658 if (TYPE_PTROB_P (type)
7659 && TYPE_PTR_P (TREE_TYPE (op))
7660 && VOID_TYPE_P (TREE_TYPE (TREE_TYPE (op)))
7661 /* Inside a call to std::construct_at or to
7662 std::allocator<T>::{,de}allocate, we permit casting from void*
7663 because that is compiler-generated code. */
7664 && !is_std_construct_at (ctx->call)
7665 && !is_std_allocator_allocate (ctx->call))
7667 /* Likewise, don't error when casting from void* when OP is
7668 &heap uninit and similar. */
7669 tree sop = tree_strip_nop_conversions (op);
7670 if (TREE_CODE (sop) == ADDR_EXPR
7671 && VAR_P (TREE_OPERAND (sop, 0))
7672 && DECL_ARTIFICIAL (TREE_OPERAND (sop, 0)))
7673 /* OK */;
7674 else
7676 if (!ctx->quiet)
7677 error_at (loc, "cast from %qT is not allowed",
7678 TREE_TYPE (op));
7679 *non_constant_p = true;
7680 return t;
7684 if (TREE_CODE (op) == PTRMEM_CST && !TYPE_PTRMEM_P (type))
7685 op = cplus_expand_constant (op);
7687 if (TREE_CODE (op) == PTRMEM_CST && tcode == NOP_EXPR)
7689 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (op))
7690 && !can_convert_qual (type, op))
7691 op = cplus_expand_constant (op);
7692 return cp_fold_convert (type, op);
7695 if (INDIRECT_TYPE_P (type) && TREE_CODE (op) == INTEGER_CST)
7697 if (integer_zerop (op))
7699 if (TYPE_REF_P (type))
7701 if (!ctx->quiet)
7702 error_at (loc, "dereferencing a null pointer");
7703 *non_constant_p = true;
7704 return t;
7707 else
7709 /* This detects for example:
7710 reinterpret_cast<void*>(sizeof 0)
7712 if (!ctx->quiet)
7713 error_at (loc, "%<reinterpret_cast<%T>(%E)%> is not "
7714 "a constant expression",
7715 type, op);
7716 *non_constant_p = true;
7717 return t;
7721 if (INDIRECT_TYPE_P (type)
7722 && TREE_CODE (op) == NOP_EXPR
7723 && TREE_TYPE (op) == ptr_type_node
7724 && TREE_CODE (TREE_OPERAND (op, 0)) == ADDR_EXPR
7725 && VAR_P (TREE_OPERAND (TREE_OPERAND (op, 0), 0))
7726 && (DECL_NAME (TREE_OPERAND (TREE_OPERAND (op, 0),
7727 0)) == heap_uninit_identifier
7728 || DECL_NAME (TREE_OPERAND (TREE_OPERAND (op, 0),
7729 0)) == heap_vec_uninit_identifier))
7731 tree var = TREE_OPERAND (TREE_OPERAND (op, 0), 0);
7732 tree var_size = TYPE_SIZE_UNIT (TREE_TYPE (var));
7733 tree elt_type = TREE_TYPE (type);
7734 tree cookie_size = NULL_TREE;
7735 tree arg_size = NULL_TREE;
7736 if (TREE_CODE (elt_type) == RECORD_TYPE
7737 && TYPE_NAME (elt_type) == heap_identifier)
7739 tree fld1 = TYPE_FIELDS (elt_type);
7740 tree fld2 = DECL_CHAIN (fld1);
7741 elt_type = TREE_TYPE (TREE_TYPE (fld2));
7742 cookie_size = TYPE_SIZE_UNIT (TREE_TYPE (fld1));
7744 DECL_NAME (var)
7745 = (DECL_NAME (var) == heap_uninit_identifier
7746 ? heap_identifier : heap_vec_identifier);
7747 /* For zero sized elt_type, try to recover how many outer_nelts
7748 it should have. */
7749 if ((cookie_size ? tree_int_cst_equal (var_size, cookie_size)
7750 : integer_zerop (var_size))
7751 && !int_size_in_bytes (elt_type)
7752 && TREE_CODE (oldop) == CALL_EXPR
7753 && call_expr_nargs (oldop) >= 1)
7754 if (tree fun = get_function_named_in_call (oldop))
7755 if (cxx_replaceable_global_alloc_fn (fun)
7756 && IDENTIFIER_NEW_OP_P (DECL_NAME (fun)))
7757 arg_size = CALL_EXPR_ARG (oldop, 0);
7758 TREE_TYPE (var)
7759 = build_new_constexpr_heap_type (ctx, elt_type, cookie_size,
7760 var_size, arg_size,
7761 non_constant_p, overflow_p);
7762 TREE_TYPE (TREE_OPERAND (op, 0))
7763 = build_pointer_type (TREE_TYPE (var));
7766 if (op == oldop && tcode != UNARY_PLUS_EXPR)
7767 /* We didn't fold at the top so we could check for ptr-int
7768 conversion. */
7769 return fold (t);
7771 tree sop;
7773 /* Handle an array's bounds having been deduced after we built
7774 the wrapping expression. */
7775 if (same_type_ignoring_tlq_and_bounds_p (type, TREE_TYPE (op)))
7776 r = op;
7777 else if (sop = tree_strip_nop_conversions (op),
7778 sop != op && (same_type_ignoring_tlq_and_bounds_p
7779 (type, TREE_TYPE (sop))))
7780 r = sop;
7781 else if (tcode == UNARY_PLUS_EXPR)
7782 r = fold_convert (TREE_TYPE (t), op);
7783 else
7784 r = fold_build1 (tcode, type, op);
7786 /* Conversion of an out-of-range value has implementation-defined
7787 behavior; the language considers it different from arithmetic
7788 overflow, which is undefined. */
7789 if (TREE_OVERFLOW_P (r) && !TREE_OVERFLOW_P (op))
7790 TREE_OVERFLOW (r) = false;
7792 break;
7794 case EXCESS_PRECISION_EXPR:
7796 tree oldop = TREE_OPERAND (t, 0);
7798 tree op = cxx_eval_constant_expression (ctx, oldop,
7799 lval,
7800 non_constant_p, overflow_p);
7801 if (*non_constant_p)
7802 return t;
7803 r = fold_convert (TREE_TYPE (t), op);
7804 break;
7807 case EMPTY_CLASS_EXPR:
7808 /* Handle EMPTY_CLASS_EXPR produced by build_call_a by lowering
7809 it to an appropriate CONSTRUCTOR. */
7810 return build_constructor (TREE_TYPE (t), NULL);
7812 case STATEMENT_LIST:
7813 new_ctx = *ctx;
7814 new_ctx.ctor = new_ctx.object = NULL_TREE;
7815 return cxx_eval_statement_list (&new_ctx, t,
7816 non_constant_p, overflow_p, jump_target);
7818 case BIND_EXPR:
7819 return cxx_eval_constant_expression (ctx, BIND_EXPR_BODY (t),
7820 lval,
7821 non_constant_p, overflow_p,
7822 jump_target);
7824 case PREINCREMENT_EXPR:
7825 case POSTINCREMENT_EXPR:
7826 case PREDECREMENT_EXPR:
7827 case POSTDECREMENT_EXPR:
7828 return cxx_eval_increment_expression (ctx, t,
7829 lval, non_constant_p, overflow_p);
7831 case LAMBDA_EXPR:
7832 case NEW_EXPR:
7833 case VEC_NEW_EXPR:
7834 case DELETE_EXPR:
7835 case VEC_DELETE_EXPR:
7836 case THROW_EXPR:
7837 case MODOP_EXPR:
7838 /* GCC internal stuff. */
7839 case VA_ARG_EXPR:
7840 case NON_DEPENDENT_EXPR:
7841 case BASELINK:
7842 case OFFSET_REF:
7843 if (!ctx->quiet)
7844 error_at (loc, "expression %qE is not a constant expression", t);
7845 *non_constant_p = true;
7846 break;
7848 case OBJ_TYPE_REF:
7849 /* Virtual function lookup. We don't need to do anything fancy. */
7850 return cxx_eval_constant_expression (ctx, OBJ_TYPE_REF_EXPR (t),
7851 lval, non_constant_p, overflow_p);
7853 case PLACEHOLDER_EXPR:
7854 /* Use of the value or address of the current object. */
7855 if (tree ctor = lookup_placeholder (ctx, lval, TREE_TYPE (t)))
7857 if (TREE_CODE (ctor) == CONSTRUCTOR)
7858 return ctor;
7859 else
7860 return cxx_eval_constant_expression (ctx, ctor, lval,
7861 non_constant_p, overflow_p);
7863 /* A placeholder without a referent. We can get here when
7864 checking whether NSDMIs are noexcept, or in massage_init_elt;
7865 just say it's non-constant for now. */
7866 gcc_assert (ctx->quiet);
7867 *non_constant_p = true;
7868 break;
7870 case EXIT_EXPR:
7872 tree cond = TREE_OPERAND (t, 0);
7873 cond = cxx_eval_constant_expression (ctx, cond, vc_prvalue,
7874 non_constant_p, overflow_p);
7875 VERIFY_CONSTANT (cond);
7876 if (integer_nonzerop (cond))
7877 *jump_target = t;
7879 break;
7881 case GOTO_EXPR:
7882 if (breaks (&TREE_OPERAND (t, 0))
7883 || continues (&TREE_OPERAND (t, 0)))
7884 *jump_target = TREE_OPERAND (t, 0);
7885 else
7887 gcc_assert (cxx_dialect >= cxx23);
7888 if (!ctx->quiet)
7889 error_at (loc, "%<goto%> is not a constant expression");
7890 *non_constant_p = true;
7892 break;
7894 case LOOP_EXPR:
7895 case DO_STMT:
7896 case WHILE_STMT:
7897 case FOR_STMT:
7898 cxx_eval_loop_expr (ctx, t,
7899 non_constant_p, overflow_p, jump_target);
7900 break;
7902 case SWITCH_EXPR:
7903 case SWITCH_STMT:
7904 cxx_eval_switch_expr (ctx, t,
7905 non_constant_p, overflow_p, jump_target);
7906 break;
7908 case REQUIRES_EXPR:
7909 /* It's possible to get a requires-expression in a constant
7910 expression. For example:
7912 template<typename T> concept bool C() {
7913 return requires (T t) { t; };
7916 template<typename T> requires !C<T>() void f(T);
7918 Normalization leaves f with the associated constraint
7919 '!requires (T t) { ... }' which is not transformed into
7920 a constraint. */
7921 if (!processing_template_decl)
7922 return evaluate_requires_expr (t);
7923 else
7924 *non_constant_p = true;
7925 return t;
7927 case ANNOTATE_EXPR:
7928 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
7929 lval,
7930 non_constant_p, overflow_p,
7931 jump_target);
7932 break;
7934 case USING_STMT:
7935 r = void_node;
7936 break;
7938 case ASSERTION_STMT:
7939 case PRECONDITION_STMT:
7940 case POSTCONDITION_STMT:
7942 contract_semantic semantic = get_contract_semantic (t);
7943 if (semantic == CCS_IGNORE)
7944 break;
7946 if (!cxx_eval_assert (ctx, CONTRACT_CONDITION (t),
7947 G_("contract predicate is false in "
7948 "constant expression"),
7949 EXPR_LOCATION (t), checked_contract_p (semantic),
7950 non_constant_p, overflow_p))
7951 *non_constant_p = true;
7952 r = void_node;
7954 break;
7956 case TEMPLATE_ID_EXPR:
7958 /* We can evaluate template-id that refers to a concept only if
7959 the template arguments are non-dependent. */
7960 tree id = unpack_concept_check (t);
7961 tree tmpl = TREE_OPERAND (id, 0);
7962 if (!concept_definition_p (tmpl))
7963 internal_error ("unexpected template-id %qE", t);
7965 if (function_concept_p (tmpl))
7967 if (!ctx->quiet)
7968 error_at (cp_expr_loc_or_input_loc (t),
7969 "function concept must be called");
7970 r = error_mark_node;
7971 break;
7974 if (!value_dependent_expression_p (t)
7975 && !uid_sensitive_constexpr_evaluation_p ())
7976 r = evaluate_concept_check (t);
7977 else
7978 *non_constant_p = true;
7980 break;
7983 case ASM_EXPR:
7984 if (!ctx->quiet)
7985 inline_asm_in_constexpr_error (loc, /*constexpr_fundef_p*/false);
7986 *non_constant_p = true;
7987 return t;
7989 case BIT_CAST_EXPR:
7990 if (lval)
7992 if (!ctx->quiet)
7993 error_at (EXPR_LOCATION (t),
7994 "address of a call to %qs is not a constant expression",
7995 "__builtin_bit_cast");
7996 *non_constant_p = true;
7997 return t;
7999 r = cxx_eval_bit_cast (ctx, t, non_constant_p, overflow_p);
8000 break;
8002 default:
8003 if (STATEMENT_CODE_P (TREE_CODE (t)))
8005 /* This function doesn't know how to deal with pre-genericize
8006 statements; this can only happen with statement-expressions,
8007 so for now just fail. */
8008 if (!ctx->quiet)
8009 error_at (EXPR_LOCATION (t),
8010 "statement is not a constant expression");
8012 else
8013 internal_error ("unexpected expression %qE of kind %s", t,
8014 get_tree_code_name (TREE_CODE (t)));
8015 *non_constant_p = true;
8016 break;
8019 if (r == error_mark_node)
8020 *non_constant_p = true;
8022 if (*non_constant_p)
8023 return t;
8024 else
8025 return r;
8028 /* P0859: A function is needed for constant evaluation if it is a constexpr
8029 function that is named by an expression ([basic.def.odr]) that is
8030 potentially constant evaluated.
8032 So we need to instantiate any constexpr functions mentioned by the
8033 expression even if the definition isn't needed for evaluating the
8034 expression. */
8036 static tree
8037 instantiate_cx_fn_r (tree *tp, int *walk_subtrees, void */*data*/)
8039 if (TREE_CODE (*tp) == FUNCTION_DECL
8040 && DECL_DECLARED_CONSTEXPR_P (*tp)
8041 && !DECL_INITIAL (*tp)
8042 && !trivial_fn_p (*tp)
8043 && DECL_TEMPLOID_INSTANTIATION (*tp)
8044 && !uid_sensitive_constexpr_evaluation_p ())
8046 ++function_depth;
8047 instantiate_decl (*tp, /*defer_ok*/false, /*expl_inst*/false);
8048 --function_depth;
8050 else if (TREE_CODE (*tp) == CALL_EXPR
8051 || TREE_CODE (*tp) == AGGR_INIT_EXPR)
8053 if (EXPR_HAS_LOCATION (*tp))
8054 input_location = EXPR_LOCATION (*tp);
8057 if (!EXPR_P (*tp))
8058 *walk_subtrees = 0;
8060 return NULL_TREE;
8063 static void
8064 instantiate_constexpr_fns (tree t)
8066 location_t loc = input_location;
8067 cp_walk_tree_without_duplicates (&t, instantiate_cx_fn_r, NULL);
8068 input_location = loc;
8071 /* Look for heap variables in the expression *TP. */
8073 static tree
8074 find_heap_var_refs (tree *tp, int *walk_subtrees, void */*data*/)
8076 if (VAR_P (*tp)
8077 && (DECL_NAME (*tp) == heap_uninit_identifier
8078 || DECL_NAME (*tp) == heap_identifier
8079 || DECL_NAME (*tp) == heap_vec_uninit_identifier
8080 || DECL_NAME (*tp) == heap_vec_identifier
8081 || DECL_NAME (*tp) == heap_deleted_identifier))
8082 return *tp;
8084 if (TYPE_P (*tp))
8085 *walk_subtrees = 0;
8086 return NULL_TREE;
8089 /* Find immediate function decls in *TP if any. */
8091 static tree
8092 find_immediate_fndecl (tree *tp, int */*walk_subtrees*/, void */*data*/)
8094 if (TREE_CODE (*tp) == FUNCTION_DECL && DECL_IMMEDIATE_FUNCTION_P (*tp))
8095 return *tp;
8096 if (TREE_CODE (*tp) == PTRMEM_CST
8097 && TREE_CODE (PTRMEM_CST_MEMBER (*tp)) == FUNCTION_DECL
8098 && DECL_IMMEDIATE_FUNCTION_P (PTRMEM_CST_MEMBER (*tp)))
8099 return PTRMEM_CST_MEMBER (*tp);
8100 return NULL_TREE;
8103 /* T has TREE_CONSTANT set but has been deemed not a valid C++ constant
8104 expression. Return a version of T that has TREE_CONSTANT cleared. */
8106 static tree
8107 mark_non_constant (tree t)
8109 gcc_checking_assert (TREE_CONSTANT (t));
8111 /* This isn't actually constant, so unset TREE_CONSTANT.
8112 Don't clear TREE_CONSTANT on ADDR_EXPR, as the middle-end requires
8113 it to be set if it is invariant address, even when it is not
8114 a valid C++ constant expression. Wrap it with a NOP_EXPR
8115 instead. */
8116 if (EXPR_P (t) && TREE_CODE (t) != ADDR_EXPR)
8117 t = copy_node (t);
8118 else if (TREE_CODE (t) == CONSTRUCTOR)
8119 t = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (t), t);
8120 else
8121 t = build_nop (TREE_TYPE (t), t);
8122 TREE_CONSTANT (t) = false;
8123 return t;
8126 /* ALLOW_NON_CONSTANT is false if T is required to be a constant expression.
8127 STRICT has the same sense as for constant_value_1: true if we only allow
8128 conforming C++ constant expressions, or false if we want a constant value
8129 even if it doesn't conform.
8130 MANIFESTLY_CONST_EVAL is true if T is manifestly const-evaluated as
8131 per P0595 even when ALLOW_NON_CONSTANT is true.
8132 CONSTEXPR_DTOR is true when evaluating the dtor of a constexpr variable.
8133 OBJECT must be non-NULL in that case. */
8135 static tree
8136 cxx_eval_outermost_constant_expr (tree t, bool allow_non_constant,
8137 bool strict = true,
8138 bool manifestly_const_eval = false,
8139 bool constexpr_dtor = false,
8140 tree object = NULL_TREE)
8142 auto_timevar time (TV_CONSTEXPR);
8144 bool non_constant_p = false;
8145 bool overflow_p = false;
8147 if (BRACE_ENCLOSED_INITIALIZER_P (t))
8149 gcc_checking_assert (allow_non_constant);
8150 return t;
8153 constexpr_global_ctx global_ctx;
8154 constexpr_ctx ctx = { &global_ctx, NULL, NULL, NULL, NULL, NULL, NULL,
8155 allow_non_constant, strict,
8156 manifestly_const_eval || !allow_non_constant };
8158 /* Turn off -frounding-math for manifestly constant evaluation. */
8159 warning_sentinel rm (flag_rounding_math, ctx.manifestly_const_eval);
8160 tree type = initialized_type (t);
8161 tree r = t;
8162 bool is_consteval = false;
8163 if (VOID_TYPE_P (type))
8165 if (constexpr_dtor)
8166 /* Used for destructors of array elements. */
8167 type = TREE_TYPE (object);
8168 else
8170 if (cxx_dialect < cxx20)
8171 return t;
8172 if (TREE_CODE (t) != CALL_EXPR && TREE_CODE (t) != AGGR_INIT_EXPR)
8173 return t;
8174 /* Calls to immediate functions returning void need to be
8175 evaluated. */
8176 tree fndecl = cp_get_callee_fndecl_nofold (t);
8177 if (fndecl == NULL_TREE || !DECL_IMMEDIATE_FUNCTION_P (fndecl))
8178 return t;
8179 else
8180 is_consteval = true;
8183 else if (cxx_dialect >= cxx20
8184 && (TREE_CODE (t) == CALL_EXPR
8185 || TREE_CODE (t) == AGGR_INIT_EXPR
8186 || TREE_CODE (t) == TARGET_EXPR))
8188 /* For non-concept checks, determine if it is consteval. */
8189 if (!concept_check_p (t))
8191 tree x = t;
8192 if (TREE_CODE (x) == TARGET_EXPR)
8193 x = TARGET_EXPR_INITIAL (x);
8194 tree fndecl = cp_get_callee_fndecl_nofold (x);
8195 if (fndecl && DECL_IMMEDIATE_FUNCTION_P (fndecl))
8196 is_consteval = true;
8199 if (AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type))
8201 /* In C++14 an NSDMI can participate in aggregate initialization,
8202 and can refer to the address of the object being initialized, so
8203 we need to pass in the relevant VAR_DECL if we want to do the
8204 evaluation in a single pass. The evaluation will dynamically
8205 update ctx.values for the VAR_DECL. We use the same strategy
8206 for C++11 constexpr constructors that refer to the object being
8207 initialized. */
8208 if (constexpr_dtor)
8210 gcc_assert (object && VAR_P (object));
8211 gcc_assert (DECL_DECLARED_CONSTEXPR_P (object));
8212 gcc_assert (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (object));
8213 if (error_operand_p (DECL_INITIAL (object)))
8214 return t;
8215 ctx.ctor = unshare_expr (DECL_INITIAL (object));
8216 TREE_READONLY (ctx.ctor) = false;
8217 /* Temporarily force decl_really_constant_value to return false
8218 for it, we want to use ctx.ctor for the current value instead. */
8219 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (object) = false;
8221 else
8223 ctx.ctor = build_constructor (type, NULL);
8224 CONSTRUCTOR_NO_CLEARING (ctx.ctor) = true;
8226 if (!object)
8228 if (TREE_CODE (t) == TARGET_EXPR)
8229 object = TARGET_EXPR_SLOT (t);
8230 else if (TREE_CODE (t) == AGGR_INIT_EXPR)
8231 object = AGGR_INIT_EXPR_SLOT (t);
8233 ctx.object = object;
8234 if (object)
8235 gcc_assert (same_type_ignoring_top_level_qualifiers_p
8236 (type, TREE_TYPE (object)));
8237 if (object && DECL_P (object))
8238 global_ctx.put_value (object, ctx.ctor);
8239 if (TREE_CODE (r) == TARGET_EXPR)
8240 /* Avoid creating another CONSTRUCTOR when we expand the
8241 TARGET_EXPR. */
8242 r = TARGET_EXPR_INITIAL (r);
8245 auto_vec<tree, 16> cleanups;
8246 global_ctx.cleanups = &cleanups;
8248 if (manifestly_const_eval)
8249 instantiate_constexpr_fns (r);
8250 r = cxx_eval_constant_expression (&ctx, r, vc_prvalue,
8251 &non_constant_p, &overflow_p);
8253 if (!constexpr_dtor)
8254 verify_constant (r, allow_non_constant, &non_constant_p, &overflow_p);
8255 else
8256 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (object) = true;
8258 unsigned int i;
8259 tree cleanup;
8260 /* Evaluate the cleanups. */
8261 FOR_EACH_VEC_ELT_REVERSE (cleanups, i, cleanup)
8262 cxx_eval_constant_expression (&ctx, cleanup, vc_discard,
8263 &non_constant_p, &overflow_p);
8265 /* Mutable logic is a bit tricky: we want to allow initialization of
8266 constexpr variables with mutable members, but we can't copy those
8267 members to another constexpr variable. */
8268 if (TREE_CODE (r) == CONSTRUCTOR && CONSTRUCTOR_MUTABLE_POISON (r))
8270 if (!allow_non_constant)
8271 error ("%qE is not a constant expression because it refers to "
8272 "mutable subobjects of %qT", t, type);
8273 non_constant_p = true;
8276 if (TREE_CODE (r) == CONSTRUCTOR && CONSTRUCTOR_NO_CLEARING (r))
8278 if (!allow_non_constant)
8279 error ("%qE is not a constant expression because it refers to "
8280 "an incompletely initialized variable", t);
8281 TREE_CONSTANT (r) = false;
8282 non_constant_p = true;
8285 if (!global_ctx.heap_vars.is_empty ())
8287 tree heap_var = cp_walk_tree_without_duplicates (&r, find_heap_var_refs,
8288 NULL);
8289 unsigned int i;
8290 if (heap_var)
8292 if (!allow_non_constant && !non_constant_p)
8293 error_at (DECL_SOURCE_LOCATION (heap_var),
8294 "%qE is not a constant expression because it refers to "
8295 "a result of %<operator new%>", t);
8296 r = t;
8297 non_constant_p = true;
8299 FOR_EACH_VEC_ELT (global_ctx.heap_vars, i, heap_var)
8301 if (DECL_NAME (heap_var) != heap_deleted_identifier)
8303 if (!allow_non_constant && !non_constant_p)
8304 error_at (DECL_SOURCE_LOCATION (heap_var),
8305 "%qE is not a constant expression because allocated "
8306 "storage has not been deallocated", t);
8307 r = t;
8308 non_constant_p = true;
8310 varpool_node::get (heap_var)->remove ();
8314 /* Check that immediate invocation does not return an expression referencing
8315 any immediate function decls. */
8316 if (is_consteval || in_immediate_context ())
8317 if (tree immediate_fndecl
8318 = cp_walk_tree_without_duplicates (&r, find_immediate_fndecl,
8319 NULL))
8321 if (!allow_non_constant && !non_constant_p)
8322 error_at (cp_expr_loc_or_input_loc (t),
8323 "immediate evaluation returns address of immediate "
8324 "function %qD", immediate_fndecl);
8325 r = t;
8326 non_constant_p = true;
8329 if (non_constant_p)
8330 /* If we saw something bad, go back to our argument. The wrapping below is
8331 only for the cases of TREE_CONSTANT argument or overflow. */
8332 r = t;
8334 if (!non_constant_p && overflow_p)
8335 non_constant_p = true;
8337 /* Unshare the result. */
8338 bool should_unshare = true;
8339 if (r == t || (TREE_CODE (t) == TARGET_EXPR
8340 && TARGET_EXPR_INITIAL (t) == r))
8341 should_unshare = false;
8343 if (non_constant_p && !allow_non_constant)
8344 return error_mark_node;
8345 else if (constexpr_dtor)
8346 return r;
8347 else if (non_constant_p && TREE_CONSTANT (r))
8348 r = mark_non_constant (r);
8349 else if (non_constant_p)
8350 return t;
8352 if (should_unshare)
8353 r = unshare_expr (r);
8355 if (TREE_CODE (r) == CONSTRUCTOR && CLASS_TYPE_P (TREE_TYPE (r)))
8357 r = adjust_temp_type (type, r);
8358 if (TREE_CODE (t) == TARGET_EXPR
8359 && TARGET_EXPR_INITIAL (t) == r)
8360 return t;
8361 else if (TREE_CODE (t) == CONSTRUCTOR || TREE_CODE (t) == CALL_EXPR)
8362 /* Don't add a TARGET_EXPR if our argument didn't have one. */;
8363 else if (TREE_CODE (t) == TARGET_EXPR && TARGET_EXPR_CLEANUP (t))
8364 r = get_target_expr (r);
8365 else
8367 r = get_target_expr (r, tf_warning_or_error | tf_no_cleanup);
8368 TREE_CONSTANT (r) = true;
8372 /* Remember the original location if that wouldn't need a wrapper. */
8373 if (location_t loc = EXPR_LOCATION (t))
8374 protected_set_expr_location (r, loc);
8376 return r;
8379 /* If T represents a constant expression returns its reduced value.
8380 Otherwise return error_mark_node. */
8382 tree
8383 cxx_constant_value (tree t, tree decl /* = NULL_TREE */,
8384 tsubst_flags_t complain /* = tf_error */)
8386 bool sfinae = !(complain & tf_error);
8387 tree r = cxx_eval_outermost_constant_expr (t, sfinae, true, true, false, decl);
8388 if (sfinae && !TREE_CONSTANT (r))
8389 r = error_mark_node;
8390 return r;
8393 /* Like cxx_constant_value, but used for evaluation of constexpr destructors
8394 of constexpr variables. The actual initializer of DECL is not modified. */
8396 void
8397 cxx_constant_dtor (tree t, tree decl)
8399 cxx_eval_outermost_constant_expr (t, false, true, true, true, decl);
8402 /* Helper routine for fold_simple function. Either return simplified
8403 expression T, otherwise NULL_TREE.
8404 In contrast to cp_fully_fold, and to maybe_constant_value, we try to fold
8405 even if we are within template-declaration. So be careful on call, as in
8406 such case types can be undefined. */
8408 static tree
8409 fold_simple_1 (tree t)
8411 tree op1;
8412 enum tree_code code = TREE_CODE (t);
8414 switch (code)
8416 case INTEGER_CST:
8417 case REAL_CST:
8418 case VECTOR_CST:
8419 case FIXED_CST:
8420 case COMPLEX_CST:
8421 return t;
8423 case SIZEOF_EXPR:
8424 return fold_sizeof_expr (t);
8426 case ABS_EXPR:
8427 case ABSU_EXPR:
8428 case CONJ_EXPR:
8429 case REALPART_EXPR:
8430 case IMAGPART_EXPR:
8431 case NEGATE_EXPR:
8432 case BIT_NOT_EXPR:
8433 case TRUTH_NOT_EXPR:
8434 case VIEW_CONVERT_EXPR:
8435 CASE_CONVERT:
8436 case FLOAT_EXPR:
8437 case FIX_TRUNC_EXPR:
8438 case FIXED_CONVERT_EXPR:
8439 case ADDR_SPACE_CONVERT_EXPR:
8441 op1 = TREE_OPERAND (t, 0);
8443 t = const_unop (code, TREE_TYPE (t), op1);
8444 if (!t)
8445 return NULL_TREE;
8447 if (CONVERT_EXPR_CODE_P (code)
8448 && TREE_OVERFLOW_P (t) && !TREE_OVERFLOW_P (op1))
8449 TREE_OVERFLOW (t) = false;
8450 return t;
8452 default:
8453 return NULL_TREE;
8457 /* If T is a simple constant expression, returns its simplified value.
8458 Otherwise returns T. In contrast to maybe_constant_value we
8459 simplify only few operations on constant-expressions, and we don't
8460 try to simplify constexpressions. */
8462 tree
8463 fold_simple (tree t)
8465 if (processing_template_decl)
8466 return t;
8468 tree r = fold_simple_1 (t);
8469 if (r)
8470 return r;
8472 return t;
8475 /* If T is a constant expression, returns its reduced value.
8476 Otherwise, if T does not have TREE_CONSTANT set, returns T.
8477 Otherwise, returns a version of T without TREE_CONSTANT.
8478 MANIFESTLY_CONST_EVAL is true if T is manifestly const-evaluated
8479 as per P0595. */
8481 static GTY((deletable)) hash_map<tree, tree> *cv_cache;
8483 tree
8484 maybe_constant_value (tree t, tree decl /* = NULL_TREE */,
8485 bool manifestly_const_eval /* = false */)
8487 tree r;
8489 if (!is_nondependent_constant_expression (t))
8491 if (TREE_OVERFLOW_P (t)
8492 || (!processing_template_decl && TREE_CONSTANT (t)))
8493 t = mark_non_constant (t);
8494 return t;
8496 else if (CONSTANT_CLASS_P (t))
8497 /* No caching or evaluation needed. */
8498 return t;
8500 if (manifestly_const_eval)
8501 return cxx_eval_outermost_constant_expr (t, true, true, true, false, decl);
8503 if (cv_cache == NULL)
8504 cv_cache = hash_map<tree, tree>::create_ggc (101);
8505 if (tree *cached = cv_cache->get (t))
8507 r = *cached;
8508 if (r != t)
8510 r = break_out_target_exprs (r, /*clear_loc*/true);
8511 protected_set_expr_location (r, EXPR_LOCATION (t));
8513 return r;
8516 /* Don't evaluate an unevaluated operand. */
8517 if (cp_unevaluated_operand)
8518 return t;
8520 uid_sensitive_constexpr_evaluation_checker c;
8521 r = cxx_eval_outermost_constant_expr (t, true, true, false, false, decl);
8522 gcc_checking_assert (r == t
8523 || CONVERT_EXPR_P (t)
8524 || TREE_CODE (t) == VIEW_CONVERT_EXPR
8525 || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
8526 || !cp_tree_equal (r, t));
8527 if (!c.evaluation_restricted_p ())
8528 cv_cache->put (t, r);
8529 return r;
8532 /* Dispose of the whole CV_CACHE. */
8534 static void
8535 clear_cv_cache (void)
8537 if (cv_cache != NULL)
8538 cv_cache->empty ();
8541 /* Dispose of the whole CV_CACHE and FOLD_CACHE. */
8543 void
8544 clear_cv_and_fold_caches ()
8546 clear_cv_cache ();
8547 clear_fold_cache ();
8550 /* Internal function handling expressions in templates for
8551 fold_non_dependent_expr and fold_non_dependent_init.
8553 If we're in a template, but T isn't value dependent, simplify
8554 it. We're supposed to treat:
8556 template <typename T> void f(T[1 + 1]);
8557 template <typename T> void f(T[2]);
8559 as two declarations of the same function, for example. */
8561 static tree
8562 fold_non_dependent_expr_template (tree t, tsubst_flags_t complain,
8563 bool manifestly_const_eval,
8564 tree object)
8566 gcc_assert (processing_template_decl);
8568 if (is_nondependent_constant_expression (t))
8570 processing_template_decl_sentinel s;
8571 t = instantiate_non_dependent_expr_internal (t, complain);
8573 if (type_unknown_p (t) || BRACE_ENCLOSED_INITIALIZER_P (t))
8575 if (TREE_OVERFLOW_P (t))
8577 t = build_nop (TREE_TYPE (t), t);
8578 TREE_CONSTANT (t) = false;
8580 return t;
8583 if (cp_unevaluated_operand && !manifestly_const_eval)
8584 return t;
8586 tree r = cxx_eval_outermost_constant_expr (t, true, true,
8587 manifestly_const_eval,
8588 false, object);
8589 /* cp_tree_equal looks through NOPs, so allow them. */
8590 gcc_checking_assert (r == t
8591 || CONVERT_EXPR_P (t)
8592 || TREE_CODE (t) == VIEW_CONVERT_EXPR
8593 || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
8594 || !cp_tree_equal (r, t));
8595 return r;
8597 else if (TREE_OVERFLOW_P (t))
8599 t = build_nop (TREE_TYPE (t), t);
8600 TREE_CONSTANT (t) = false;
8603 return t;
8606 /* Like maybe_constant_value but first fully instantiate the argument.
8608 Note: this is equivalent to instantiate_non_dependent_expr (t, complain)
8609 followed by maybe_constant_value but is more efficient,
8610 because it calls instantiation_dependent_expression_p and
8611 potential_constant_expression at most once.
8612 The manifestly_const_eval argument is passed to maybe_constant_value.
8614 Callers should generally pass their active complain, or if they are in a
8615 non-template, diagnosing context, they can use the default of
8616 tf_warning_or_error. Callers that might be within a template context, don't
8617 have a complain parameter, and aren't going to remember the result for long
8618 (e.g. null_ptr_cst_p), can pass tf_none and deal with error_mark_node
8619 appropriately. */
8621 tree
8622 fold_non_dependent_expr (tree t,
8623 tsubst_flags_t complain /* = tf_warning_or_error */,
8624 bool manifestly_const_eval /* = false */,
8625 tree object /* = NULL_TREE */)
8627 if (t == NULL_TREE)
8628 return NULL_TREE;
8630 if (processing_template_decl)
8631 return fold_non_dependent_expr_template (t, complain,
8632 manifestly_const_eval, object);
8634 return maybe_constant_value (t, object, manifestly_const_eval);
8637 /* Like fold_non_dependent_expr, but if EXPR couldn't be folded to a constant,
8638 return the original expression. */
8640 tree
8641 maybe_fold_non_dependent_expr (tree expr,
8642 tsubst_flags_t complain/*=tf_warning_or_error*/)
8644 tree t = fold_non_dependent_expr (expr, complain);
8645 if (t && TREE_CONSTANT (t))
8646 return t;
8648 return expr;
8651 /* Like maybe_constant_init but first fully instantiate the argument. */
8653 tree
8654 fold_non_dependent_init (tree t,
8655 tsubst_flags_t complain /*=tf_warning_or_error*/,
8656 bool manifestly_const_eval /*=false*/,
8657 tree object /* = NULL_TREE */)
8659 if (t == NULL_TREE)
8660 return NULL_TREE;
8662 if (processing_template_decl)
8664 t = fold_non_dependent_expr_template (t, complain,
8665 manifestly_const_eval, object);
8666 /* maybe_constant_init does this stripping, so do it here too. */
8667 if (TREE_CODE (t) == TARGET_EXPR)
8669 tree init = TARGET_EXPR_INITIAL (t);
8670 if (TREE_CODE (init) == CONSTRUCTOR)
8671 t = init;
8673 return t;
8676 return maybe_constant_init (t, object, manifestly_const_eval);
8679 /* Like maybe_constant_value, but returns a CONSTRUCTOR directly, rather
8680 than wrapped in a TARGET_EXPR.
8681 ALLOW_NON_CONSTANT is false if T is required to be a constant expression.
8682 MANIFESTLY_CONST_EVAL is true if T is manifestly const-evaluated as
8683 per P0595 even when ALLOW_NON_CONSTANT is true. */
8685 static tree
8686 maybe_constant_init_1 (tree t, tree decl, bool allow_non_constant,
8687 bool manifestly_const_eval)
8689 if (!t)
8690 return t;
8691 if (TREE_CODE (t) == EXPR_STMT)
8692 t = TREE_OPERAND (t, 0);
8693 if (TREE_CODE (t) == CONVERT_EXPR
8694 && VOID_TYPE_P (TREE_TYPE (t)))
8695 t = TREE_OPERAND (t, 0);
8696 if (TREE_CODE (t) == INIT_EXPR)
8697 t = TREE_OPERAND (t, 1);
8698 if (TREE_CODE (t) == TARGET_EXPR)
8699 t = TARGET_EXPR_INITIAL (t);
8700 if (!is_nondependent_static_init_expression (t))
8701 /* Don't try to evaluate it. */;
8702 else if (CONSTANT_CLASS_P (t) && allow_non_constant)
8703 /* No evaluation needed. */;
8704 else
8706 /* [basic.start.static] allows constant-initialization of variables with
8707 static or thread storage duration even if it isn't required, but we
8708 shouldn't bend the rules the same way for automatic variables. */
8709 bool is_static = (decl && DECL_P (decl)
8710 && (TREE_STATIC (decl) || DECL_EXTERNAL (decl)));
8711 t = cxx_eval_outermost_constant_expr (t, allow_non_constant, !is_static,
8712 manifestly_const_eval, false, decl);
8714 if (TREE_CODE (t) == TARGET_EXPR)
8716 tree init = TARGET_EXPR_INITIAL (t);
8717 if (TREE_CODE (init) == CONSTRUCTOR)
8718 t = init;
8720 return t;
8723 /* Wrapper for maybe_constant_init_1 which permits non constants. */
8725 tree
8726 maybe_constant_init (tree t, tree decl, bool manifestly_const_eval)
8728 return maybe_constant_init_1 (t, decl, true, manifestly_const_eval);
8731 /* Wrapper for maybe_constant_init_1 which does not permit non constants. */
8733 tree
8734 cxx_constant_init (tree t, tree decl)
8736 return maybe_constant_init_1 (t, decl, false, true);
8739 #if 0
8740 /* FIXME see ADDR_EXPR section in potential_constant_expression_1. */
8741 /* Return true if the object referred to by REF has automatic or thread
8742 local storage. */
8744 enum { ck_ok, ck_bad, ck_unknown };
8745 static int
8746 check_automatic_or_tls (tree ref)
8748 machine_mode mode;
8749 poly_int64 bitsize, bitpos;
8750 tree offset;
8751 int volatilep = 0, unsignedp = 0;
8752 tree decl = get_inner_reference (ref, &bitsize, &bitpos, &offset,
8753 &mode, &unsignedp, &volatilep, false);
8754 duration_kind dk;
8756 /* If there isn't a decl in the middle, we don't know the linkage here,
8757 and this isn't a constant expression anyway. */
8758 if (!DECL_P (decl))
8759 return ck_unknown;
8760 dk = decl_storage_duration (decl);
8761 return (dk == dk_auto || dk == dk_thread) ? ck_bad : ck_ok;
8763 #endif
8765 /* Data structure for passing data from potential_constant_expression_1
8766 to check_for_return_continue via cp_walk_tree. */
8767 struct check_for_return_continue_data {
8768 hash_set<tree> *pset;
8769 tree continue_stmt;
8770 tree break_stmt;
8773 /* Helper function for potential_constant_expression_1 SWITCH_STMT handling,
8774 called through cp_walk_tree. Return the first RETURN_EXPR found, or note
8775 the first CONTINUE_STMT and/or BREAK_STMT if RETURN_EXPR is not found. */
8776 static tree
8777 check_for_return_continue (tree *tp, int *walk_subtrees, void *data)
8779 tree t = *tp, s, b;
8780 check_for_return_continue_data *d = (check_for_return_continue_data *) data;
8781 switch (TREE_CODE (t))
8783 case RETURN_EXPR:
8784 return t;
8786 case CONTINUE_STMT:
8787 if (d->continue_stmt == NULL_TREE)
8788 d->continue_stmt = t;
8789 break;
8791 case BREAK_STMT:
8792 if (d->break_stmt == NULL_TREE)
8793 d->break_stmt = t;
8794 break;
8796 #define RECUR(x) \
8797 if (tree r = cp_walk_tree (&x, check_for_return_continue, data, \
8798 d->pset)) \
8799 return r
8801 /* For loops, walk subtrees manually, so that continue stmts found
8802 inside of the bodies of the loops are ignored. */
8803 case DO_STMT:
8804 *walk_subtrees = 0;
8805 RECUR (DO_COND (t));
8806 s = d->continue_stmt;
8807 b = d->break_stmt;
8808 RECUR (DO_BODY (t));
8809 d->continue_stmt = s;
8810 d->break_stmt = b;
8811 break;
8813 case WHILE_STMT:
8814 *walk_subtrees = 0;
8815 RECUR (WHILE_COND (t));
8816 s = d->continue_stmt;
8817 b = d->break_stmt;
8818 RECUR (WHILE_BODY (t));
8819 d->continue_stmt = s;
8820 d->break_stmt = b;
8821 break;
8823 case FOR_STMT:
8824 *walk_subtrees = 0;
8825 RECUR (FOR_INIT_STMT (t));
8826 RECUR (FOR_COND (t));
8827 RECUR (FOR_EXPR (t));
8828 s = d->continue_stmt;
8829 b = d->break_stmt;
8830 RECUR (FOR_BODY (t));
8831 d->continue_stmt = s;
8832 d->break_stmt = b;
8833 break;
8835 case RANGE_FOR_STMT:
8836 *walk_subtrees = 0;
8837 RECUR (RANGE_FOR_EXPR (t));
8838 s = d->continue_stmt;
8839 b = d->break_stmt;
8840 RECUR (RANGE_FOR_BODY (t));
8841 d->continue_stmt = s;
8842 d->break_stmt = b;
8843 break;
8845 case SWITCH_STMT:
8846 *walk_subtrees = 0;
8847 RECUR (SWITCH_STMT_COND (t));
8848 b = d->break_stmt;
8849 RECUR (SWITCH_STMT_BODY (t));
8850 d->break_stmt = b;
8851 break;
8852 #undef RECUR
8854 case STATEMENT_LIST:
8855 case CONSTRUCTOR:
8856 break;
8858 default:
8859 if (!EXPR_P (t))
8860 *walk_subtrees = 0;
8861 break;
8864 return NULL_TREE;
8867 /* Return true if T denotes a potentially constant expression. Issue
8868 diagnostic as appropriate under control of FLAGS. If WANT_RVAL is true,
8869 an lvalue-rvalue conversion is implied. If NOW is true, we want to
8870 consider the expression in the current context, independent of constexpr
8871 substitution. If FUNDEF_P is true, we're checking a constexpr function body
8872 and hard errors should not be reported by constexpr_error.
8874 C++0x [expr.const] used to say
8876 6 An expression is a potential constant expression if it is
8877 a constant expression where all occurrences of function
8878 parameters are replaced by arbitrary constant expressions
8879 of the appropriate type.
8881 2 A conditional expression is a constant expression unless it
8882 involves one of the following as a potentially evaluated
8883 subexpression (3.2), but subexpressions of logical AND (5.14),
8884 logical OR (5.15), and conditional (5.16) operations that are
8885 not evaluated are not considered. */
8887 static bool
8888 potential_constant_expression_1 (tree t, bool want_rval, bool strict, bool now,
8889 bool fundef_p, tsubst_flags_t flags,
8890 tree *jump_target)
8892 #define RECUR(T,RV) \
8893 potential_constant_expression_1 ((T), (RV), strict, now, fundef_p, flags, \
8894 jump_target)
8896 enum { any = false, rval = true };
8897 int i;
8898 tree tmp;
8900 if (t == error_mark_node)
8901 return false;
8902 if (t == NULL_TREE)
8903 return true;
8904 location_t loc = cp_expr_loc_or_input_loc (t);
8906 if (*jump_target)
8907 /* If we are jumping, ignore everything. This is simpler than the
8908 cxx_eval_constant_expression handling because we only need to be
8909 conservatively correct, and we don't necessarily have a constant value
8910 available, so we don't bother with switch tracking. */
8911 return true;
8913 if (TREE_THIS_VOLATILE (t) && want_rval)
8915 if (flags & tf_error)
8916 constexpr_error (loc, fundef_p, "lvalue-to-rvalue conversion of "
8917 "a volatile lvalue %qE with type %qT", t,
8918 TREE_TYPE (t));
8919 return false;
8921 if (CONSTANT_CLASS_P (t))
8922 return true;
8923 if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_TYPED)
8924 && TREE_TYPE (t) == error_mark_node)
8925 return false;
8927 switch (TREE_CODE (t))
8929 case FUNCTION_DECL:
8930 case BASELINK:
8931 case TEMPLATE_DECL:
8932 case OVERLOAD:
8933 case TEMPLATE_ID_EXPR:
8934 case LABEL_DECL:
8935 case CASE_LABEL_EXPR:
8936 case PREDICT_EXPR:
8937 case CONST_DECL:
8938 case SIZEOF_EXPR:
8939 case ALIGNOF_EXPR:
8940 case OFFSETOF_EXPR:
8941 case NOEXCEPT_EXPR:
8942 case TEMPLATE_PARM_INDEX:
8943 case TRAIT_EXPR:
8944 case IDENTIFIER_NODE:
8945 case USERDEF_LITERAL:
8946 /* We can see a FIELD_DECL in a pointer-to-member expression. */
8947 case FIELD_DECL:
8948 case RESULT_DECL:
8949 case USING_DECL:
8950 case USING_STMT:
8951 case PLACEHOLDER_EXPR:
8952 case REQUIRES_EXPR:
8953 case STATIC_ASSERT:
8954 case DEBUG_BEGIN_STMT:
8955 return true;
8957 case RETURN_EXPR:
8958 if (!RECUR (TREE_OPERAND (t, 0), any))
8959 return false;
8960 /* FALLTHROUGH */
8962 case BREAK_STMT:
8963 case CONTINUE_STMT:
8964 *jump_target = t;
8965 return true;
8967 case PARM_DECL:
8968 if (now && want_rval)
8970 tree type = TREE_TYPE (t);
8971 if ((processing_template_decl && !COMPLETE_TYPE_P (type))
8972 || dependent_type_p (type)
8973 || is_really_empty_class (type, /*ignore_vptr*/false))
8974 /* An empty class has no data to read. */
8975 return true;
8976 if (flags & tf_error)
8977 constexpr_error (input_location, fundef_p,
8978 "%qE is not a constant expression", t);
8979 return false;
8981 return true;
8983 case AGGR_INIT_EXPR:
8984 case CALL_EXPR:
8985 /* -- an invocation of a function other than a constexpr function
8986 or a constexpr constructor. */
8988 tree fun = get_function_named_in_call (t);
8989 const int nargs = call_expr_nargs (t);
8990 i = 0;
8992 if (fun == NULL_TREE)
8994 /* Reset to allow the function to continue past the end
8995 of the block below. Otherwise return early. */
8996 bool bail = true;
8998 if (TREE_CODE (t) == CALL_EXPR
8999 && CALL_EXPR_FN (t) == NULL_TREE)
9000 switch (CALL_EXPR_IFN (t))
9002 /* These should be ignored, they are optimized away from
9003 constexpr functions. */
9004 case IFN_UBSAN_NULL:
9005 case IFN_UBSAN_BOUNDS:
9006 case IFN_UBSAN_VPTR:
9007 case IFN_FALLTHROUGH:
9008 case IFN_ASSUME:
9009 return true;
9011 case IFN_ADD_OVERFLOW:
9012 case IFN_SUB_OVERFLOW:
9013 case IFN_MUL_OVERFLOW:
9014 case IFN_LAUNDER:
9015 case IFN_VEC_CONVERT:
9016 bail = false;
9017 break;
9019 default:
9020 break;
9023 if (bail)
9025 /* fold_call_expr can't do anything with IFN calls. */
9026 if (flags & tf_error)
9027 constexpr_error (loc, fundef_p,
9028 "call to internal function %qE", t);
9029 return false;
9033 if (fun && is_overloaded_fn (fun))
9035 if (TREE_CODE (fun) == FUNCTION_DECL)
9037 if (builtin_valid_in_constant_expr_p (fun))
9038 return true;
9039 if (!maybe_constexpr_fn (fun)
9040 /* Allow any built-in function; if the expansion
9041 isn't constant, we'll deal with that then. */
9042 && !fndecl_built_in_p (fun)
9043 /* In C++20, replaceable global allocation functions
9044 are constant expressions. */
9045 && (!cxx_replaceable_global_alloc_fn (fun)
9046 || TREE_CODE (t) != CALL_EXPR
9047 || (!CALL_FROM_NEW_OR_DELETE_P (t)
9048 && (current_function_decl == NULL_TREE
9049 || !is_std_allocator_allocate
9050 (current_function_decl))))
9051 /* Allow placement new in std::construct_at. */
9052 && (!cxx_placement_new_fn (fun)
9053 || TREE_CODE (t) != CALL_EXPR
9054 || current_function_decl == NULL_TREE
9055 || !is_std_construct_at (current_function_decl))
9056 && !cxx_dynamic_cast_fn_p (fun))
9058 if ((flags & tf_error)
9059 && constexpr_error (loc, fundef_p,
9060 "call to non-%<constexpr%> "
9061 "function %qD", fun))
9062 explain_invalid_constexpr_fn (fun);
9063 return false;
9065 /* A call to a non-static member function takes the address
9066 of the object as the first argument. But in a constant
9067 expression the address will be folded away, so look
9068 through it now. */
9069 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fun)
9070 && !DECL_CONSTRUCTOR_P (fun))
9072 tree x = get_nth_callarg (t, 0);
9073 if (is_this_parameter (x))
9074 return true;
9075 /* Don't require an immediately constant value, as
9076 constexpr substitution might not use the value. */
9077 bool sub_now = false;
9078 if (!potential_constant_expression_1 (x, rval, strict,
9079 sub_now, fundef_p,
9080 flags, jump_target))
9081 return false;
9082 i = 1;
9085 else
9087 if (!RECUR (fun, true))
9088 return false;
9089 fun = get_first_fn (fun);
9091 /* Skip initial arguments to base constructors. */
9092 if (DECL_BASE_CONSTRUCTOR_P (fun))
9093 i = num_artificial_parms_for (fun);
9094 fun = DECL_ORIGIN (fun);
9096 else if (fun)
9098 if (RECUR (fun, rval))
9099 /* Might end up being a constant function pointer. */;
9100 else
9101 return false;
9103 for (; i < nargs; ++i)
9105 tree x = get_nth_callarg (t, i);
9106 /* In a template, reference arguments haven't been converted to
9107 REFERENCE_TYPE and we might not even know if the parameter
9108 is a reference, so accept lvalue constants too. */
9109 bool rv = processing_template_decl ? any : rval;
9110 /* Don't require an immediately constant value, as constexpr
9111 substitution might not use the value of the argument. */
9112 bool sub_now = false;
9113 if (!potential_constant_expression_1 (x, rv, strict,
9114 sub_now, fundef_p, flags,
9115 jump_target))
9116 return false;
9118 return true;
9121 case NON_LVALUE_EXPR:
9122 /* -- an lvalue-to-rvalue conversion (4.1) unless it is applied to
9123 -- an lvalue of integral type that refers to a non-volatile
9124 const variable or static data member initialized with
9125 constant expressions, or
9127 -- an lvalue of literal type that refers to non-volatile
9128 object defined with constexpr, or that refers to a
9129 sub-object of such an object; */
9130 return RECUR (TREE_OPERAND (t, 0), rval);
9132 case EXCESS_PRECISION_EXPR:
9133 return RECUR (TREE_OPERAND (t, 0), rval);
9135 case VAR_DECL:
9136 if (DECL_HAS_VALUE_EXPR_P (t))
9138 if (now && is_normal_capture_proxy (t))
9140 /* -- in a lambda-expression, a reference to this or to a
9141 variable with automatic storage duration defined outside that
9142 lambda-expression, where the reference would be an
9143 odr-use. */
9145 if (want_rval)
9146 /* Since we're doing an lvalue-rvalue conversion, this might
9147 not be an odr-use, so evaluate the variable directly. */
9148 return RECUR (DECL_CAPTURED_VARIABLE (t), rval);
9150 if (flags & tf_error)
9152 tree cap = DECL_CAPTURED_VARIABLE (t);
9153 if (constexpr_error (input_location, fundef_p,
9154 "lambda capture of %qE is not a "
9155 "constant expression", cap)
9156 && decl_constant_var_p (cap))
9157 inform (input_location, "because it is used as a glvalue");
9159 return false;
9161 /* Treat __PRETTY_FUNCTION__ inside a template function as
9162 potentially-constant. */
9163 else if (DECL_PRETTY_FUNCTION_P (t)
9164 && DECL_VALUE_EXPR (t) == error_mark_node)
9165 return true;
9166 return RECUR (DECL_VALUE_EXPR (t), rval);
9168 if (want_rval
9169 && !var_in_maybe_constexpr_fn (t)
9170 && !type_dependent_expression_p (t)
9171 && !decl_maybe_constant_var_p (t)
9172 && (strict
9173 || !CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (t))
9174 || (DECL_INITIAL (t)
9175 && !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t)))
9176 && COMPLETE_TYPE_P (TREE_TYPE (t))
9177 && !is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
9179 if (flags & tf_error)
9180 non_const_var_error (loc, t, fundef_p);
9181 return false;
9183 return true;
9185 case NOP_EXPR:
9186 if (REINTERPRET_CAST_P (t))
9188 if (flags & tf_error)
9189 constexpr_error (loc, fundef_p, "%<reinterpret_cast%> is not a "
9190 "constant expression");
9191 return false;
9193 /* FALLTHRU */
9194 case CONVERT_EXPR:
9195 case VIEW_CONVERT_EXPR:
9196 /* -- a reinterpret_cast. FIXME not implemented, and this rule
9197 may change to something more specific to type-punning (DR 1312). */
9199 tree from = TREE_OPERAND (t, 0);
9200 if (location_wrapper_p (t))
9202 iloc_sentinel ils = loc;
9203 return (RECUR (from, want_rval));
9205 if (INDIRECT_TYPE_P (TREE_TYPE (t)))
9207 STRIP_ANY_LOCATION_WRAPPER (from);
9208 if (TREE_CODE (from) == INTEGER_CST
9209 && !integer_zerop (from))
9211 if (flags & tf_error)
9212 constexpr_error (loc, fundef_p,
9213 "%<reinterpret_cast%> from integer to "
9214 "pointer");
9215 return false;
9218 return (RECUR (from, TREE_CODE (t) != VIEW_CONVERT_EXPR));
9221 case ADDRESSOF_EXPR:
9222 /* This is like ADDR_EXPR, except it won't form pointer-to-member. */
9223 t = TREE_OPERAND (t, 0);
9224 goto handle_addr_expr;
9226 case ADDR_EXPR:
9227 /* -- a unary operator & that is applied to an lvalue that
9228 designates an object with thread or automatic storage
9229 duration; */
9230 t = TREE_OPERAND (t, 0);
9232 if (TREE_CODE (t) == OFFSET_REF && PTRMEM_OK_P (t))
9233 /* A pointer-to-member constant. */
9234 return true;
9236 handle_addr_expr:
9237 #if 0
9238 /* FIXME adjust when issue 1197 is fully resolved. For now don't do
9239 any checking here, as we might dereference the pointer later. If
9240 we remove this code, also remove check_automatic_or_tls. */
9241 i = check_automatic_or_tls (t);
9242 if (i == ck_ok)
9243 return true;
9244 if (i == ck_bad)
9246 if (flags & tf_error)
9247 error ("address-of an object %qE with thread local or "
9248 "automatic storage is not a constant expression", t);
9249 return false;
9251 #endif
9252 return RECUR (t, any);
9254 case COMPONENT_REF:
9255 case ARROW_EXPR:
9256 case OFFSET_REF:
9257 /* -- a class member access unless its postfix-expression is
9258 of literal type or of pointer to literal type. */
9259 /* This test would be redundant, as it follows from the
9260 postfix-expression being a potential constant expression. */
9261 if (type_unknown_p (t))
9262 return true;
9263 if (is_overloaded_fn (t))
9264 /* In a template, a COMPONENT_REF of a function expresses ob.fn(),
9265 which uses ob as an lvalue. */
9266 want_rval = false;
9267 gcc_fallthrough ();
9269 case REALPART_EXPR:
9270 case IMAGPART_EXPR:
9271 case BIT_FIELD_REF:
9272 return RECUR (TREE_OPERAND (t, 0), want_rval);
9274 case EXPR_PACK_EXPANSION:
9275 return RECUR (PACK_EXPANSION_PATTERN (t), want_rval);
9277 case INDIRECT_REF:
9279 tree x = TREE_OPERAND (t, 0);
9280 STRIP_NOPS (x);
9281 if (is_this_parameter (x) && !is_capture_proxy (x))
9283 if (!var_in_maybe_constexpr_fn (x))
9285 if (flags & tf_error)
9286 constexpr_error (loc, fundef_p, "use of %<this%> in a "
9287 "constant expression");
9288 return false;
9290 return true;
9292 return RECUR (x, rval);
9295 case STATEMENT_LIST:
9296 for (tree stmt : tsi_range (t))
9297 if (!RECUR (stmt, any))
9298 return false;
9299 return true;
9301 case MODIFY_EXPR:
9302 if (cxx_dialect < cxx14)
9303 goto fail;
9304 if (!RECUR (TREE_OPERAND (t, 0), any))
9305 return false;
9306 /* Just ignore clobbers. */
9307 if (TREE_CLOBBER_P (TREE_OPERAND (t, 1)))
9308 return true;
9309 if (!RECUR (TREE_OPERAND (t, 1), rval))
9310 return false;
9311 return true;
9313 case MODOP_EXPR:
9314 if (cxx_dialect < cxx14)
9315 goto fail;
9316 if (!RECUR (TREE_OPERAND (t, 0), rval))
9317 return false;
9318 if (!RECUR (TREE_OPERAND (t, 2), rval))
9319 return false;
9320 return true;
9322 case DO_STMT:
9323 if (!RECUR (DO_COND (t), rval))
9324 return false;
9325 if (!RECUR (DO_BODY (t), any))
9326 return false;
9327 if (breaks (jump_target) || continues (jump_target))
9328 *jump_target = NULL_TREE;
9329 return true;
9331 case FOR_STMT:
9332 if (!RECUR (FOR_INIT_STMT (t), any))
9333 return false;
9334 tmp = FOR_COND (t);
9335 if (!RECUR (tmp, rval))
9336 return false;
9337 if (tmp)
9339 if (!processing_template_decl)
9340 tmp = cxx_eval_outermost_constant_expr (tmp, true);
9341 /* If we couldn't evaluate the condition, it might not ever be
9342 true. */
9343 if (!integer_onep (tmp))
9345 /* Before returning true, check if the for body can contain
9346 a return. */
9347 hash_set<tree> pset;
9348 check_for_return_continue_data data = { &pset, NULL_TREE,
9349 NULL_TREE };
9350 if (tree ret_expr
9351 = cp_walk_tree (&FOR_BODY (t), check_for_return_continue,
9352 &data, &pset))
9353 *jump_target = ret_expr;
9354 return true;
9357 if (!RECUR (FOR_EXPR (t), any))
9358 return false;
9359 if (!RECUR (FOR_BODY (t), any))
9360 return false;
9361 if (breaks (jump_target) || continues (jump_target))
9362 *jump_target = NULL_TREE;
9363 return true;
9365 case RANGE_FOR_STMT:
9366 if (!RECUR (RANGE_FOR_INIT_STMT (t), any))
9367 return false;
9368 if (!RECUR (RANGE_FOR_EXPR (t), any))
9369 return false;
9370 if (!RECUR (RANGE_FOR_BODY (t), any))
9371 return false;
9372 if (breaks (jump_target) || continues (jump_target))
9373 *jump_target = NULL_TREE;
9374 return true;
9376 case WHILE_STMT:
9377 tmp = WHILE_COND (t);
9378 if (!RECUR (tmp, rval))
9379 return false;
9380 if (!processing_template_decl)
9381 tmp = cxx_eval_outermost_constant_expr (tmp, true);
9382 /* If we couldn't evaluate the condition, it might not ever be true. */
9383 if (!integer_onep (tmp))
9385 /* Before returning true, check if the while body can contain
9386 a return. */
9387 hash_set<tree> pset;
9388 check_for_return_continue_data data = { &pset, NULL_TREE,
9389 NULL_TREE };
9390 if (tree ret_expr
9391 = cp_walk_tree (&WHILE_BODY (t), check_for_return_continue,
9392 &data, &pset))
9393 *jump_target = ret_expr;
9394 return true;
9396 if (!RECUR (WHILE_BODY (t), any))
9397 return false;
9398 if (breaks (jump_target) || continues (jump_target))
9399 *jump_target = NULL_TREE;
9400 return true;
9402 case SWITCH_STMT:
9403 if (!RECUR (SWITCH_STMT_COND (t), rval))
9404 return false;
9405 /* FIXME we don't check SWITCH_STMT_BODY currently, because even
9406 unreachable labels would be checked and it is enough if there is
9407 a single switch cond value for which it is a valid constant
9408 expression. We need to check if there are any RETURN_EXPRs
9409 or CONTINUE_STMTs inside of the body though, as in that case
9410 we need to set *jump_target. */
9411 else
9413 hash_set<tree> pset;
9414 check_for_return_continue_data data = { &pset, NULL_TREE,
9415 NULL_TREE };
9416 if (tree ret_expr
9417 = cp_walk_tree (&SWITCH_STMT_BODY (t), check_for_return_continue,
9418 &data, &pset))
9419 /* The switch might return. */
9420 *jump_target = ret_expr;
9421 else if (data.continue_stmt)
9422 /* The switch can't return, but might continue. */
9423 *jump_target = data.continue_stmt;
9425 return true;
9427 case STMT_EXPR:
9428 return RECUR (STMT_EXPR_STMT (t), rval);
9430 case LAMBDA_EXPR:
9431 if (cxx_dialect >= cxx17)
9432 /* In C++17 lambdas can be constexpr, don't give up yet. */
9433 return true;
9434 else if (flags & tf_error)
9435 constexpr_error (loc, fundef_p, "lambda-expression is not a "
9436 "constant expression before C++17");
9437 return false;
9439 case NEW_EXPR:
9440 case VEC_NEW_EXPR:
9441 case DELETE_EXPR:
9442 case VEC_DELETE_EXPR:
9443 if (cxx_dialect >= cxx20)
9444 /* In C++20, new-expressions are potentially constant. */
9445 return true;
9446 else if (flags & tf_error)
9447 constexpr_error (loc, fundef_p, "new-expression is not a "
9448 "constant expression before C++20");
9449 return false;
9451 case DYNAMIC_CAST_EXPR:
9452 case PSEUDO_DTOR_EXPR:
9453 case THROW_EXPR:
9454 case OMP_PARALLEL:
9455 case OMP_TASK:
9456 case OMP_FOR:
9457 case OMP_SIMD:
9458 case OMP_DISTRIBUTE:
9459 case OMP_TASKLOOP:
9460 case OMP_LOOP:
9461 case OMP_TEAMS:
9462 case OMP_TARGET_DATA:
9463 case OMP_TARGET:
9464 case OMP_SECTIONS:
9465 case OMP_ORDERED:
9466 case OMP_CRITICAL:
9467 case OMP_SINGLE:
9468 case OMP_SECTION:
9469 case OMP_MASTER:
9470 case OMP_MASKED:
9471 case OMP_TASKGROUP:
9472 case OMP_TARGET_UPDATE:
9473 case OMP_TARGET_ENTER_DATA:
9474 case OMP_TARGET_EXIT_DATA:
9475 case OMP_ATOMIC:
9476 case OMP_ATOMIC_READ:
9477 case OMP_ATOMIC_CAPTURE_OLD:
9478 case OMP_ATOMIC_CAPTURE_NEW:
9479 case OMP_DEPOBJ:
9480 case OACC_PARALLEL:
9481 case OACC_KERNELS:
9482 case OACC_SERIAL:
9483 case OACC_DATA:
9484 case OACC_HOST_DATA:
9485 case OACC_LOOP:
9486 case OACC_CACHE:
9487 case OACC_DECLARE:
9488 case OACC_ENTER_DATA:
9489 case OACC_EXIT_DATA:
9490 case OACC_UPDATE:
9491 /* GCC internal stuff. */
9492 case VA_ARG_EXPR:
9493 case TRANSACTION_EXPR:
9494 case AT_ENCODE_EXPR:
9495 fail:
9496 if (flags & tf_error)
9497 constexpr_error (loc, fundef_p, "expression %qE is not a constant "
9498 "expression", t);
9499 return false;
9501 case ASM_EXPR:
9502 if (flags & tf_error)
9503 inline_asm_in_constexpr_error (loc, fundef_p);
9504 return false;
9506 case OBJ_TYPE_REF:
9507 if (cxx_dialect >= cxx20)
9508 /* In C++20 virtual calls can be constexpr, don't give up yet. */
9509 return true;
9510 else if (flags & tf_error)
9511 constexpr_error (loc, fundef_p, "virtual functions cannot be "
9512 "%<constexpr%> before C++20");
9513 return false;
9515 case TYPEID_EXPR:
9516 /* In C++20, a typeid expression whose operand is of polymorphic
9517 class type can be constexpr. */
9519 tree e = TREE_OPERAND (t, 0);
9520 if (cxx_dialect < cxx20
9521 && strict
9522 && !TYPE_P (e)
9523 && !type_dependent_expression_p (e)
9524 && TYPE_POLYMORPHIC_P (TREE_TYPE (e)))
9526 if (flags & tf_error)
9527 constexpr_error (loc, fundef_p, "%<typeid%> is not a "
9528 "constant expression because %qE is "
9529 "of polymorphic type", e);
9530 return false;
9532 return true;
9535 case POINTER_DIFF_EXPR:
9536 case MINUS_EXPR:
9537 want_rval = true;
9538 goto binary;
9540 case LT_EXPR:
9541 case LE_EXPR:
9542 case GT_EXPR:
9543 case GE_EXPR:
9544 case EQ_EXPR:
9545 case NE_EXPR:
9546 case SPACESHIP_EXPR:
9547 want_rval = true;
9548 goto binary;
9550 case PREINCREMENT_EXPR:
9551 case POSTINCREMENT_EXPR:
9552 case PREDECREMENT_EXPR:
9553 case POSTDECREMENT_EXPR:
9554 if (cxx_dialect < cxx14)
9555 goto fail;
9556 goto unary;
9558 case BIT_NOT_EXPR:
9559 /* A destructor. */
9560 if (TYPE_P (TREE_OPERAND (t, 0)))
9561 return true;
9562 /* fall through. */
9564 case CONJ_EXPR:
9565 case SAVE_EXPR:
9566 case FIX_TRUNC_EXPR:
9567 case FLOAT_EXPR:
9568 case NEGATE_EXPR:
9569 case ABS_EXPR:
9570 case ABSU_EXPR:
9571 case TRUTH_NOT_EXPR:
9572 case FIXED_CONVERT_EXPR:
9573 case UNARY_PLUS_EXPR:
9574 case UNARY_LEFT_FOLD_EXPR:
9575 case UNARY_RIGHT_FOLD_EXPR:
9576 unary:
9577 return RECUR (TREE_OPERAND (t, 0), rval);
9579 case CAST_EXPR:
9580 case CONST_CAST_EXPR:
9581 case STATIC_CAST_EXPR:
9582 case REINTERPRET_CAST_EXPR:
9583 case IMPLICIT_CONV_EXPR:
9584 if (!cast_valid_in_integral_constant_expression_p (TREE_TYPE (t)))
9585 /* In C++98, a conversion to non-integral type can't be part of a
9586 constant expression. */
9588 if (flags & tf_error)
9589 constexpr_error (loc, fundef_p,
9590 "cast to non-integral type %qT in a constant "
9591 "expression", TREE_TYPE (t));
9592 return false;
9594 /* This might be a conversion from a class to a (potentially) literal
9595 type. Let's consider it potentially constant since the conversion
9596 might be a constexpr user-defined conversion. */
9597 else if (cxx_dialect >= cxx11
9598 && (dependent_type_p (TREE_TYPE (t))
9599 || !COMPLETE_TYPE_P (TREE_TYPE (t))
9600 || literal_type_p (TREE_TYPE (t)))
9601 && TREE_OPERAND (t, 0))
9603 tree type = TREE_TYPE (TREE_OPERAND (t, 0));
9604 /* If this is a dependent type, it could end up being a class
9605 with conversions. */
9606 if (type == NULL_TREE || WILDCARD_TYPE_P (type))
9607 return true;
9608 /* Or a non-dependent class which has conversions. */
9609 else if (CLASS_TYPE_P (type)
9610 && (TYPE_HAS_CONVERSION (type) || dependent_scope_p (type)))
9611 return true;
9614 return (RECUR (TREE_OPERAND (t, 0),
9615 !TYPE_REF_P (TREE_TYPE (t))));
9617 case BIND_EXPR:
9618 return RECUR (BIND_EXPR_BODY (t), want_rval);
9620 case NON_DEPENDENT_EXPR:
9621 /* Treat NON_DEPENDENT_EXPR as non-constant: it's not handled by
9622 constexpr evaluation or tsubst, so fold_non_dependent_expr can't
9623 do anything useful with it. And we shouldn't see it in a context
9624 where a constant expression is strictly required, hence the assert. */
9625 gcc_checking_assert (!(flags & tf_error));
9626 return false;
9628 case CLEANUP_POINT_EXPR:
9629 case MUST_NOT_THROW_EXPR:
9630 case TRY_CATCH_EXPR:
9631 case TRY_BLOCK:
9632 case EH_SPEC_BLOCK:
9633 case EXPR_STMT:
9634 case PAREN_EXPR:
9635 /* For convenience. */
9636 case LOOP_EXPR:
9637 case EXIT_EXPR:
9638 return RECUR (TREE_OPERAND (t, 0), want_rval);
9640 case DECL_EXPR:
9641 tmp = DECL_EXPR_DECL (t);
9642 if (VAR_P (tmp) && !DECL_ARTIFICIAL (tmp)
9643 && (processing_template_decl
9644 ? !decl_maybe_constant_var_p (tmp)
9645 : !decl_constant_var_p (tmp)))
9647 if (CP_DECL_THREAD_LOCAL_P (tmp) && !DECL_REALLY_EXTERN (tmp))
9649 if (flags & tf_error)
9650 constexpr_error (DECL_SOURCE_LOCATION (tmp), fundef_p,
9651 "%qD defined %<thread_local%> in "
9652 "%<constexpr%> context", tmp);
9653 return false;
9655 else if (TREE_STATIC (tmp))
9657 if (flags & tf_error)
9658 constexpr_error (DECL_SOURCE_LOCATION (tmp), fundef_p,
9659 "%qD defined %<static%> in %<constexpr%> "
9660 "context", tmp);
9661 return false;
9663 else if (!check_for_uninitialized_const_var
9664 (tmp, /*constexpr_context_p=*/true, flags))
9665 return false;
9667 return RECUR (DECL_INITIAL (tmp), want_rval);
9669 case TRY_FINALLY_EXPR:
9670 return (RECUR (TREE_OPERAND (t, 0), want_rval)
9671 && RECUR (TREE_OPERAND (t, 1), any));
9673 case SCOPE_REF:
9674 return RECUR (TREE_OPERAND (t, 1), want_rval);
9676 case TARGET_EXPR:
9677 if (!TARGET_EXPR_DIRECT_INIT_P (t)
9678 && !literal_type_p (TREE_TYPE (t)))
9680 if (flags & tf_error)
9682 auto_diagnostic_group d;
9683 if (constexpr_error (loc, fundef_p,
9684 "temporary of non-literal type %qT in a "
9685 "constant expression", TREE_TYPE (t)))
9686 explain_non_literal_class (TREE_TYPE (t));
9688 return false;
9690 /* FALLTHRU */
9691 case INIT_EXPR:
9692 return RECUR (TREE_OPERAND (t, 1), rval);
9694 case CONSTRUCTOR:
9696 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
9697 constructor_elt *ce;
9698 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
9699 if (!RECUR (ce->value, want_rval))
9700 return false;
9701 return true;
9704 case TREE_LIST:
9706 gcc_assert (TREE_PURPOSE (t) == NULL_TREE
9707 || DECL_P (TREE_PURPOSE (t)));
9708 if (!RECUR (TREE_VALUE (t), want_rval))
9709 return false;
9710 if (TREE_CHAIN (t) == NULL_TREE)
9711 return true;
9712 return RECUR (TREE_CHAIN (t), want_rval);
9715 case TRUNC_DIV_EXPR:
9716 case CEIL_DIV_EXPR:
9717 case FLOOR_DIV_EXPR:
9718 case ROUND_DIV_EXPR:
9719 case TRUNC_MOD_EXPR:
9720 case CEIL_MOD_EXPR:
9721 case ROUND_MOD_EXPR:
9723 tree denom = TREE_OPERAND (t, 1);
9724 if (!RECUR (denom, rval))
9725 return false;
9726 /* We can't call cxx_eval_outermost_constant_expr on an expression
9727 that hasn't been through instantiate_non_dependent_expr yet. */
9728 if (!processing_template_decl)
9729 denom = cxx_eval_outermost_constant_expr (denom, true);
9730 if (integer_zerop (denom))
9732 if (flags & tf_error)
9733 constexpr_error (input_location, fundef_p,
9734 "division by zero is not a constant expression");
9735 return false;
9737 else
9739 want_rval = true;
9740 return RECUR (TREE_OPERAND (t, 0), want_rval);
9744 case COMPOUND_EXPR:
9746 /* check_return_expr sometimes wraps a TARGET_EXPR in a
9747 COMPOUND_EXPR; don't get confused. */
9748 tree op0 = TREE_OPERAND (t, 0);
9749 tree op1 = TREE_OPERAND (t, 1);
9750 STRIP_NOPS (op1);
9751 if (TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
9752 return RECUR (op0, want_rval);
9753 else
9754 goto binary;
9757 /* If the first operand is the non-short-circuit constant, look at
9758 the second operand; otherwise we only care about the first one for
9759 potentiality. */
9760 case TRUTH_AND_EXPR:
9761 case TRUTH_ANDIF_EXPR:
9762 tmp = boolean_true_node;
9763 goto truth;
9764 case TRUTH_OR_EXPR:
9765 case TRUTH_ORIF_EXPR:
9766 tmp = boolean_false_node;
9767 truth:
9769 tree op0 = TREE_OPERAND (t, 0);
9770 tree op1 = TREE_OPERAND (t, 1);
9771 if (!RECUR (op0, rval))
9772 return false;
9773 if (!(flags & tf_error) && RECUR (op1, rval))
9774 /* When quiet, try to avoid expensive trial evaluation by first
9775 checking potentiality of the second operand. */
9776 return true;
9777 if (!processing_template_decl)
9778 op0 = cxx_eval_outermost_constant_expr (op0, true);
9779 if (tree_int_cst_equal (op0, tmp))
9780 return (flags & tf_error) ? RECUR (op1, rval) : false;
9781 else
9782 return true;
9785 case PLUS_EXPR:
9786 case MULT_EXPR:
9787 case POINTER_PLUS_EXPR:
9788 case RDIV_EXPR:
9789 case EXACT_DIV_EXPR:
9790 case MIN_EXPR:
9791 case MAX_EXPR:
9792 case LSHIFT_EXPR:
9793 case RSHIFT_EXPR:
9794 case LROTATE_EXPR:
9795 case RROTATE_EXPR:
9796 case BIT_IOR_EXPR:
9797 case BIT_XOR_EXPR:
9798 case BIT_AND_EXPR:
9799 case TRUTH_XOR_EXPR:
9800 case UNORDERED_EXPR:
9801 case ORDERED_EXPR:
9802 case UNLT_EXPR:
9803 case UNLE_EXPR:
9804 case UNGT_EXPR:
9805 case UNGE_EXPR:
9806 case UNEQ_EXPR:
9807 case LTGT_EXPR:
9808 case RANGE_EXPR:
9809 case COMPLEX_EXPR:
9810 want_rval = true;
9811 /* Fall through. */
9812 case ARRAY_REF:
9813 case ARRAY_RANGE_REF:
9814 case MEMBER_REF:
9815 case DOTSTAR_EXPR:
9816 case MEM_REF:
9817 case BINARY_LEFT_FOLD_EXPR:
9818 case BINARY_RIGHT_FOLD_EXPR:
9819 binary:
9820 for (i = 0; i < 2; ++i)
9821 if (!RECUR (TREE_OPERAND (t, i), want_rval))
9822 return false;
9823 return true;
9825 case VEC_PERM_EXPR:
9826 for (i = 0; i < 3; ++i)
9827 if (!RECUR (TREE_OPERAND (t, i), true))
9828 return false;
9829 return true;
9831 case COND_EXPR:
9832 if (COND_EXPR_IS_VEC_DELETE (t) && cxx_dialect < cxx20)
9834 if (flags & tf_error)
9835 constexpr_error (loc, fundef_p, "%<delete[]%> is not a "
9836 "constant expression");
9837 return false;
9839 /* Fall through. */
9840 case IF_STMT:
9841 case VEC_COND_EXPR:
9842 /* If the condition is a known constant, we know which of the legs we
9843 care about; otherwise we only require that the condition and
9844 either of the legs be potentially constant. */
9845 tmp = TREE_OPERAND (t, 0);
9846 if (!RECUR (tmp, rval))
9847 return false;
9848 if (!processing_template_decl)
9849 tmp = cxx_eval_outermost_constant_expr (tmp, true);
9850 /* potential_constant_expression* isn't told if it is called for
9851 manifestly_const_eval or not, so for consteval if always
9852 process both branches as if the condition is not a known
9853 constant. */
9854 if (TREE_CODE (t) != IF_STMT || !IF_STMT_CONSTEVAL_P (t))
9856 if (integer_zerop (tmp))
9857 return RECUR (TREE_OPERAND (t, 2), want_rval);
9858 else if (TREE_CODE (tmp) == INTEGER_CST)
9859 return RECUR (TREE_OPERAND (t, 1), want_rval);
9861 tmp = *jump_target;
9862 for (i = 1; i < 3; ++i)
9864 tree this_jump_target = tmp;
9865 if (potential_constant_expression_1 (TREE_OPERAND (t, i),
9866 want_rval, strict, now, fundef_p,
9867 tf_none, &this_jump_target))
9869 if (returns (&this_jump_target))
9870 *jump_target = this_jump_target;
9871 else if (!returns (jump_target))
9873 if (breaks (&this_jump_target)
9874 || continues (&this_jump_target))
9875 *jump_target = this_jump_target;
9876 if (i == 1)
9878 /* If the then branch is potentially constant, but
9879 does not return, check if the else branch
9880 couldn't return, break or continue. */
9881 hash_set<tree> pset;
9882 check_for_return_continue_data data = { &pset, NULL_TREE,
9883 NULL_TREE };
9884 if (tree ret_expr
9885 = cp_walk_tree (&TREE_OPERAND (t, 2),
9886 check_for_return_continue, &data,
9887 &pset))
9888 *jump_target = ret_expr;
9889 else if (*jump_target == NULL_TREE)
9891 if (data.continue_stmt)
9892 *jump_target = data.continue_stmt;
9893 else if (data.break_stmt)
9894 *jump_target = data.break_stmt;
9898 return true;
9901 if (flags & tf_error)
9903 if (TREE_CODE (t) == IF_STMT)
9904 constexpr_error (loc, fundef_p, "neither branch of %<if%> is a "
9905 "constant expression");
9906 else
9907 constexpr_error (loc, fundef_p, "expression %qE is not a "
9908 "constant expression", t);
9910 return false;
9912 case VEC_INIT_EXPR:
9913 if (VEC_INIT_EXPR_IS_CONSTEXPR (t))
9914 return true;
9915 if (flags & tf_error)
9917 if (constexpr_error (loc, fundef_p, "non-constant array "
9918 "initialization"))
9919 diagnose_non_constexpr_vec_init (t);
9921 return false;
9923 case TYPE_DECL:
9924 case TAG_DEFN:
9925 /* We can see these in statement-expressions. */
9926 return true;
9928 case CLEANUP_STMT:
9929 if (!RECUR (CLEANUP_BODY (t), any))
9930 return false;
9931 if (!CLEANUP_EH_ONLY (t) && !RECUR (CLEANUP_EXPR (t), any))
9932 return false;
9933 return true;
9935 case EMPTY_CLASS_EXPR:
9936 return true;
9938 case GOTO_EXPR:
9940 tree *target = &TREE_OPERAND (t, 0);
9941 /* Gotos representing break, continue and cdtor return are OK. */
9942 if (breaks (target) || continues (target) || returns (target))
9944 *jump_target = *target;
9945 return true;
9947 if (flags & tf_error)
9948 constexpr_error (loc, fundef_p, "%<goto%> is not a constant "
9949 "expression");
9950 return false;
9953 case ASSERTION_STMT:
9954 case PRECONDITION_STMT:
9955 case POSTCONDITION_STMT:
9956 if (!checked_contract_p (get_contract_semantic (t)))
9957 return true;
9958 return RECUR (CONTRACT_CONDITION (t), rval);
9960 case LABEL_EXPR:
9961 t = LABEL_EXPR_LABEL (t);
9962 if (DECL_ARTIFICIAL (t) || cxx_dialect >= cxx23)
9963 return true;
9964 else if (flags & tf_error)
9965 constexpr_error (loc, fundef_p, "label definition in %<constexpr%> "
9966 "function only available with %<-std=c++2b%> or "
9967 "%<-std=gnu++2b%>");
9968 return false;
9970 case ANNOTATE_EXPR:
9971 return RECUR (TREE_OPERAND (t, 0), rval);
9973 case BIT_CAST_EXPR:
9974 return RECUR (TREE_OPERAND (t, 0), rval);
9976 /* Coroutine await, yield and return expressions are not. */
9977 case CO_AWAIT_EXPR:
9978 case CO_YIELD_EXPR:
9979 case CO_RETURN_EXPR:
9980 return false;
9982 case NONTYPE_ARGUMENT_PACK:
9984 tree args = ARGUMENT_PACK_ARGS (t);
9985 int len = TREE_VEC_LENGTH (args);
9986 for (int i = 0; i < len; ++i)
9987 if (!RECUR (TREE_VEC_ELT (args, i), any))
9988 return false;
9989 return true;
9992 default:
9993 if (objc_non_constant_expr_p (t))
9994 return false;
9996 sorry ("unexpected AST of kind %s", get_tree_code_name (TREE_CODE (t)));
9997 gcc_unreachable ();
9998 return false;
10000 #undef RECUR
10003 bool
10004 potential_constant_expression_1 (tree t, bool want_rval, bool strict, bool now,
10005 bool fundef_p, tsubst_flags_t flags)
10007 if (flags & tf_error)
10009 /* Check potentiality quietly first, as that could be performed more
10010 efficiently in some cases (currently only for TRUTH_*_EXPR). If
10011 that fails, replay the check noisily to give errors. */
10012 flags &= ~tf_error;
10013 if (potential_constant_expression_1 (t, want_rval, strict, now, fundef_p,
10014 flags))
10015 return true;
10016 flags |= tf_error;
10019 tree target = NULL_TREE;
10020 return potential_constant_expression_1 (t, want_rval, strict, now, fundef_p,
10021 flags, &target);
10024 /* The main entry point to the above. */
10026 bool
10027 potential_constant_expression (tree t)
10029 return potential_constant_expression_1 (t, /*want_rval*/false, /*strict*/true,
10030 /*now*/false, /*fundef_p*/false,
10031 tf_none);
10034 /* As above, but require a constant rvalue. */
10036 bool
10037 potential_rvalue_constant_expression (tree t)
10039 return potential_constant_expression_1 (t, /*want_rval*/true, /*strict*/true,
10040 /*now*/false, /*fundef_p*/false,
10041 tf_none);
10044 /* Like above, but complain about non-constant expressions. */
10046 bool
10047 require_potential_constant_expression (tree t)
10049 return potential_constant_expression_1 (t, /*want_rval*/false, /*strict*/true,
10050 /*now*/false, /*fundef_p*/false,
10051 tf_warning_or_error);
10054 /* Cross product of the above. */
10056 bool
10057 require_potential_rvalue_constant_expression (tree t)
10059 return potential_constant_expression_1 (t, /*want_rval*/true, /*strict*/true,
10060 /*now*/false, /*fundef_p*/false,
10061 tf_warning_or_error);
10064 /* Like require_potential_rvalue_constant_expression, but fundef_p is true. */
10066 bool
10067 require_potential_rvalue_constant_expression_fncheck (tree t)
10069 return potential_constant_expression_1 (t, /*want_rval*/true, /*strict*/true,
10070 /*now*/false, /*fundef_p*/true,
10071 tf_warning_or_error);
10074 /* Like above, but don't consider PARM_DECL a potential_constant_expression. */
10076 bool
10077 require_rvalue_constant_expression (tree t)
10079 return potential_constant_expression_1 (t, /*want_rval*/true, /*strict*/true,
10080 /*now*/true, /*fundef_p*/false,
10081 tf_warning_or_error);
10084 /* Like potential_constant_expression, but don't consider possible constexpr
10085 substitution of the current function. That is, PARM_DECL qualifies under
10086 potential_constant_expression, but not here.
10088 This is basically what you can check when any actual constant values might
10089 be value-dependent. */
10091 bool
10092 is_constant_expression (tree t)
10094 return potential_constant_expression_1 (t, /*want_rval*/false, /*strict*/true,
10095 /*now*/true, /*fundef_p*/false,
10096 tf_none);
10099 /* As above, but expect an rvalue. */
10101 bool
10102 is_rvalue_constant_expression (tree t)
10104 return potential_constant_expression_1 (t, /*want_rval*/true, /*strict*/true,
10105 /*now*/true, /*fundef_p*/false,
10106 tf_none);
10109 /* Like above, but complain about non-constant expressions. */
10111 bool
10112 require_constant_expression (tree t)
10114 return potential_constant_expression_1 (t, /*want_rval*/false, /*strict*/true,
10115 /*now*/true, /*fundef_p*/false,
10116 tf_warning_or_error);
10119 /* Like is_constant_expression, but allow const variables that are not allowed
10120 under constexpr rules. */
10122 bool
10123 is_static_init_expression (tree t)
10125 return potential_constant_expression_1 (t, /*want_rval*/false,
10126 /*strict*/false, /*now*/true,
10127 /*fundef_p*/false, tf_none);
10130 /* Returns true if T is a potential constant expression that is not
10131 instantiation-dependent, and therefore a candidate for constant folding even
10132 in a template. */
10134 bool
10135 is_nondependent_constant_expression (tree t)
10137 return (!type_unknown_p (t)
10138 && is_constant_expression (t)
10139 && !instantiation_dependent_expression_p (t));
10142 /* Returns true if T is a potential static initializer expression that is not
10143 instantiation-dependent. */
10145 bool
10146 is_nondependent_static_init_expression (tree t)
10148 return (!type_unknown_p (t)
10149 && is_static_init_expression (t)
10150 && !instantiation_dependent_expression_p (t));
10153 /* True iff FN is an implicitly constexpr function. */
10155 bool
10156 decl_implicit_constexpr_p (tree fn)
10158 if (!(flag_implicit_constexpr
10159 && TREE_CODE (fn) == FUNCTION_DECL
10160 && DECL_DECLARED_CONSTEXPR_P (fn)))
10161 return false;
10163 if (DECL_CLONED_FUNCTION_P (fn))
10164 fn = DECL_CLONED_FUNCTION (fn);
10166 return (DECL_LANG_SPECIFIC (fn)
10167 && DECL_LANG_SPECIFIC (fn)->u.fn.implicit_constexpr);
10170 /* Finalize constexpr processing after parsing. */
10172 void
10173 fini_constexpr (void)
10175 /* The contexpr call and fundef copies tables are no longer needed. */
10176 constexpr_call_table = NULL;
10177 fundef_copies_table = NULL;
10180 #include "gt-cp-constexpr.h"