c++: P2448 - Relaxing some constexpr restrictions [PR106649]
[official-gcc.git] / gcc / cp / constexpr.cc
bloba390cf921f3899fb72b1c6175ff03b272976c62f
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"
43 static bool verify_constant (tree, bool, bool *, bool *);
44 #define VERIFY_CONSTANT(X) \
45 do { \
46 if (verify_constant ((X), ctx->quiet, non_constant_p, overflow_p)) \
47 return t; \
48 } while (0)
50 static HOST_WIDE_INT find_array_ctor_elt (tree ary, tree dindex,
51 bool insert = false);
52 static int array_index_cmp (tree key, tree index);
54 /* Returns true iff FUN is an instantiation of a constexpr function
55 template or a defaulted constexpr function. */
57 bool
58 is_instantiation_of_constexpr (tree fun)
60 return ((DECL_TEMPLOID_INSTANTIATION (fun)
61 && DECL_DECLARED_CONSTEXPR_P (DECL_TI_TEMPLATE (fun)))
62 || (DECL_DEFAULTED_FN (fun)
63 && DECL_DECLARED_CONSTEXPR_P (fun)));
66 /* Return true if T is a literal type. */
68 bool
69 literal_type_p (tree t)
71 if (SCALAR_TYPE_P (t)
72 || VECTOR_TYPE_P (t)
73 || TYPE_REF_P (t)
74 || (VOID_TYPE_P (t) && cxx_dialect >= cxx14))
75 return true;
76 if (CLASS_TYPE_P (t))
78 t = complete_type (t);
79 gcc_assert (COMPLETE_TYPE_P (t) || errorcount);
80 return CLASSTYPE_LITERAL_P (t);
82 if (TREE_CODE (t) == ARRAY_TYPE)
83 return literal_type_p (strip_array_types (t));
84 return false;
87 /* If DECL is a variable declared `constexpr', require its type
88 be literal. Return error_mark_node if we give an error, the
89 DECL otherwise. */
91 tree
92 ensure_literal_type_for_constexpr_object (tree decl)
94 tree type = TREE_TYPE (decl);
95 if (VAR_P (decl)
96 && (DECL_DECLARED_CONSTEXPR_P (decl)
97 || var_in_constexpr_fn (decl))
98 && !processing_template_decl)
100 tree stype = strip_array_types (type);
101 if (CLASS_TYPE_P (stype) && !COMPLETE_TYPE_P (complete_type (stype)))
102 /* Don't complain here, we'll complain about incompleteness
103 when we try to initialize the variable. */;
104 else if (!literal_type_p (type))
106 if (DECL_DECLARED_CONSTEXPR_P (decl))
108 auto_diagnostic_group d;
109 error_at (DECL_SOURCE_LOCATION (decl),
110 "the type %qT of %<constexpr%> variable %qD "
111 "is not literal", type, decl);
112 explain_non_literal_class (type);
113 decl = error_mark_node;
115 else if (cxx_dialect < cxx23)
117 if (!is_instantiation_of_constexpr (current_function_decl))
119 auto_diagnostic_group d;
120 error_at (DECL_SOURCE_LOCATION (decl),
121 "variable %qD of non-literal type %qT in "
122 "%<constexpr%> function only available with "
123 "%<-std=c++2b%> or %<-std=gnu++2b%>", decl, type);
124 explain_non_literal_class (type);
125 decl = error_mark_node;
127 cp_function_chain->invalid_constexpr = true;
130 else if (DECL_DECLARED_CONSTEXPR_P (decl)
131 && variably_modified_type_p (type, NULL_TREE))
133 error_at (DECL_SOURCE_LOCATION (decl),
134 "%<constexpr%> variable %qD has variably-modified "
135 "type %qT", decl, type);
136 decl = error_mark_node;
139 return decl;
142 /* Issue a diagnostic with text GMSGID for constructs that are invalid in
143 constexpr functions. CONSTEXPR_FUNDEF_P is true if we're checking
144 a constexpr function body; if so, don't report hard errors and issue
145 a pedwarn pre-C++23, or a warning in C++23, if requested by
146 -Winvalid-constexpr. Otherwise, we're not in the context where we are
147 checking if a function can be marked 'constexpr', so give a hard error. */
149 ATTRIBUTE_GCC_DIAG(3,4)
150 static bool
151 constexpr_error (location_t location, bool constexpr_fundef_p,
152 const char *gmsgid, ...)
154 diagnostic_info diagnostic;
155 va_list ap;
156 rich_location richloc (line_table, location);
157 va_start (ap, gmsgid);
158 bool ret;
159 if (!constexpr_fundef_p)
161 /* Report an error that cannot be suppressed. */
162 diagnostic_set_info (&diagnostic, gmsgid, &ap, &richloc, DK_ERROR);
163 ret = diagnostic_report_diagnostic (global_dc, &diagnostic);
165 else if (warn_invalid_constexpr)
167 diagnostic_set_info (&diagnostic, gmsgid, &ap, &richloc,
168 cxx_dialect < cxx23 ? DK_PEDWARN : DK_WARNING);
169 diagnostic.option_index = OPT_Winvalid_constexpr;
170 ret = diagnostic_report_diagnostic (global_dc, &diagnostic);
172 else
173 ret = false;
174 va_end (ap);
175 return ret;
178 struct constexpr_fundef_hasher : ggc_ptr_hash<constexpr_fundef>
180 static hashval_t hash (const constexpr_fundef *);
181 static bool equal (const constexpr_fundef *, const constexpr_fundef *);
184 /* This table holds all constexpr function definitions seen in
185 the current translation unit. */
187 static GTY (()) hash_table<constexpr_fundef_hasher> *constexpr_fundef_table;
189 /* Utility function used for managing the constexpr function table.
190 Return true if the entries pointed to by P and Q are for the
191 same constexpr function. */
193 inline bool
194 constexpr_fundef_hasher::equal (const constexpr_fundef *lhs,
195 const constexpr_fundef *rhs)
197 return lhs->decl == rhs->decl;
200 /* Utility function used for managing the constexpr function table.
201 Return a hash value for the entry pointed to by Q. */
203 inline hashval_t
204 constexpr_fundef_hasher::hash (const constexpr_fundef *fundef)
206 return DECL_UID (fundef->decl);
209 /* Return a previously saved definition of function FUN. */
211 constexpr_fundef *
212 retrieve_constexpr_fundef (tree fun)
214 if (constexpr_fundef_table == NULL)
215 return NULL;
217 constexpr_fundef fundef = { fun, NULL_TREE, NULL_TREE, NULL_TREE };
218 return constexpr_fundef_table->find (&fundef);
221 /* Check whether the parameter and return types of FUN are valid for a
222 constexpr function, and complain if COMPLAIN. */
224 bool
225 is_valid_constexpr_fn (tree fun, bool complain)
227 bool ret = true;
229 if (DECL_INHERITED_CTOR (fun)
230 && TREE_CODE (fun) == TEMPLATE_DECL)
232 ret = false;
233 if (complain)
234 error ("inherited constructor %qD is not %<constexpr%>",
235 DECL_INHERITED_CTOR (fun));
237 else
239 for (tree parm = FUNCTION_FIRST_USER_PARM (fun);
240 parm != NULL_TREE; parm = TREE_CHAIN (parm))
241 if (!literal_type_p (TREE_TYPE (parm)))
243 ret = false;
244 if (complain)
246 auto_diagnostic_group d;
247 if (constexpr_error (input_location, /*constexpr_fundef_p*/true,
248 "invalid type for parameter %d of "
249 "%<constexpr%> function %q+#D",
250 DECL_PARM_INDEX (parm), fun))
251 explain_non_literal_class (TREE_TYPE (parm));
256 if (LAMBDA_TYPE_P (CP_DECL_CONTEXT (fun)) && cxx_dialect < cxx17)
258 ret = false;
259 if (complain)
260 inform (DECL_SOURCE_LOCATION (fun),
261 "lambdas are implicitly %<constexpr%> only in C++17 and later");
263 else if (DECL_DESTRUCTOR_P (fun))
265 if (cxx_dialect < cxx20)
267 ret = false;
268 if (complain)
269 error_at (DECL_SOURCE_LOCATION (fun),
270 "%<constexpr%> destructors only available"
271 " with %<-std=c++20%> or %<-std=gnu++20%>");
274 else if (!DECL_CONSTRUCTOR_P (fun))
276 tree rettype = TREE_TYPE (TREE_TYPE (fun));
277 if (!literal_type_p (rettype))
279 ret = false;
280 if (complain)
282 auto_diagnostic_group d;
283 if (constexpr_error (input_location, /*constexpr_fundef_p*/true,
284 "invalid return type %qT of %<constexpr%> "
285 "function %q+D", rettype, fun))
286 explain_non_literal_class (rettype);
290 /* C++14 DR 1684 removed this restriction. */
291 if (cxx_dialect < cxx14
292 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fun)
293 && !CLASSTYPE_LITERAL_P (DECL_CONTEXT (fun)))
295 ret = false;
296 if (complain)
298 auto_diagnostic_group d;
299 if (pedwarn (DECL_SOURCE_LOCATION (fun), OPT_Wpedantic,
300 "enclosing class of %<constexpr%> non-static"
301 " member function %q+#D is not a literal type",
302 fun))
303 explain_non_literal_class (DECL_CONTEXT (fun));
307 else if (CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fun)))
309 ret = false;
310 if (complain)
311 error ("%q#T has virtual base classes", DECL_CONTEXT (fun));
314 return ret;
317 /* Subroutine of build_data_member_initialization. MEMBER is a COMPONENT_REF
318 for a member of an anonymous aggregate, INIT is the initializer for that
319 member, and VEC_OUTER is the vector of constructor elements for the class
320 whose constructor we are processing. Add the initializer to the vector
321 and return true to indicate success. */
323 static bool
324 build_anon_member_initialization (tree member, tree init,
325 vec<constructor_elt, va_gc> **vec_outer)
327 /* MEMBER presents the relevant fields from the inside out, but we need
328 to build up the initializer from the outside in so that we can reuse
329 previously built CONSTRUCTORs if this is, say, the second field in an
330 anonymous struct. So we use a vec as a stack. */
331 auto_vec<tree, 2> fields;
334 fields.safe_push (TREE_OPERAND (member, 1));
335 member = TREE_OPERAND (member, 0);
337 while (ANON_AGGR_TYPE_P (TREE_TYPE (member))
338 && TREE_CODE (member) == COMPONENT_REF);
340 /* VEC has the constructor elements vector for the context of FIELD.
341 If FIELD is an anonymous aggregate, we will push inside it. */
342 vec<constructor_elt, va_gc> **vec = vec_outer;
343 tree field;
344 while (field = fields.pop(),
345 ANON_AGGR_TYPE_P (TREE_TYPE (field)))
347 tree ctor;
348 /* If there is already an outer constructor entry for the anonymous
349 aggregate FIELD, use it; otherwise, insert one. */
350 if (vec_safe_is_empty (*vec)
351 || (*vec)->last().index != field)
353 ctor = build_constructor (TREE_TYPE (field), NULL);
354 CONSTRUCTOR_APPEND_ELT (*vec, field, ctor);
356 else
357 ctor = (*vec)->last().value;
358 vec = &CONSTRUCTOR_ELTS (ctor);
361 /* Now we're at the innermost field, the one that isn't an anonymous
362 aggregate. Add its initializer to the CONSTRUCTOR and we're done. */
363 gcc_assert (fields.is_empty());
364 CONSTRUCTOR_APPEND_ELT (*vec, field, init);
366 return true;
369 /* Subroutine of build_constexpr_constructor_member_initializers.
370 The expression tree T represents a data member initialization
371 in a (constexpr) constructor definition. Build a pairing of
372 the data member with its initializer, and prepend that pair
373 to the existing initialization pair INITS. */
375 static bool
376 build_data_member_initialization (tree t, vec<constructor_elt, va_gc> **vec)
378 tree member, init;
379 if (TREE_CODE (t) == CLEANUP_POINT_EXPR)
380 t = TREE_OPERAND (t, 0);
381 if (TREE_CODE (t) == EXPR_STMT)
382 t = TREE_OPERAND (t, 0);
383 if (t == error_mark_node)
384 return false;
385 if (TREE_CODE (t) == STATEMENT_LIST)
387 for (tree stmt : tsi_range (t))
388 if (! build_data_member_initialization (stmt, vec))
389 return false;
390 return true;
392 if (TREE_CODE (t) == CLEANUP_STMT)
394 /* We can't see a CLEANUP_STMT in a constructor for a literal class,
395 but we can in a constexpr constructor for a non-literal class. Just
396 ignore it; either all the initialization will be constant, in which
397 case the cleanup can't run, or it can't be constexpr.
398 Still recurse into CLEANUP_BODY. */
399 return build_data_member_initialization (CLEANUP_BODY (t), vec);
401 if (TREE_CODE (t) == CONVERT_EXPR)
402 t = TREE_OPERAND (t, 0);
403 if (TREE_CODE (t) == INIT_EXPR
404 /* vptr initialization shows up as a MODIFY_EXPR. In C++14 we only
405 use what this function builds for cx_check_missing_mem_inits, and
406 assignment in the ctor body doesn't count. */
407 || (cxx_dialect < cxx14 && TREE_CODE (t) == MODIFY_EXPR))
409 member = TREE_OPERAND (t, 0);
410 init = break_out_target_exprs (TREE_OPERAND (t, 1));
412 else if (TREE_CODE (t) == CALL_EXPR)
414 tree fn = get_callee_fndecl (t);
415 if (!fn || !DECL_CONSTRUCTOR_P (fn))
416 /* We're only interested in calls to subobject constructors. */
417 return true;
418 member = CALL_EXPR_ARG (t, 0);
419 /* We don't use build_cplus_new here because it complains about
420 abstract bases. Leaving the call unwrapped means that it has the
421 wrong type, but cxx_eval_constant_expression doesn't care. */
422 init = break_out_target_exprs (t);
424 else if (TREE_CODE (t) == BIND_EXPR)
425 return build_data_member_initialization (BIND_EXPR_BODY (t), vec);
426 else
427 /* Don't add anything else to the CONSTRUCTOR. */
428 return true;
429 if (INDIRECT_REF_P (member))
430 member = TREE_OPERAND (member, 0);
431 if (TREE_CODE (member) == NOP_EXPR)
433 tree op = member;
434 STRIP_NOPS (op);
435 if (TREE_CODE (op) == ADDR_EXPR)
437 gcc_assert (same_type_ignoring_top_level_qualifiers_p
438 (TREE_TYPE (TREE_TYPE (op)),
439 TREE_TYPE (TREE_TYPE (member))));
440 /* Initializing a cv-qualified member; we need to look through
441 the const_cast. */
442 member = op;
444 else if (op == current_class_ptr
445 && (same_type_ignoring_top_level_qualifiers_p
446 (TREE_TYPE (TREE_TYPE (member)),
447 current_class_type)))
448 /* Delegating constructor. */
449 member = op;
450 else
452 /* This is an initializer for an empty base; keep it for now so
453 we can check it in cxx_eval_bare_aggregate. */
454 gcc_assert (is_empty_class (TREE_TYPE (TREE_TYPE (member))));
457 if (TREE_CODE (member) == ADDR_EXPR)
458 member = TREE_OPERAND (member, 0);
459 if (TREE_CODE (member) == COMPONENT_REF)
461 tree aggr = TREE_OPERAND (member, 0);
462 if (TREE_CODE (aggr) == VAR_DECL)
463 /* Initializing a local variable, don't add anything. */
464 return true;
465 if (TREE_CODE (aggr) != COMPONENT_REF)
466 /* Normal member initialization. */
467 member = TREE_OPERAND (member, 1);
468 else if (ANON_AGGR_TYPE_P (TREE_TYPE (aggr)))
469 /* Initializing a member of an anonymous union. */
470 return build_anon_member_initialization (member, init, vec);
471 else
472 /* We're initializing a vtable pointer in a base. Leave it as
473 COMPONENT_REF so we remember the path to get to the vfield. */
474 gcc_assert (TREE_TYPE (member) == vtbl_ptr_type_node);
477 /* Value-initialization can produce multiple initializers for the
478 same field; use the last one. */
479 if (!vec_safe_is_empty (*vec) && (*vec)->last().index == member)
480 (*vec)->last().value = init;
481 else
482 CONSTRUCTOR_APPEND_ELT (*vec, member, init);
483 return true;
486 /* Subroutine of check_constexpr_ctor_body_1 and constexpr_fn_retval.
487 In C++11 mode checks that the TYPE_DECLs in the BIND_EXPR_VARS of a
488 BIND_EXPR conform to 7.1.5/3/4 on typedef and alias declarations. */
490 static bool
491 check_constexpr_bind_expr_vars (tree t)
493 gcc_assert (TREE_CODE (t) == BIND_EXPR);
495 for (tree var = BIND_EXPR_VARS (t); var; var = DECL_CHAIN (var))
496 if (TREE_CODE (var) == TYPE_DECL
497 && DECL_IMPLICIT_TYPEDEF_P (var)
498 && !LAMBDA_TYPE_P (TREE_TYPE (var)))
499 return false;
500 return true;
503 /* Subroutine of check_constexpr_ctor_body. */
505 static bool
506 check_constexpr_ctor_body_1 (tree last, tree list)
508 switch (TREE_CODE (list))
510 case DECL_EXPR:
511 if (TREE_CODE (DECL_EXPR_DECL (list)) == USING_DECL
512 || TREE_CODE (DECL_EXPR_DECL (list)) == TYPE_DECL)
513 return true;
514 return false;
516 case CLEANUP_POINT_EXPR:
517 return check_constexpr_ctor_body (last, TREE_OPERAND (list, 0),
518 /*complain=*/false);
520 case BIND_EXPR:
521 if (!check_constexpr_bind_expr_vars (list)
522 || !check_constexpr_ctor_body (last, BIND_EXPR_BODY (list),
523 /*complain=*/false))
524 return false;
525 return true;
527 case USING_STMT:
528 case STATIC_ASSERT:
529 case DEBUG_BEGIN_STMT:
530 return true;
532 default:
533 return false;
537 /* Make sure that there are no statements after LAST in the constructor
538 body represented by LIST. */
540 bool
541 check_constexpr_ctor_body (tree last, tree list, bool complain)
543 /* C++14 doesn't require a constexpr ctor to have an empty body. */
544 if (cxx_dialect >= cxx14)
545 return true;
547 bool ok = true;
548 if (TREE_CODE (list) == STATEMENT_LIST)
550 tree_stmt_iterator i = tsi_last (list);
551 for (; !tsi_end_p (i); tsi_prev (&i))
553 tree t = tsi_stmt (i);
554 if (t == last)
555 break;
556 if (!check_constexpr_ctor_body_1 (last, t))
558 ok = false;
559 break;
563 else if (list != last
564 && !check_constexpr_ctor_body_1 (last, list))
565 ok = false;
566 if (!ok)
568 if (complain)
569 error ("%<constexpr%> constructor does not have empty body");
570 DECL_DECLARED_CONSTEXPR_P (current_function_decl) = false;
572 return ok;
575 /* V is a vector of constructor elements built up for the base and member
576 initializers of a constructor for TYPE. They need to be in increasing
577 offset order, which they might not be yet if TYPE has a primary base
578 which is not first in the base-clause or a vptr and at least one base
579 all of which are non-primary. */
581 static vec<constructor_elt, va_gc> *
582 sort_constexpr_mem_initializers (tree type, vec<constructor_elt, va_gc> *v)
584 tree pri = CLASSTYPE_PRIMARY_BINFO (type);
585 tree field_type;
586 unsigned i;
587 constructor_elt *ce;
589 if (pri)
590 field_type = BINFO_TYPE (pri);
591 else if (TYPE_CONTAINS_VPTR_P (type))
592 field_type = vtbl_ptr_type_node;
593 else
594 return v;
596 /* Find the element for the primary base or vptr and move it to the
597 beginning of the vec. */
598 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
599 if (TREE_TYPE (ce->index) == field_type)
600 break;
602 if (i > 0 && i < vec_safe_length (v))
604 vec<constructor_elt, va_gc> &vref = *v;
605 constructor_elt elt = vref[i];
606 for (; i > 0; --i)
607 vref[i] = vref[i-1];
608 vref[0] = elt;
611 return v;
614 /* Build compile-time evalable representations of member-initializer list
615 for a constexpr constructor. */
617 static tree
618 build_constexpr_constructor_member_initializers (tree type, tree body)
620 vec<constructor_elt, va_gc> *vec = NULL;
621 bool ok = true;
622 while (true)
623 switch (TREE_CODE (body))
625 case MUST_NOT_THROW_EXPR:
626 case EH_SPEC_BLOCK:
627 body = TREE_OPERAND (body, 0);
628 break;
630 case STATEMENT_LIST:
631 for (tree stmt : tsi_range (body))
633 body = stmt;
634 if (TREE_CODE (body) == BIND_EXPR)
635 break;
637 break;
639 case BIND_EXPR:
640 body = BIND_EXPR_BODY (body);
641 goto found;
643 default:
644 gcc_unreachable ();
646 found:
647 if (TREE_CODE (body) == TRY_BLOCK)
649 body = TREE_OPERAND (body, 0);
650 if (TREE_CODE (body) == BIND_EXPR)
651 body = BIND_EXPR_BODY (body);
653 if (TREE_CODE (body) == CLEANUP_POINT_EXPR)
655 body = TREE_OPERAND (body, 0);
656 if (TREE_CODE (body) == EXPR_STMT)
657 body = TREE_OPERAND (body, 0);
658 if (TREE_CODE (body) == INIT_EXPR
659 && (same_type_ignoring_top_level_qualifiers_p
660 (TREE_TYPE (TREE_OPERAND (body, 0)),
661 current_class_type)))
663 /* Trivial copy. */
664 return TREE_OPERAND (body, 1);
666 ok = build_data_member_initialization (body, &vec);
668 else if (TREE_CODE (body) == STATEMENT_LIST)
670 for (tree stmt : tsi_range (body))
672 ok = build_data_member_initialization (stmt, &vec);
673 if (!ok)
674 break;
677 else if (EXPR_P (body))
678 ok = build_data_member_initialization (body, &vec);
679 else
680 gcc_assert (errorcount > 0);
681 if (ok)
683 if (vec_safe_length (vec) > 0)
685 /* In a delegating constructor, return the target. */
686 constructor_elt *ce = &(*vec)[0];
687 if (ce->index == current_class_ptr)
689 body = ce->value;
690 vec_free (vec);
691 return body;
694 vec = sort_constexpr_mem_initializers (type, vec);
695 return build_constructor (type, vec);
697 else
698 return error_mark_node;
701 /* We have an expression tree T that represents a call, either CALL_EXPR
702 or AGGR_INIT_EXPR. If the call is lexically to a named function,
703 retrun the _DECL for that function. */
705 static tree
706 get_function_named_in_call (tree t)
708 tree fun = cp_get_callee (t);
709 if (fun && TREE_CODE (fun) == ADDR_EXPR
710 && TREE_CODE (TREE_OPERAND (fun, 0)) == FUNCTION_DECL)
711 fun = TREE_OPERAND (fun, 0);
712 return fun;
715 /* Subroutine of check_constexpr_fundef. BODY is the body of a function
716 declared to be constexpr, or a sub-statement thereof. Returns the
717 return value if suitable, error_mark_node for a statement not allowed in
718 a constexpr function, or NULL_TREE if no return value was found. */
720 tree
721 constexpr_fn_retval (tree body)
723 switch (TREE_CODE (body))
725 case STATEMENT_LIST:
727 tree expr = NULL_TREE;
728 for (tree stmt : tsi_range (body))
730 tree s = constexpr_fn_retval (stmt);
731 if (s == error_mark_node)
732 return error_mark_node;
733 else if (s == NULL_TREE)
734 /* Keep iterating. */;
735 else if (expr)
736 /* Multiple return statements. */
737 return error_mark_node;
738 else
739 expr = s;
741 return expr;
744 case RETURN_EXPR:
745 return break_out_target_exprs (TREE_OPERAND (body, 0));
747 case DECL_EXPR:
749 tree decl = DECL_EXPR_DECL (body);
750 if (TREE_CODE (decl) == USING_DECL
751 /* Accept __func__, __FUNCTION__, and __PRETTY_FUNCTION__. */
752 || DECL_ARTIFICIAL (decl))
753 return NULL_TREE;
754 return error_mark_node;
757 case CLEANUP_POINT_EXPR:
758 return constexpr_fn_retval (TREE_OPERAND (body, 0));
760 case BIND_EXPR:
761 if (!check_constexpr_bind_expr_vars (body))
762 return error_mark_node;
763 return constexpr_fn_retval (BIND_EXPR_BODY (body));
765 case USING_STMT:
766 case DEBUG_BEGIN_STMT:
767 return NULL_TREE;
769 case CALL_EXPR:
771 tree fun = get_function_named_in_call (body);
772 if (fun != NULL_TREE
773 && fndecl_built_in_p (fun, BUILT_IN_UNREACHABLE))
774 return NULL_TREE;
776 /* Fallthru. */
778 default:
779 return error_mark_node;
783 /* Subroutine of check_constexpr_fundef. BODY is the DECL_SAVED_TREE of
784 FUN; do the necessary transformations to turn it into a single expression
785 that we can store in the hash table. */
787 static tree
788 massage_constexpr_body (tree fun, tree body)
790 if (DECL_CONSTRUCTOR_P (fun))
791 body = build_constexpr_constructor_member_initializers
792 (DECL_CONTEXT (fun), body);
793 else if (cxx_dialect < cxx14)
795 if (TREE_CODE (body) == EH_SPEC_BLOCK)
796 body = EH_SPEC_STMTS (body);
797 if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
798 body = TREE_OPERAND (body, 0);
799 body = constexpr_fn_retval (body);
801 return body;
804 /* CTYPE is a type constructed from BODY. Return true if some
805 bases/fields are uninitialized, and complain if COMPLAIN. */
807 static bool
808 cx_check_missing_mem_inits (tree ctype, tree body, bool complain)
810 /* We allow uninitialized bases/fields in C++20. */
811 if (cxx_dialect >= cxx20)
812 return false;
814 unsigned nelts = 0;
816 if (body)
818 if (TREE_CODE (body) != CONSTRUCTOR)
819 return false;
820 nelts = CONSTRUCTOR_NELTS (body);
822 tree field = TYPE_FIELDS (ctype);
824 if (TREE_CODE (ctype) == UNION_TYPE)
826 if (nelts == 0 && next_aggregate_field (field))
828 if (complain)
829 error ("%<constexpr%> constructor for union %qT must "
830 "initialize exactly one non-static data member", ctype);
831 return true;
833 return false;
836 /* Iterate over the CONSTRUCTOR, checking any missing fields don't
837 need an explicit initialization. */
838 bool bad = false;
839 for (unsigned i = 0; i <= nelts; ++i)
841 tree index = NULL_TREE;
842 if (i < nelts)
844 index = CONSTRUCTOR_ELT (body, i)->index;
845 /* Skip base and vtable inits. */
846 if (TREE_CODE (index) != FIELD_DECL
847 || DECL_ARTIFICIAL (index))
848 continue;
851 for (; field != index; field = DECL_CHAIN (field))
853 tree ftype;
854 if (TREE_CODE (field) != FIELD_DECL)
855 continue;
856 if (DECL_UNNAMED_BIT_FIELD (field))
857 continue;
858 if (DECL_ARTIFICIAL (field))
859 continue;
860 if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
862 /* Recurse to check the anonymous aggregate member. */
863 bad |= cx_check_missing_mem_inits
864 (TREE_TYPE (field), NULL_TREE, complain);
865 if (bad && !complain)
866 return true;
867 continue;
869 ftype = TREE_TYPE (field);
870 if (!ftype || !TYPE_P (ftype) || !COMPLETE_TYPE_P (ftype))
871 /* A flexible array can't be intialized here, so don't complain
872 that it isn't. */
873 continue;
874 if (is_empty_field (field))
875 /* An empty field doesn't need an initializer. */
876 continue;
877 ftype = strip_array_types (ftype);
878 if (type_has_constexpr_default_constructor (ftype))
880 /* It's OK to skip a member with a trivial constexpr ctor.
881 A constexpr ctor that isn't trivial should have been
882 added in by now. */
883 gcc_checking_assert (!TYPE_HAS_COMPLEX_DFLT (ftype)
884 || errorcount != 0);
885 continue;
887 if (!complain)
888 return true;
889 auto_diagnostic_group d;
890 error ("member %qD must be initialized by mem-initializer "
891 "in %<constexpr%> constructor", field);
892 inform (DECL_SOURCE_LOCATION (field), "declared here");
893 bad = true;
895 if (field == NULL_TREE)
896 break;
898 if (ANON_AGGR_TYPE_P (TREE_TYPE (index)))
900 /* Check the anonymous aggregate initializer is valid. */
901 bad |= cx_check_missing_mem_inits
902 (TREE_TYPE (index), CONSTRUCTOR_ELT (body, i)->value, complain);
903 if (bad && !complain)
904 return true;
906 field = DECL_CHAIN (field);
909 return bad;
912 /* We are processing the definition of the constexpr function FUN.
913 Check that its body fulfills the apropriate requirements and
914 enter it in the constexpr function definition table. */
916 void
917 maybe_save_constexpr_fundef (tree fun)
919 if (processing_template_decl
920 || cp_function_chain->invalid_constexpr
921 || (DECL_CLONED_FUNCTION_P (fun) && !DECL_DELETING_DESTRUCTOR_P (fun)))
922 return;
924 /* With -fimplicit-constexpr, try to make inlines constexpr. We'll
925 actually set DECL_DECLARED_CONSTEXPR_P below if the checks pass. */
926 bool implicit = false;
927 if (flag_implicit_constexpr)
929 if (DECL_DELETING_DESTRUCTOR_P (fun)
930 && decl_implicit_constexpr_p (DECL_CLONED_FUNCTION (fun)))
931 /* Don't inherit implicit constexpr from the non-deleting
932 destructor. */
933 DECL_DECLARED_CONSTEXPR_P (fun) = false;
935 if (!DECL_DECLARED_CONSTEXPR_P (fun)
936 && DECL_DECLARED_INLINE_P (fun)
937 && !lookup_attribute ("noinline", DECL_ATTRIBUTES (fun)))
938 implicit = true;
941 if (!DECL_DECLARED_CONSTEXPR_P (fun) && !implicit)
942 return;
944 bool complain = !DECL_GENERATED_P (fun) && !implicit;
946 if (!is_valid_constexpr_fn (fun, complain))
947 return;
949 tree massaged = massage_constexpr_body (fun, DECL_SAVED_TREE (fun));
950 if (massaged == NULL_TREE || massaged == error_mark_node)
952 if (!DECL_CONSTRUCTOR_P (fun) && complain)
953 error ("body of %<constexpr%> function %qD not a return-statement",
954 fun);
955 return;
958 bool potential = potential_rvalue_constant_expression (massaged);
959 if (!potential && complain)
960 require_potential_rvalue_constant_expression_fncheck (massaged);
962 if (DECL_CONSTRUCTOR_P (fun) && potential
963 && !DECL_DEFAULTED_FN (fun))
965 if (cx_check_missing_mem_inits (DECL_CONTEXT (fun),
966 massaged, complain))
967 potential = false;
968 else if (cxx_dialect > cxx11)
970 /* What we got from massage_constexpr_body is pretty much just the
971 ctor-initializer, also check the body. */
972 massaged = DECL_SAVED_TREE (fun);
973 potential = potential_rvalue_constant_expression (massaged);
974 if (!potential && complain)
975 require_potential_rvalue_constant_expression_fncheck (massaged);
979 if (!potential && complain
980 /* If -Wno-invalid-constexpr was specified, we haven't complained
981 about non-constant expressions yet. Register the function and
982 complain in explain_invalid_constexpr_fn if the function is
983 called. */
984 && warn_invalid_constexpr != 0)
985 return;
987 if (implicit)
989 if (potential)
991 DECL_DECLARED_CONSTEXPR_P (fun) = true;
992 DECL_LANG_SPECIFIC (fun)->u.fn.implicit_constexpr = true;
993 if (DECL_CONSTRUCTOR_P (fun))
994 TYPE_HAS_CONSTEXPR_CTOR (DECL_CONTEXT (fun)) = true;
996 else
997 /* Don't bother keeping the pre-generic body of unsuitable functions
998 not explicitly declared constexpr. */
999 return;
1002 constexpr_fundef entry = {fun, NULL_TREE, NULL_TREE, NULL_TREE};
1003 bool clear_ctx = false;
1004 if (DECL_RESULT (fun) && DECL_CONTEXT (DECL_RESULT (fun)) == NULL_TREE)
1006 clear_ctx = true;
1007 DECL_CONTEXT (DECL_RESULT (fun)) = fun;
1009 tree saved_fn = current_function_decl;
1010 current_function_decl = fun;
1011 entry.body = copy_fn (entry.decl, entry.parms, entry.result);
1012 current_function_decl = saved_fn;
1013 if (clear_ctx)
1014 DECL_CONTEXT (DECL_RESULT (entry.decl)) = NULL_TREE;
1015 if (!potential)
1016 /* For a template instantiation, we want to remember the pre-generic body
1017 for explain_invalid_constexpr_fn, but do tell cxx_eval_call_expression
1018 that it doesn't need to bother trying to expand the function. */
1019 entry.result = error_mark_node;
1021 register_constexpr_fundef (entry);
1024 /* BODY is a validated and massaged definition of a constexpr
1025 function. Register it in the hash table. */
1027 void
1028 register_constexpr_fundef (const constexpr_fundef &value)
1030 /* Create the constexpr function table if necessary. */
1031 if (constexpr_fundef_table == NULL)
1032 constexpr_fundef_table
1033 = hash_table<constexpr_fundef_hasher>::create_ggc (101);
1035 constexpr_fundef **slot = constexpr_fundef_table->find_slot
1036 (const_cast<constexpr_fundef *> (&value), INSERT);
1038 gcc_assert (*slot == NULL);
1039 *slot = ggc_alloc<constexpr_fundef> ();
1040 **slot = value;
1043 /* FUN is a non-constexpr (or, with -Wno-invalid-constexpr, a constexpr
1044 function called in a context that requires a constant expression).
1045 If it comes from a constexpr template, explain why the instantiation
1046 isn't constexpr. Otherwise, explain why the function cannot be used
1047 in a constexpr context. */
1049 void
1050 explain_invalid_constexpr_fn (tree fun)
1052 static hash_set<tree> *diagnosed;
1053 tree body;
1054 /* In C++23, a function marked 'constexpr' may not actually be a constant
1055 expression. We haven't diagnosed the problem yet: -Winvalid-constexpr
1056 wasn't enabled. The function was called, so diagnose why it cannot be
1057 used in a constant expression. */
1058 if (warn_invalid_constexpr == 0 && DECL_DECLARED_CONSTEXPR_P (fun))
1059 /* Go on. */;
1060 /* Only diagnose defaulted functions, lambdas, or instantiations. */
1061 else if (!DECL_DEFAULTED_FN (fun)
1062 && !LAMBDA_TYPE_P (CP_DECL_CONTEXT (fun))
1063 && !is_instantiation_of_constexpr (fun))
1065 inform (DECL_SOURCE_LOCATION (fun), "%qD declared here", fun);
1066 return;
1068 if (diagnosed == NULL)
1069 diagnosed = new hash_set<tree>;
1070 if (diagnosed->add (fun))
1071 /* Already explained. */
1072 return;
1074 iloc_sentinel ils = input_location;
1075 if (!lambda_static_thunk_p (fun))
1077 /* Diagnostics should completely ignore the static thunk, so leave
1078 input_location set to our caller's location. */
1079 input_location = DECL_SOURCE_LOCATION (fun);
1080 inform (input_location,
1081 "%qD is not usable as a %<constexpr%> function because:", fun);
1083 /* First check the declaration. */
1084 if (is_valid_constexpr_fn (fun, true))
1086 /* Then if it's OK, the body. */
1087 if (!DECL_DECLARED_CONSTEXPR_P (fun)
1088 && DECL_DEFAULTED_FN (fun))
1089 explain_implicit_non_constexpr (fun);
1090 else
1092 if (constexpr_fundef *fd = retrieve_constexpr_fundef (fun))
1093 body = fd->body;
1094 else
1095 body = DECL_SAVED_TREE (fun);
1096 body = massage_constexpr_body (fun, body);
1097 require_potential_rvalue_constant_expression (body);
1098 if (DECL_CONSTRUCTOR_P (fun))
1099 cx_check_missing_mem_inits (DECL_CONTEXT (fun), body, true);
1104 /* Objects of this type represent calls to constexpr functions
1105 along with the bindings of parameters to their arguments, for
1106 the purpose of compile time evaluation. */
1108 struct GTY((for_user)) constexpr_call {
1109 /* Description of the constexpr function definition. */
1110 constexpr_fundef *fundef;
1111 /* Parameter bindings environment. A TREE_VEC of arguments. */
1112 tree bindings;
1113 /* Result of the call.
1114 NULL means the call is being evaluated.
1115 error_mark_node means that the evaluation was erroneous;
1116 otherwise, the actuall value of the call. */
1117 tree result;
1118 /* The hash of this call; we remember it here to avoid having to
1119 recalculate it when expanding the hash table. */
1120 hashval_t hash;
1121 /* Whether __builtin_is_constant_evaluated() should evaluate to true. */
1122 bool manifestly_const_eval;
1125 struct constexpr_call_hasher : ggc_ptr_hash<constexpr_call>
1127 static hashval_t hash (constexpr_call *);
1128 static bool equal (constexpr_call *, constexpr_call *);
1131 enum constexpr_switch_state {
1132 /* Used when processing a switch for the first time by cxx_eval_switch_expr
1133 and default: label for that switch has not been seen yet. */
1134 css_default_not_seen,
1135 /* Used when processing a switch for the first time by cxx_eval_switch_expr
1136 and default: label for that switch has been seen already. */
1137 css_default_seen,
1138 /* Used when processing a switch for the second time by
1139 cxx_eval_switch_expr, where default: label should match. */
1140 css_default_processing
1143 /* The constexpr expansion context part which needs one instance per
1144 cxx_eval_outermost_constant_expr invocation. VALUES is a map of values of
1145 variables initialized within the expression. */
1147 class constexpr_global_ctx {
1148 /* Values for any temporaries or local variables within the
1149 constant-expression. */
1150 hash_map<tree,tree> values;
1151 public:
1152 /* Number of cxx_eval_constant_expression calls (except skipped ones,
1153 on simple constants or location wrappers) encountered during current
1154 cxx_eval_outermost_constant_expr call. */
1155 HOST_WIDE_INT constexpr_ops_count;
1156 /* Heap VAR_DECLs created during the evaluation of the outermost constant
1157 expression. */
1158 auto_vec<tree, 16> heap_vars;
1159 /* Cleanups that need to be evaluated at the end of CLEANUP_POINT_EXPR. */
1160 vec<tree> *cleanups;
1161 /* If non-null, only allow modification of existing values of the variables
1162 in this set. Set by modifiable_tracker, below. */
1163 hash_set<tree> *modifiable;
1164 /* Number of heap VAR_DECL deallocations. */
1165 unsigned heap_dealloc_count;
1166 /* Constructor. */
1167 constexpr_global_ctx ()
1168 : constexpr_ops_count (0), cleanups (NULL), modifiable (nullptr),
1169 heap_dealloc_count (0) {}
1171 tree get_value (tree t)
1173 if (tree *p = values.get (t))
1174 return *p;
1175 return NULL_TREE;
1177 tree *get_value_ptr (tree t)
1179 if (modifiable && !modifiable->contains (t))
1180 return nullptr;
1181 return values.get (t);
1183 void put_value (tree t, tree v)
1185 bool already_in_map = values.put (t, v);
1186 if (!already_in_map && modifiable)
1187 modifiable->add (t);
1189 void remove_value (tree t) { values.remove (t); }
1192 /* Helper class for constexpr_global_ctx. In some cases we want to avoid
1193 side-effects from evaluation of a particular subexpression of a
1194 constant-expression. In such cases we use modifiable_tracker to prevent
1195 modification of variables created outside of that subexpression.
1197 ??? We could change the hash_set to a hash_map, allow and track external
1198 modifications, and roll them back in the destructor. It's not clear to me
1199 that this would be worthwhile. */
1201 class modifiable_tracker
1203 hash_set<tree> set;
1204 constexpr_global_ctx *global;
1205 public:
1206 modifiable_tracker (constexpr_global_ctx *g): global(g)
1208 global->modifiable = &set;
1210 ~modifiable_tracker ()
1212 for (tree t: set)
1213 global->remove_value (t);
1214 global->modifiable = nullptr;
1218 /* The constexpr expansion context. CALL is the current function
1219 expansion, CTOR is the current aggregate initializer, OBJECT is the
1220 object being initialized by CTOR, either a VAR_DECL or a _REF. */
1222 struct constexpr_ctx {
1223 /* The part of the context that needs to be unique to the whole
1224 cxx_eval_outermost_constant_expr invocation. */
1225 constexpr_global_ctx *global;
1226 /* The innermost call we're evaluating. */
1227 constexpr_call *call;
1228 /* SAVE_EXPRs and TARGET_EXPR_SLOT vars of TARGET_EXPRs that we've seen
1229 within the current LOOP_EXPR. NULL if we aren't inside a loop. */
1230 vec<tree> *save_exprs;
1231 /* The CONSTRUCTOR we're currently building up for an aggregate
1232 initializer. */
1233 tree ctor;
1234 /* The object we're building the CONSTRUCTOR for. */
1235 tree object;
1236 /* If inside SWITCH_EXPR. */
1237 constexpr_switch_state *css_state;
1238 /* The aggregate initialization context inside which this one is nested. This
1239 is used by lookup_placeholder to resolve PLACEHOLDER_EXPRs. */
1240 const constexpr_ctx *parent;
1242 /* Whether we should error on a non-constant expression or fail quietly.
1243 This flag needs to be here, but some of the others could move to global
1244 if they get larger than a word. */
1245 bool quiet;
1246 /* Whether we are strictly conforming to constant expression rules or
1247 trying harder to get a constant value. */
1248 bool strict;
1249 /* Whether __builtin_is_constant_evaluated () should be true. */
1250 bool manifestly_const_eval;
1253 /* This internal flag controls whether we should avoid doing anything during
1254 constexpr evaluation that would cause extra DECL_UID generation, such as
1255 template instantiation and function body copying. */
1257 static bool uid_sensitive_constexpr_evaluation_value;
1259 /* An internal counter that keeps track of the number of times
1260 uid_sensitive_constexpr_evaluation_p returned true. */
1262 static unsigned uid_sensitive_constexpr_evaluation_true_counter;
1264 /* The accessor for uid_sensitive_constexpr_evaluation_value which also
1265 increments the corresponding counter. */
1267 static bool
1268 uid_sensitive_constexpr_evaluation_p ()
1270 if (uid_sensitive_constexpr_evaluation_value)
1272 ++uid_sensitive_constexpr_evaluation_true_counter;
1273 return true;
1275 else
1276 return false;
1279 /* The default constructor for uid_sensitive_constexpr_evaluation_sentinel
1280 enables the internal flag for uid_sensitive_constexpr_evaluation_p
1281 during the lifetime of the sentinel object. Upon its destruction, the
1282 previous value of uid_sensitive_constexpr_evaluation_p is restored. */
1284 uid_sensitive_constexpr_evaluation_sentinel
1285 ::uid_sensitive_constexpr_evaluation_sentinel ()
1286 : ovr (uid_sensitive_constexpr_evaluation_value, true)
1290 /* The default constructor for uid_sensitive_constexpr_evaluation_checker
1291 records the current number of times that uid_sensitive_constexpr_evaluation_p
1292 has been called and returned true. */
1294 uid_sensitive_constexpr_evaluation_checker
1295 ::uid_sensitive_constexpr_evaluation_checker ()
1296 : saved_counter (uid_sensitive_constexpr_evaluation_true_counter)
1300 /* Returns true iff uid_sensitive_constexpr_evaluation_p is true, and
1301 some constexpr evaluation was restricted due to u_s_c_e_p being called
1302 and returning true during the lifetime of this checker object. */
1304 bool
1305 uid_sensitive_constexpr_evaluation_checker::evaluation_restricted_p () const
1307 return (uid_sensitive_constexpr_evaluation_value
1308 && saved_counter != uid_sensitive_constexpr_evaluation_true_counter);
1312 /* A table of all constexpr calls that have been evaluated by the
1313 compiler in this translation unit. */
1315 static GTY (()) hash_table<constexpr_call_hasher> *constexpr_call_table;
1317 /* Compute a hash value for a constexpr call representation. */
1319 inline hashval_t
1320 constexpr_call_hasher::hash (constexpr_call *info)
1322 return info->hash;
1325 /* Return true if the objects pointed to by P and Q represent calls
1326 to the same constexpr function with the same arguments.
1327 Otherwise, return false. */
1329 bool
1330 constexpr_call_hasher::equal (constexpr_call *lhs, constexpr_call *rhs)
1332 if (lhs == rhs)
1333 return true;
1334 if (lhs->hash != rhs->hash)
1335 return false;
1336 if (lhs->manifestly_const_eval != rhs->manifestly_const_eval)
1337 return false;
1338 if (!constexpr_fundef_hasher::equal (lhs->fundef, rhs->fundef))
1339 return false;
1340 return cp_tree_equal (lhs->bindings, rhs->bindings);
1343 /* Initialize the constexpr call table, if needed. */
1345 static void
1346 maybe_initialize_constexpr_call_table (void)
1348 if (constexpr_call_table == NULL)
1349 constexpr_call_table = hash_table<constexpr_call_hasher>::create_ggc (101);
1352 /* During constexpr CALL_EXPR evaluation, to avoid issues with sharing when
1353 a function happens to get called recursively, we unshare the callee
1354 function's body and evaluate this unshared copy instead of evaluating the
1355 original body.
1357 FUNDEF_COPIES_TABLE is a per-function freelist of these unshared function
1358 copies. The underlying data structure of FUNDEF_COPIES_TABLE is a hash_map
1359 that's keyed off of the original FUNCTION_DECL and whose value is a
1360 TREE_LIST of this function's unused copies awaiting reuse.
1362 This is not GC-deletable to avoid GC affecting UID generation. */
1364 static GTY(()) decl_tree_map *fundef_copies_table;
1366 /* Reuse a copy or create a new unshared copy of the function FUN.
1367 Return this copy. We use a TREE_LIST whose PURPOSE is body, VALUE
1368 is parms, TYPE is result. */
1370 static tree
1371 get_fundef_copy (constexpr_fundef *fundef)
1373 tree copy;
1374 bool existed;
1375 tree *slot = &(hash_map_safe_get_or_insert<hm_ggc>
1376 (fundef_copies_table, fundef->decl, &existed, 127));
1378 if (!existed)
1380 /* There is no cached function available, or in use. We can use
1381 the function directly. That the slot is now created records
1382 that this function is now in use. */
1383 copy = build_tree_list (fundef->body, fundef->parms);
1384 TREE_TYPE (copy) = fundef->result;
1386 else if (*slot == NULL_TREE)
1388 if (uid_sensitive_constexpr_evaluation_p ())
1389 return NULL_TREE;
1391 /* We've already used the function itself, so make a copy. */
1392 copy = build_tree_list (NULL, NULL);
1393 tree saved_body = DECL_SAVED_TREE (fundef->decl);
1394 tree saved_parms = DECL_ARGUMENTS (fundef->decl);
1395 tree saved_result = DECL_RESULT (fundef->decl);
1396 tree saved_fn = current_function_decl;
1397 DECL_SAVED_TREE (fundef->decl) = fundef->body;
1398 DECL_ARGUMENTS (fundef->decl) = fundef->parms;
1399 DECL_RESULT (fundef->decl) = fundef->result;
1400 current_function_decl = fundef->decl;
1401 TREE_PURPOSE (copy) = copy_fn (fundef->decl, TREE_VALUE (copy),
1402 TREE_TYPE (copy));
1403 current_function_decl = saved_fn;
1404 DECL_RESULT (fundef->decl) = saved_result;
1405 DECL_ARGUMENTS (fundef->decl) = saved_parms;
1406 DECL_SAVED_TREE (fundef->decl) = saved_body;
1408 else
1410 /* We have a cached function available. */
1411 copy = *slot;
1412 *slot = TREE_CHAIN (copy);
1415 return copy;
1418 /* Save the copy COPY of function FUN for later reuse by
1419 get_fundef_copy(). By construction, there will always be an entry
1420 to find. */
1422 static void
1423 save_fundef_copy (tree fun, tree copy)
1425 tree *slot = fundef_copies_table->get (fun);
1426 TREE_CHAIN (copy) = *slot;
1427 *slot = copy;
1430 /* Whether our evaluation wants a prvalue (e.g. CONSTRUCTOR or _CST),
1431 a glvalue (e.g. VAR_DECL or _REF), or nothing. */
1433 enum value_cat {
1434 vc_prvalue = 0,
1435 vc_glvalue = 1,
1436 vc_discard = 2
1439 static tree cxx_eval_constant_expression (const constexpr_ctx *, tree,
1440 value_cat, bool *, bool *, tree * = NULL);
1441 static tree cxx_fold_indirect_ref (const constexpr_ctx *, location_t, tree, tree,
1442 bool * = NULL);
1443 static tree find_heap_var_refs (tree *, int *, void *);
1445 /* Attempt to evaluate T which represents a call to a builtin function.
1446 We assume here that all builtin functions evaluate to scalar types
1447 represented by _CST nodes. */
1449 static tree
1450 cxx_eval_builtin_function_call (const constexpr_ctx *ctx, tree t, tree fun,
1451 value_cat lval,
1452 bool *non_constant_p, bool *overflow_p)
1454 const int nargs = call_expr_nargs (t);
1455 tree *args = (tree *) alloca (nargs * sizeof (tree));
1456 tree new_call;
1457 int i;
1459 /* Don't fold __builtin_constant_p within a constexpr function. */
1460 bool bi_const_p = DECL_IS_BUILTIN_CONSTANT_P (fun);
1462 /* If we aren't requiring a constant expression, defer __builtin_constant_p
1463 in a constexpr function until we have values for the parameters. */
1464 if (bi_const_p
1465 && !ctx->manifestly_const_eval
1466 && current_function_decl
1467 && DECL_DECLARED_CONSTEXPR_P (current_function_decl))
1469 *non_constant_p = true;
1470 return t;
1473 /* For __builtin_is_constant_evaluated, defer it if not
1474 ctx->manifestly_const_eval (as sometimes we try to constant evaluate
1475 without manifestly_const_eval even expressions or parts thereof which
1476 will later be manifestly const_eval evaluated), otherwise fold it to
1477 true. */
1478 if (fndecl_built_in_p (fun, CP_BUILT_IN_IS_CONSTANT_EVALUATED,
1479 BUILT_IN_FRONTEND))
1481 if (!ctx->manifestly_const_eval)
1483 *non_constant_p = true;
1484 return t;
1486 return boolean_true_node;
1489 if (fndecl_built_in_p (fun, CP_BUILT_IN_SOURCE_LOCATION, BUILT_IN_FRONTEND))
1491 temp_override<tree> ovr (current_function_decl);
1492 if (ctx->call && ctx->call->fundef)
1493 current_function_decl = ctx->call->fundef->decl;
1494 return fold_builtin_source_location (EXPR_LOCATION (t));
1497 int strops = 0;
1498 int strret = 0;
1499 if (fndecl_built_in_p (fun, BUILT_IN_NORMAL))
1500 switch (DECL_FUNCTION_CODE (fun))
1502 case BUILT_IN_STRLEN:
1503 case BUILT_IN_STRNLEN:
1504 strops = 1;
1505 break;
1506 case BUILT_IN_MEMCHR:
1507 case BUILT_IN_STRCHR:
1508 case BUILT_IN_STRRCHR:
1509 strops = 1;
1510 strret = 1;
1511 break;
1512 case BUILT_IN_MEMCMP:
1513 case BUILT_IN_STRCMP:
1514 strops = 2;
1515 break;
1516 case BUILT_IN_STRSTR:
1517 strops = 2;
1518 strret = 1;
1519 break;
1520 case BUILT_IN_ASAN_POINTER_COMPARE:
1521 case BUILT_IN_ASAN_POINTER_SUBTRACT:
1522 /* These builtins shall be ignored during constant expression
1523 evaluation. */
1524 return void_node;
1525 case BUILT_IN_UNREACHABLE:
1526 case BUILT_IN_TRAP:
1527 if (!*non_constant_p && !ctx->quiet)
1529 /* Do not allow__builtin_unreachable in constexpr function.
1530 The __builtin_unreachable call with BUILTINS_LOCATION
1531 comes from cp_maybe_instrument_return. */
1532 if (EXPR_LOCATION (t) == BUILTINS_LOCATION)
1533 error ("%<constexpr%> call flows off the end of the function");
1534 else
1535 error ("%q+E is not a constant expression", t);
1537 *non_constant_p = true;
1538 return t;
1539 default:
1540 break;
1543 /* Be permissive for arguments to built-ins; __builtin_constant_p should
1544 return constant false for a non-constant argument. */
1545 constexpr_ctx new_ctx = *ctx;
1546 new_ctx.quiet = true;
1547 for (i = 0; i < nargs; ++i)
1549 tree arg = CALL_EXPR_ARG (t, i);
1550 tree oarg = arg;
1552 /* To handle string built-ins we need to pass ADDR_EXPR<STRING_CST> since
1553 expand_builtin doesn't know how to look in the values table. */
1554 bool strop = i < strops;
1555 if (strop)
1557 STRIP_NOPS (arg);
1558 if (TREE_CODE (arg) == ADDR_EXPR)
1559 arg = TREE_OPERAND (arg, 0);
1560 else
1561 strop = false;
1564 /* If builtin_valid_in_constant_expr_p is true,
1565 potential_constant_expression_1 has not recursed into the arguments
1566 of the builtin, verify it here. */
1567 if (!builtin_valid_in_constant_expr_p (fun)
1568 || potential_constant_expression (arg))
1570 bool dummy1 = false, dummy2 = false;
1571 arg = cxx_eval_constant_expression (&new_ctx, arg, vc_prvalue,
1572 &dummy1, &dummy2);
1575 if (bi_const_p)
1576 /* For __builtin_constant_p, fold all expressions with constant values
1577 even if they aren't C++ constant-expressions. */
1578 arg = cp_fold_rvalue (arg);
1579 else if (strop)
1581 if (TREE_CODE (arg) == CONSTRUCTOR)
1582 arg = braced_lists_to_strings (TREE_TYPE (arg), arg);
1583 if (TREE_CODE (arg) == STRING_CST)
1584 arg = build_address (arg);
1585 else
1586 arg = oarg;
1589 args[i] = arg;
1592 bool save_ffbcp = force_folding_builtin_constant_p;
1593 force_folding_builtin_constant_p |= ctx->manifestly_const_eval;
1594 tree save_cur_fn = current_function_decl;
1595 /* Return name of ctx->call->fundef->decl for __builtin_FUNCTION (). */
1596 if (fndecl_built_in_p (fun, BUILT_IN_FUNCTION)
1597 && ctx->call
1598 && ctx->call->fundef)
1599 current_function_decl = ctx->call->fundef->decl;
1600 if (fndecl_built_in_p (fun,
1601 CP_BUILT_IN_IS_POINTER_INTERCONVERTIBLE_WITH_CLASS,
1602 BUILT_IN_FRONTEND))
1604 location_t loc = EXPR_LOCATION (t);
1605 if (nargs >= 1)
1606 VERIFY_CONSTANT (args[0]);
1607 new_call
1608 = fold_builtin_is_pointer_inverconvertible_with_class (loc, nargs,
1609 args);
1611 else if (fndecl_built_in_p (fun,
1612 CP_BUILT_IN_IS_CORRESPONDING_MEMBER,
1613 BUILT_IN_FRONTEND))
1615 location_t loc = EXPR_LOCATION (t);
1616 if (nargs >= 2)
1618 VERIFY_CONSTANT (args[0]);
1619 VERIFY_CONSTANT (args[1]);
1621 new_call = fold_builtin_is_corresponding_member (loc, nargs, args);
1623 else
1624 new_call = fold_builtin_call_array (EXPR_LOCATION (t), TREE_TYPE (t),
1625 CALL_EXPR_FN (t), nargs, args);
1626 current_function_decl = save_cur_fn;
1627 force_folding_builtin_constant_p = save_ffbcp;
1628 if (new_call == NULL)
1630 if (!*non_constant_p && !ctx->quiet)
1632 new_call = build_call_array_loc (EXPR_LOCATION (t), TREE_TYPE (t),
1633 CALL_EXPR_FN (t), nargs, args);
1634 error ("%q+E is not a constant expression", new_call);
1636 *non_constant_p = true;
1637 return t;
1640 if (!potential_constant_expression (new_call))
1642 if (!*non_constant_p && !ctx->quiet)
1643 error ("%q+E is not a constant expression", new_call);
1644 *non_constant_p = true;
1645 return t;
1648 if (strret)
1650 /* memchr returns a pointer into the first argument, but we replaced the
1651 argument above with a STRING_CST; put it back it now. */
1652 tree op = CALL_EXPR_ARG (t, strret-1);
1653 STRIP_NOPS (new_call);
1654 if (TREE_CODE (new_call) == POINTER_PLUS_EXPR)
1655 TREE_OPERAND (new_call, 0) = op;
1656 else if (TREE_CODE (new_call) == ADDR_EXPR)
1657 new_call = op;
1660 return cxx_eval_constant_expression (&new_ctx, new_call, lval,
1661 non_constant_p, overflow_p);
1664 /* TEMP is the constant value of a temporary object of type TYPE. Adjust
1665 the type of the value to match. */
1667 static tree
1668 adjust_temp_type (tree type, tree temp)
1670 if (same_type_p (TREE_TYPE (temp), type))
1671 return temp;
1672 /* Avoid wrapping an aggregate value in a NOP_EXPR. */
1673 if (TREE_CODE (temp) == CONSTRUCTOR)
1675 /* build_constructor wouldn't retain various CONSTRUCTOR flags. */
1676 tree t = copy_node (temp);
1677 TREE_TYPE (t) = type;
1678 return t;
1680 if (TREE_CODE (temp) == EMPTY_CLASS_EXPR)
1681 return build0 (EMPTY_CLASS_EXPR, type);
1682 gcc_assert (scalarish_type_p (type));
1683 /* Now we know we're dealing with a scalar, and a prvalue of non-class
1684 type is cv-unqualified. */
1685 return cp_fold_convert (cv_unqualified (type), temp);
1688 /* If T is a CONSTRUCTOR, return an unshared copy of T and any
1689 sub-CONSTRUCTORs. Otherwise return T.
1691 We use this whenever we initialize an object as a whole, whether it's a
1692 parameter, a local variable, or a subobject, so that subsequent
1693 modifications don't affect other places where it was used. */
1695 tree
1696 unshare_constructor (tree t MEM_STAT_DECL)
1698 if (!t || TREE_CODE (t) != CONSTRUCTOR)
1699 return t;
1700 auto_vec <tree*, 4> ptrs;
1701 ptrs.safe_push (&t);
1702 while (!ptrs.is_empty ())
1704 tree *p = ptrs.pop ();
1705 tree n = copy_node (*p PASS_MEM_STAT);
1706 CONSTRUCTOR_ELTS (n) = vec_safe_copy (CONSTRUCTOR_ELTS (*p) PASS_MEM_STAT);
1707 *p = n;
1708 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (n);
1709 constructor_elt *ce;
1710 for (HOST_WIDE_INT i = 0; vec_safe_iterate (v, i, &ce); ++i)
1711 if (ce->value && TREE_CODE (ce->value) == CONSTRUCTOR)
1712 ptrs.safe_push (&ce->value);
1714 return t;
1717 /* If T is a CONSTRUCTOR, ggc_free T and any sub-CONSTRUCTORs. */
1719 static void
1720 free_constructor (tree t)
1722 if (!t || TREE_CODE (t) != CONSTRUCTOR)
1723 return;
1724 releasing_vec ctors;
1725 vec_safe_push (ctors, t);
1726 while (!ctors->is_empty ())
1728 tree c = ctors->pop ();
1729 if (vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (c))
1731 constructor_elt *ce;
1732 for (HOST_WIDE_INT i = 0; vec_safe_iterate (elts, i, &ce); ++i)
1733 if (TREE_CODE (ce->value) == CONSTRUCTOR)
1734 vec_safe_push (ctors, ce->value);
1735 ggc_free (elts);
1737 ggc_free (c);
1741 /* Helper function of cxx_bind_parameters_in_call. Return non-NULL
1742 if *TP is address of a static variable (or part of it) currently being
1743 constructed or of a heap artificial variable. */
1745 static tree
1746 addr_of_non_const_var (tree *tp, int *walk_subtrees, void *data)
1748 if (TREE_CODE (*tp) == ADDR_EXPR)
1749 if (tree var = get_base_address (TREE_OPERAND (*tp, 0)))
1750 if (VAR_P (var) && TREE_STATIC (var))
1752 if (DECL_NAME (var) == heap_uninit_identifier
1753 || DECL_NAME (var) == heap_identifier
1754 || DECL_NAME (var) == heap_vec_uninit_identifier
1755 || DECL_NAME (var) == heap_vec_identifier)
1756 return var;
1758 constexpr_global_ctx *global = (constexpr_global_ctx *) data;
1759 if (global->get_value (var))
1760 return var;
1762 if (TYPE_P (*tp))
1763 *walk_subtrees = false;
1764 return NULL_TREE;
1767 /* Subroutine of cxx_eval_call_expression.
1768 We are processing a call expression (either CALL_EXPR or
1769 AGGR_INIT_EXPR) in the context of CTX. Evaluate
1770 all arguments and bind their values to correspondings
1771 parameters, making up the NEW_CALL context. */
1773 static tree
1774 cxx_bind_parameters_in_call (const constexpr_ctx *ctx, tree t, tree fun,
1775 bool *non_constant_p, bool *overflow_p,
1776 bool *non_constant_args)
1778 const int nargs = call_expr_nargs (t);
1779 tree parms = DECL_ARGUMENTS (fun);
1780 int i;
1781 /* We don't record ellipsis args below. */
1782 int nparms = list_length (parms);
1783 int nbinds = nargs < nparms ? nargs : nparms;
1784 tree binds = make_tree_vec (nbinds);
1785 for (i = 0; i < nargs; ++i)
1787 tree x, arg;
1788 tree type = parms ? TREE_TYPE (parms) : void_type_node;
1789 if (parms && DECL_BY_REFERENCE (parms))
1790 type = TREE_TYPE (type);
1791 x = get_nth_callarg (t, i);
1792 /* For member function, the first argument is a pointer to the implied
1793 object. For a constructor, it might still be a dummy object, in
1794 which case we get the real argument from ctx. */
1795 if (i == 0 && DECL_CONSTRUCTOR_P (fun)
1796 && is_dummy_object (x))
1798 x = ctx->object;
1799 x = build_address (x);
1801 if (TREE_ADDRESSABLE (type))
1802 /* Undo convert_for_arg_passing work here. */
1803 x = convert_from_reference (x);
1804 /* Normally we would strip a TARGET_EXPR in an initialization context
1805 such as this, but here we do the elision differently: we keep the
1806 TARGET_EXPR, and use its CONSTRUCTOR as the value of the parm. */
1807 arg = cxx_eval_constant_expression (ctx, x, vc_prvalue,
1808 non_constant_p, overflow_p);
1809 /* Don't VERIFY_CONSTANT here. */
1810 if (*non_constant_p && ctx->quiet)
1811 break;
1812 /* Just discard ellipsis args after checking their constantitude. */
1813 if (!parms)
1814 continue;
1816 if (!*non_constant_p)
1818 /* Make sure the binding has the same type as the parm. But
1819 only for constant args. */
1820 if (!TYPE_REF_P (type))
1821 arg = adjust_temp_type (type, arg);
1822 if (!TREE_CONSTANT (arg))
1823 *non_constant_args = true;
1824 else if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
1825 /* The destructor needs to see any modifications the callee makes
1826 to the argument. */
1827 *non_constant_args = true;
1828 /* If arg is or contains address of a heap artificial variable or
1829 of a static variable being constructed, avoid caching the
1830 function call, as those variables might be modified by the
1831 function, or might be modified by the callers in between
1832 the cached function and just read by the function. */
1833 else if (!*non_constant_args
1834 && cp_walk_tree (&arg, addr_of_non_const_var, ctx->global,
1835 NULL))
1836 *non_constant_args = true;
1838 /* For virtual calls, adjust the this argument, so that it is
1839 the object on which the method is called, rather than
1840 one of its bases. */
1841 if (i == 0 && DECL_VIRTUAL_P (fun))
1843 tree addr = arg;
1844 STRIP_NOPS (addr);
1845 if (TREE_CODE (addr) == ADDR_EXPR)
1847 tree obj = TREE_OPERAND (addr, 0);
1848 while (TREE_CODE (obj) == COMPONENT_REF
1849 && DECL_FIELD_IS_BASE (TREE_OPERAND (obj, 1))
1850 && !same_type_ignoring_top_level_qualifiers_p
1851 (TREE_TYPE (obj), DECL_CONTEXT (fun)))
1852 obj = TREE_OPERAND (obj, 0);
1853 if (obj != TREE_OPERAND (addr, 0))
1854 arg = build_fold_addr_expr_with_type (obj,
1855 TREE_TYPE (arg));
1858 TREE_VEC_ELT (binds, i) = arg;
1860 parms = TREE_CHAIN (parms);
1863 return binds;
1866 /* Variables and functions to manage constexpr call expansion context.
1867 These do not need to be marked for PCH or GC. */
1869 /* FIXME remember and print actual constant arguments. */
1870 static vec<tree> call_stack;
1871 static int call_stack_tick;
1872 static int last_cx_error_tick;
1874 static int
1875 push_cx_call_context (tree call)
1877 ++call_stack_tick;
1878 if (!EXPR_HAS_LOCATION (call))
1879 SET_EXPR_LOCATION (call, input_location);
1880 call_stack.safe_push (call);
1881 int len = call_stack.length ();
1882 if (len > max_constexpr_depth)
1883 return false;
1884 return len;
1887 static void
1888 pop_cx_call_context (void)
1890 ++call_stack_tick;
1891 call_stack.pop ();
1894 vec<tree>
1895 cx_error_context (void)
1897 vec<tree> r = vNULL;
1898 if (call_stack_tick != last_cx_error_tick
1899 && !call_stack.is_empty ())
1900 r = call_stack;
1901 last_cx_error_tick = call_stack_tick;
1902 return r;
1905 /* E is an operand of a failed assertion, fold it either with or without
1906 constexpr context. */
1908 static tree
1909 fold_operand (tree e, const constexpr_ctx *ctx)
1911 if (ctx)
1913 bool new_non_constant_p = false, new_overflow_p = false;
1914 e = cxx_eval_constant_expression (ctx, e, vc_prvalue,
1915 &new_non_constant_p,
1916 &new_overflow_p);
1918 else
1919 e = fold_non_dependent_expr (e, tf_none, /*manifestly_const_eval=*/true);
1920 return e;
1923 /* If we have a condition in conjunctive normal form (CNF), find the first
1924 failing clause. In other words, given an expression like
1926 true && true && false && true && false
1928 return the first 'false'. EXPR is the expression. */
1930 static tree
1931 find_failing_clause_r (const constexpr_ctx *ctx, tree expr)
1933 if (TREE_CODE (expr) == TRUTH_ANDIF_EXPR)
1935 /* First check the left side... */
1936 tree e = find_failing_clause_r (ctx, TREE_OPERAND (expr, 0));
1937 if (e == NULL_TREE)
1938 /* ...if we didn't find a false clause, check the right side. */
1939 e = find_failing_clause_r (ctx, TREE_OPERAND (expr, 1));
1940 return e;
1942 tree e = contextual_conv_bool (expr, tf_none);
1943 e = fold_operand (e, ctx);
1944 if (integer_zerop (e))
1945 /* This is the failing clause. */
1946 return expr;
1947 return NULL_TREE;
1950 /* Wrapper for find_failing_clause_r. */
1952 tree
1953 find_failing_clause (const constexpr_ctx *ctx, tree expr)
1955 if (TREE_CODE (expr) == TRUTH_ANDIF_EXPR)
1956 if (tree e = find_failing_clause_r (ctx, expr))
1957 expr = e;
1958 return expr;
1961 /* Emit additional diagnostics for failing condition BAD.
1962 Used by finish_static_assert and IFN_ASSUME constexpr diagnostics.
1963 If SHOW_EXPR_P is true, print the condition (because it was
1964 instantiation-dependent). */
1966 void
1967 diagnose_failing_condition (tree bad, location_t cloc, bool show_expr_p,
1968 const constexpr_ctx *ctx /* = nullptr */)
1970 /* Nobody wants to see the artificial (bool) cast. */
1971 bad = tree_strip_nop_conversions (bad);
1972 if (TREE_CODE (bad) == CLEANUP_POINT_EXPR)
1973 bad = TREE_OPERAND (bad, 0);
1975 /* Actually explain the failure if this is a concept check or a
1976 requires-expression. */
1977 if (concept_check_p (bad) || TREE_CODE (bad) == REQUIRES_EXPR)
1978 diagnose_constraints (cloc, bad, NULL_TREE);
1979 else if (COMPARISON_CLASS_P (bad)
1980 && ARITHMETIC_TYPE_P (TREE_TYPE (TREE_OPERAND (bad, 0))))
1982 tree op0 = fold_operand (TREE_OPERAND (bad, 0), ctx);
1983 tree op1 = fold_operand (TREE_OPERAND (bad, 1), ctx);
1984 tree cond = build2 (TREE_CODE (bad), boolean_type_node, op0, op1);
1985 inform (cloc, "the comparison reduces to %qE", cond);
1987 else if (show_expr_p)
1988 inform (cloc, "%qE evaluates to false", bad);
1991 /* Evaluate a call T to a GCC internal function when possible and return
1992 the evaluated result or, under the control of CTX, give an error, set
1993 NON_CONSTANT_P, and return the unevaluated call T otherwise. */
1995 static tree
1996 cxx_eval_internal_function (const constexpr_ctx *ctx, tree t,
1997 value_cat lval,
1998 bool *non_constant_p, bool *overflow_p)
2000 enum tree_code opcode = ERROR_MARK;
2002 switch (CALL_EXPR_IFN (t))
2004 case IFN_UBSAN_NULL:
2005 case IFN_UBSAN_BOUNDS:
2006 case IFN_UBSAN_VPTR:
2007 case IFN_FALLTHROUGH:
2008 return void_node;
2010 case IFN_ASSUME:
2011 if (potential_rvalue_constant_expression (CALL_EXPR_ARG (t, 0)))
2013 constexpr_ctx new_ctx = *ctx;
2014 new_ctx.quiet = true;
2015 tree arg = CALL_EXPR_ARG (t, 0);
2016 bool new_non_constant_p = false, new_overflow_p = false;
2017 /* Avoid modification of existing values. */
2018 modifiable_tracker ms (new_ctx.global);
2019 arg = cxx_eval_constant_expression (&new_ctx, arg, vc_prvalue,
2020 &new_non_constant_p,
2021 &new_overflow_p);
2022 if (!new_non_constant_p && !new_overflow_p && integer_zerop (arg))
2024 if (!*non_constant_p && !ctx->quiet)
2026 /* See if we can find which clause was failing
2027 (for logical AND). */
2028 tree bad = find_failing_clause (&new_ctx,
2029 CALL_EXPR_ARG (t, 0));
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, EXPR_LOCATION (t));
2034 auto_diagnostic_group d;
2036 /* Report the error. */
2037 error_at (cloc,
2038 "failed %<assume%> attribute assumption");
2039 diagnose_failing_condition (bad, cloc, false, &new_ctx);
2042 *non_constant_p = true;
2043 return t;
2046 return void_node;
2048 case IFN_ADD_OVERFLOW:
2049 opcode = PLUS_EXPR;
2050 break;
2051 case IFN_SUB_OVERFLOW:
2052 opcode = MINUS_EXPR;
2053 break;
2054 case IFN_MUL_OVERFLOW:
2055 opcode = MULT_EXPR;
2056 break;
2058 case IFN_LAUNDER:
2059 return cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0),
2060 vc_prvalue, non_constant_p,
2061 overflow_p);
2063 case IFN_VEC_CONVERT:
2065 tree arg = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0),
2066 vc_prvalue, non_constant_p,
2067 overflow_p);
2068 if (TREE_CODE (arg) == VECTOR_CST)
2069 if (tree r = fold_const_call (CFN_VEC_CONVERT, TREE_TYPE (t), arg))
2070 return r;
2072 /* FALLTHRU */
2074 default:
2075 if (!ctx->quiet)
2076 error_at (cp_expr_loc_or_input_loc (t),
2077 "call to internal function %qE", t);
2078 *non_constant_p = true;
2079 return t;
2082 /* Evaluate constant arguments using OPCODE and return a complex
2083 number containing the result and the overflow bit. */
2084 tree arg0 = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0), lval,
2085 non_constant_p, overflow_p);
2086 tree arg1 = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 1), lval,
2087 non_constant_p, overflow_p);
2089 if (TREE_CODE (arg0) == INTEGER_CST && TREE_CODE (arg1) == INTEGER_CST)
2091 location_t loc = cp_expr_loc_or_input_loc (t);
2092 tree type = TREE_TYPE (TREE_TYPE (t));
2093 tree result = fold_binary_loc (loc, opcode, type,
2094 fold_convert_loc (loc, type, arg0),
2095 fold_convert_loc (loc, type, arg1));
2096 tree ovf
2097 = build_int_cst (type, arith_overflowed_p (opcode, type, arg0, arg1));
2098 /* Reset TREE_OVERFLOW to avoid warnings for the overflow. */
2099 if (TREE_OVERFLOW (result))
2100 TREE_OVERFLOW (result) = 0;
2102 return build_complex (TREE_TYPE (t), result, ovf);
2105 *non_constant_p = true;
2106 return t;
2109 /* Clean CONSTRUCTOR_NO_CLEARING from CTOR and its sub-aggregates. */
2111 static void
2112 clear_no_implicit_zero (tree ctor)
2114 if (CONSTRUCTOR_NO_CLEARING (ctor))
2116 CONSTRUCTOR_NO_CLEARING (ctor) = false;
2117 for (auto &e: CONSTRUCTOR_ELTS (ctor))
2118 if (TREE_CODE (e.value) == CONSTRUCTOR)
2119 clear_no_implicit_zero (e.value);
2123 /* Complain about a const object OBJ being modified in a constant expression.
2124 EXPR is the MODIFY_EXPR expression performing the modification. */
2126 static void
2127 modifying_const_object_error (tree expr, tree obj)
2129 location_t loc = cp_expr_loc_or_input_loc (expr);
2130 auto_diagnostic_group d;
2131 error_at (loc, "modifying a const object %qE is not allowed in "
2132 "a constant expression", TREE_OPERAND (expr, 0));
2133 inform (location_of (obj), "originally declared %<const%> here");
2136 /* Return true if FNDECL is a replaceable global allocation function that
2137 should be useable during constant expression evaluation. */
2139 static inline bool
2140 cxx_replaceable_global_alloc_fn (tree fndecl)
2142 return (cxx_dialect >= cxx20
2143 && IDENTIFIER_NEWDEL_OP_P (DECL_NAME (fndecl))
2144 && CP_DECL_CONTEXT (fndecl) == global_namespace
2145 && (DECL_IS_REPLACEABLE_OPERATOR_NEW_P (fndecl)
2146 || DECL_IS_OPERATOR_DELETE_P (fndecl)));
2149 /* Return true if FNDECL is a placement new function that should be
2150 useable during constant expression evaluation of std::construct_at. */
2152 static inline bool
2153 cxx_placement_new_fn (tree fndecl)
2155 if (cxx_dialect >= cxx20
2156 && IDENTIFIER_NEW_OP_P (DECL_NAME (fndecl))
2157 && CP_DECL_CONTEXT (fndecl) == global_namespace
2158 && !DECL_IS_REPLACEABLE_OPERATOR_NEW_P (fndecl)
2159 && TREE_CODE (TREE_TYPE (fndecl)) == FUNCTION_TYPE)
2161 tree first_arg = TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (fndecl)));
2162 if (TREE_VALUE (first_arg) == ptr_type_node
2163 && TREE_CHAIN (first_arg) == void_list_node)
2164 return true;
2166 return false;
2169 /* Return true if FNDECL is std::construct_at. */
2171 static inline bool
2172 is_std_construct_at (tree fndecl)
2174 if (!decl_in_std_namespace_p (fndecl))
2175 return false;
2177 tree name = DECL_NAME (fndecl);
2178 return name && id_equal (name, "construct_at");
2181 /* Overload for the above taking constexpr_call*. */
2183 static inline bool
2184 is_std_construct_at (const constexpr_call *call)
2186 return (call
2187 && call->fundef
2188 && is_std_construct_at (call->fundef->decl));
2191 /* Return true if FNDECL is std::allocator<T>::{,de}allocate. */
2193 static inline bool
2194 is_std_allocator_allocate (tree fndecl)
2196 tree name = DECL_NAME (fndecl);
2197 if (name == NULL_TREE
2198 || !(id_equal (name, "allocate") || id_equal (name, "deallocate")))
2199 return false;
2201 tree ctx = DECL_CONTEXT (fndecl);
2202 if (ctx == NULL_TREE || !CLASS_TYPE_P (ctx) || !TYPE_MAIN_DECL (ctx))
2203 return false;
2205 tree decl = TYPE_MAIN_DECL (ctx);
2206 name = DECL_NAME (decl);
2207 if (name == NULL_TREE || !id_equal (name, "allocator"))
2208 return false;
2210 return decl_in_std_namespace_p (decl);
2213 /* Overload for the above taking constexpr_call*. */
2215 static inline bool
2216 is_std_allocator_allocate (const constexpr_call *call)
2218 return (call
2219 && call->fundef
2220 && is_std_allocator_allocate (call->fundef->decl));
2223 /* Return true if FNDECL is __dynamic_cast. */
2225 static inline bool
2226 cxx_dynamic_cast_fn_p (tree fndecl)
2228 return (cxx_dialect >= cxx20
2229 && id_equal (DECL_NAME (fndecl), "__dynamic_cast")
2230 && CP_DECL_CONTEXT (fndecl) == abi_node);
2233 /* Often, we have an expression in the form of address + offset, e.g.
2234 "&_ZTV1A + 16". Extract the object from it, i.e. "_ZTV1A". */
2236 static tree
2237 extract_obj_from_addr_offset (tree expr)
2239 if (TREE_CODE (expr) == POINTER_PLUS_EXPR)
2240 expr = TREE_OPERAND (expr, 0);
2241 STRIP_NOPS (expr);
2242 if (TREE_CODE (expr) == ADDR_EXPR)
2243 expr = TREE_OPERAND (expr, 0);
2244 return expr;
2247 /* Given a PATH like
2249 g.D.2181.D.2154.D.2102.D.2093
2251 find a component with type TYPE. Return NULL_TREE if not found, and
2252 error_mark_node if the component is not accessible. If STOP is non-null,
2253 this function will return NULL_TREE if STOP is found before TYPE. */
2255 static tree
2256 get_component_with_type (tree path, tree type, tree stop)
2258 while (true)
2260 if (same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (path), type))
2261 /* Found it. */
2262 return path;
2263 else if (stop
2264 && (same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (path),
2265 stop)))
2266 return NULL_TREE;
2267 else if (TREE_CODE (path) == COMPONENT_REF
2268 && DECL_FIELD_IS_BASE (TREE_OPERAND (path, 1)))
2270 /* We need to check that the component we're accessing is in fact
2271 accessible. */
2272 if (TREE_PRIVATE (TREE_OPERAND (path, 1))
2273 || TREE_PROTECTED (TREE_OPERAND (path, 1)))
2274 return error_mark_node;
2275 path = TREE_OPERAND (path, 0);
2277 else
2278 return NULL_TREE;
2282 /* Evaluate a call to __dynamic_cast (permitted by P1327R1).
2284 The declaration of __dynamic_cast is:
2286 void* __dynamic_cast (const void* __src_ptr,
2287 const __class_type_info* __src_type,
2288 const __class_type_info* __dst_type,
2289 ptrdiff_t __src2dst);
2291 where src2dst has the following possible values
2293 >-1: src_type is a unique public non-virtual base of dst_type
2294 dst_ptr + src2dst == src_ptr
2295 -1: unspecified relationship
2296 -2: src_type is not a public base of dst_type
2297 -3: src_type is a multiple public non-virtual base of dst_type
2299 Since literal types can't have virtual bases, we only expect hint >=0,
2300 -2, or -3. */
2302 static tree
2303 cxx_eval_dynamic_cast_fn (const constexpr_ctx *ctx, tree call,
2304 bool *non_constant_p, bool *overflow_p)
2306 /* T will be something like
2307 __dynamic_cast ((B*) b, &_ZTI1B, &_ZTI1D, 8)
2308 dismantle it. */
2309 gcc_assert (call_expr_nargs (call) == 4);
2310 tsubst_flags_t complain = ctx->quiet ? tf_none : tf_warning_or_error;
2311 tree obj = CALL_EXPR_ARG (call, 0);
2312 tree type = CALL_EXPR_ARG (call, 2);
2313 HOST_WIDE_INT hint = int_cst_value (CALL_EXPR_ARG (call, 3));
2314 location_t loc = cp_expr_loc_or_input_loc (call);
2316 /* Get the target type of the dynamic_cast. */
2317 gcc_assert (TREE_CODE (type) == ADDR_EXPR);
2318 type = TREE_OPERAND (type, 0);
2319 type = TREE_TYPE (DECL_NAME (type));
2321 /* TYPE can only be either T* or T&. We can't know which of these it
2322 is by looking at TYPE, but OBJ will be "(T*) x" in the first case,
2323 and something like "(T*)(T&)(T*) x" in the second case. */
2324 bool reference_p = false;
2325 while (CONVERT_EXPR_P (obj) || TREE_CODE (obj) == SAVE_EXPR)
2327 reference_p |= TYPE_REF_P (TREE_TYPE (obj));
2328 obj = TREE_OPERAND (obj, 0);
2331 /* Evaluate the object so that we know its dynamic type. */
2332 obj = cxx_eval_constant_expression (ctx, obj, vc_prvalue, non_constant_p,
2333 overflow_p);
2334 if (*non_constant_p)
2335 return call;
2337 /* We expect OBJ to be in form of &d.D.2102 when HINT == 0,
2338 but when HINT is > 0, it can also be something like
2339 &d.D.2102 + 18446744073709551608, which includes the BINFO_OFFSET. */
2340 obj = extract_obj_from_addr_offset (obj);
2341 const tree objtype = TREE_TYPE (obj);
2342 /* If OBJ doesn't refer to a base field, we're done. */
2343 if (tree t = (TREE_CODE (obj) == COMPONENT_REF
2344 ? TREE_OPERAND (obj, 1) : obj))
2345 if (TREE_CODE (t) != FIELD_DECL || !DECL_FIELD_IS_BASE (t))
2347 if (reference_p)
2349 if (!ctx->quiet)
2351 error_at (loc, "reference %<dynamic_cast%> failed");
2352 inform (loc, "dynamic type %qT of its operand does "
2353 "not have a base class of type %qT",
2354 objtype, type);
2356 *non_constant_p = true;
2358 return integer_zero_node;
2361 /* [class.cdtor] When a dynamic_cast is used in a constructor ...
2362 or in a destructor ... if the operand of the dynamic_cast refers
2363 to the object under construction or destruction, this object is
2364 considered to be a most derived object that has the type of the
2365 constructor or destructor's class. */
2366 tree vtable = build_vfield_ref (obj, objtype);
2367 vtable = cxx_eval_constant_expression (ctx, vtable, vc_prvalue,
2368 non_constant_p, overflow_p);
2369 if (*non_constant_p)
2370 return call;
2371 /* With -fsanitize=vptr, we initialize all vtable pointers to null,
2372 so it's possible that we got a null pointer now. */
2373 if (integer_zerop (vtable))
2375 if (!ctx->quiet)
2376 error_at (loc, "virtual table pointer is used uninitialized");
2377 *non_constant_p = true;
2378 return integer_zero_node;
2380 /* VTABLE will be &_ZTV1A + 16 or similar, get _ZTV1A. */
2381 vtable = extract_obj_from_addr_offset (vtable);
2382 const tree mdtype = DECL_CONTEXT (vtable);
2384 /* Given dynamic_cast<T>(v),
2386 [expr.dynamic.cast] If C is the class type to which T points or refers,
2387 the runtime check logically executes as follows:
2389 If, in the most derived object pointed (referred) to by v, v points
2390 (refers) to a public base class subobject of a C object, and if only
2391 one object of type C is derived from the subobject pointed (referred)
2392 to by v the result points (refers) to that C object.
2394 In this case, HINT >= 0 or -3. */
2395 if (hint >= 0 || hint == -3)
2397 /* Look for a component with type TYPE. */
2398 tree t = get_component_with_type (obj, type, mdtype);
2399 /* If not accessible, give an error. */
2400 if (t == error_mark_node)
2402 if (reference_p)
2404 if (!ctx->quiet)
2406 error_at (loc, "reference %<dynamic_cast%> failed");
2407 inform (loc, "static type %qT of its operand is a "
2408 "non-public base class of dynamic type %qT",
2409 objtype, type);
2412 *non_constant_p = true;
2414 return integer_zero_node;
2416 else if (t)
2417 /* The result points to the TYPE object. */
2418 return cp_build_addr_expr (t, complain);
2419 /* Else, TYPE was not found, because the HINT turned out to be wrong.
2420 Fall through to the normal processing. */
2423 /* Otherwise, if v points (refers) to a public base class subobject of the
2424 most derived object, and the type of the most derived object has a base
2425 class, of type C, that is unambiguous and public, the result points
2426 (refers) to the C subobject of the most derived object.
2428 But it can also be an invalid case. */
2430 /* Get the most derived object. */
2431 obj = get_component_with_type (obj, mdtype, NULL_TREE);
2432 if (obj == error_mark_node)
2434 if (reference_p)
2436 if (!ctx->quiet)
2438 error_at (loc, "reference %<dynamic_cast%> failed");
2439 inform (loc, "static type %qT of its operand is a non-public"
2440 " base class of dynamic type %qT", objtype, mdtype);
2442 *non_constant_p = true;
2444 return integer_zero_node;
2446 else
2447 gcc_assert (obj);
2449 /* Check that the type of the most derived object has a base class
2450 of type TYPE that is unambiguous and public. */
2451 base_kind b_kind;
2452 tree binfo = lookup_base (mdtype, type, ba_check, &b_kind, tf_none);
2453 if (!binfo || binfo == error_mark_node)
2455 if (reference_p)
2457 if (!ctx->quiet)
2459 error_at (loc, "reference %<dynamic_cast%> failed");
2460 if (b_kind == bk_ambig)
2461 inform (loc, "%qT is an ambiguous base class of dynamic "
2462 "type %qT of its operand", type, mdtype);
2463 else
2464 inform (loc, "dynamic type %qT of its operand does not "
2465 "have an unambiguous public base class %qT",
2466 mdtype, type);
2468 *non_constant_p = true;
2470 return integer_zero_node;
2472 /* If so, return the TYPE subobject of the most derived object. */
2473 obj = convert_to_base_statically (obj, binfo);
2474 return cp_build_addr_expr (obj, complain);
2477 /* Data structure used by replace_decl and replace_decl_r. */
2479 struct replace_decl_data
2481 /* The _DECL we want to replace. */
2482 tree decl;
2483 /* The replacement for DECL. */
2484 tree replacement;
2485 /* Trees we've visited. */
2486 hash_set<tree> *pset;
2487 /* Whether we've performed any replacements. */
2488 bool changed;
2491 /* Helper function for replace_decl, called through cp_walk_tree. */
2493 static tree
2494 replace_decl_r (tree *tp, int *walk_subtrees, void *data)
2496 replace_decl_data *d = (replace_decl_data *) data;
2498 if (*tp == d->decl)
2500 *tp = unshare_expr (d->replacement);
2501 d->changed = true;
2502 *walk_subtrees = 0;
2504 else if (TYPE_P (*tp)
2505 || d->pset->add (*tp))
2506 *walk_subtrees = 0;
2508 return NULL_TREE;
2511 /* Replace every occurrence of DECL with (an unshared copy of)
2512 REPLACEMENT within the expression *TP. Returns true iff a
2513 replacement was performed. */
2515 bool
2516 replace_decl (tree *tp, tree decl, tree replacement)
2518 gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
2519 (TREE_TYPE (decl), TREE_TYPE (replacement)));
2520 hash_set<tree> pset;
2521 replace_decl_data data = { decl, replacement, &pset, false };
2522 cp_walk_tree (tp, replace_decl_r, &data, NULL);
2523 return data.changed;
2526 /* Evaluate the call T to virtual function thunk THUNK_FNDECL. */
2528 static tree
2529 cxx_eval_thunk_call (const constexpr_ctx *ctx, tree t, tree thunk_fndecl,
2530 value_cat lval,
2531 bool *non_constant_p, bool *overflow_p)
2533 tree function = THUNK_TARGET (thunk_fndecl);
2535 if (THUNK_VIRTUAL_OFFSET (thunk_fndecl))
2537 if (!ctx->quiet)
2539 if (!DECL_DECLARED_CONSTEXPR_P (function))
2541 error ("call to non-%<constexpr%> function %qD", function);
2542 explain_invalid_constexpr_fn (function);
2544 else
2545 /* virtual_offset is only set for virtual bases, which make the
2546 class non-literal, so we don't need to handle it here. */
2547 error ("calling constexpr member function %qD through virtual "
2548 "base subobject", function);
2550 *non_constant_p = true;
2551 return t;
2554 tree new_call = copy_node (t);
2555 CALL_EXPR_FN (new_call) = function;
2556 TREE_TYPE (new_call) = TREE_TYPE (TREE_TYPE (function));
2558 tree offset = size_int (THUNK_FIXED_OFFSET (thunk_fndecl));
2560 if (DECL_THIS_THUNK_P (thunk_fndecl))
2562 /* 'this'-adjusting thunk. */
2563 tree this_arg = CALL_EXPR_ARG (t, 0);
2564 this_arg = build2 (POINTER_PLUS_EXPR, TREE_TYPE (this_arg),
2565 this_arg, offset);
2566 CALL_EXPR_ARG (new_call, 0) = this_arg;
2568 else
2569 /* Return-adjusting thunk. */
2570 new_call = build2 (POINTER_PLUS_EXPR, TREE_TYPE (new_call),
2571 new_call, offset);
2573 return cxx_eval_constant_expression (ctx, new_call, lval,
2574 non_constant_p, overflow_p);
2577 /* If OBJECT is of const class type, evaluate it to a CONSTRUCTOR and set
2578 its TREE_READONLY flag according to READONLY_P. Used for constexpr
2579 'tors to detect modifying const objects in a constexpr context. */
2581 static void
2582 cxx_set_object_constness (const constexpr_ctx *ctx, tree object,
2583 bool readonly_p, bool *non_constant_p,
2584 bool *overflow_p)
2586 if (CLASS_TYPE_P (TREE_TYPE (object))
2587 && CP_TYPE_CONST_P (TREE_TYPE (object)))
2589 /* Subobjects might not be stored in ctx->global->values but we
2590 can get its CONSTRUCTOR by evaluating *this. */
2591 tree e = cxx_eval_constant_expression (ctx, object, vc_prvalue,
2592 non_constant_p, overflow_p);
2593 if (TREE_CODE (e) == CONSTRUCTOR && !*non_constant_p)
2594 TREE_READONLY (e) = readonly_p;
2598 /* Subroutine of cxx_eval_constant_expression.
2599 Evaluate the call expression tree T in the context of OLD_CALL expression
2600 evaluation. */
2602 static tree
2603 cxx_eval_call_expression (const constexpr_ctx *ctx, tree t,
2604 value_cat lval,
2605 bool *non_constant_p, bool *overflow_p)
2607 /* Handle concept checks separately. */
2608 if (concept_check_p (t))
2609 return evaluate_concept_check (t);
2611 location_t loc = cp_expr_loc_or_input_loc (t);
2612 tree fun = get_function_named_in_call (t);
2613 constexpr_call new_call
2614 = { NULL, NULL, NULL, 0, ctx->manifestly_const_eval };
2615 int depth_ok;
2617 if (fun == NULL_TREE)
2618 return cxx_eval_internal_function (ctx, t, lval,
2619 non_constant_p, overflow_p);
2621 if (TREE_CODE (fun) != FUNCTION_DECL)
2623 /* Might be a constexpr function pointer. */
2624 fun = cxx_eval_constant_expression (ctx, fun, vc_prvalue,
2625 non_constant_p, overflow_p);
2626 STRIP_NOPS (fun);
2627 if (TREE_CODE (fun) == ADDR_EXPR)
2628 fun = TREE_OPERAND (fun, 0);
2629 /* For TARGET_VTABLE_USES_DESCRIPTORS targets, there is no
2630 indirection, the called expression is a pointer into the
2631 virtual table which should contain FDESC_EXPR. Extract the
2632 FUNCTION_DECL from there. */
2633 else if (TARGET_VTABLE_USES_DESCRIPTORS
2634 && TREE_CODE (fun) == POINTER_PLUS_EXPR
2635 && TREE_CODE (TREE_OPERAND (fun, 0)) == ADDR_EXPR
2636 && TREE_CODE (TREE_OPERAND (fun, 1)) == INTEGER_CST)
2638 tree d = TREE_OPERAND (TREE_OPERAND (fun, 0), 0);
2639 if (VAR_P (d)
2640 && DECL_VTABLE_OR_VTT_P (d)
2641 && TREE_CODE (TREE_TYPE (d)) == ARRAY_TYPE
2642 && TREE_TYPE (TREE_TYPE (d)) == vtable_entry_type
2643 && DECL_INITIAL (d)
2644 && TREE_CODE (DECL_INITIAL (d)) == CONSTRUCTOR)
2646 tree i = int_const_binop (TRUNC_DIV_EXPR, TREE_OPERAND (fun, 1),
2647 TYPE_SIZE_UNIT (vtable_entry_type));
2648 HOST_WIDE_INT idx = find_array_ctor_elt (DECL_INITIAL (d), i);
2649 if (idx >= 0)
2651 tree fdesc
2652 = (*CONSTRUCTOR_ELTS (DECL_INITIAL (d)))[idx].value;
2653 if (TREE_CODE (fdesc) == FDESC_EXPR
2654 && integer_zerop (TREE_OPERAND (fdesc, 1)))
2655 fun = TREE_OPERAND (fdesc, 0);
2660 if (TREE_CODE (fun) != FUNCTION_DECL)
2662 if (!ctx->quiet && !*non_constant_p)
2663 error_at (loc, "expression %qE does not designate a %<constexpr%> "
2664 "function", fun);
2665 *non_constant_p = true;
2666 return t;
2668 if (DECL_CLONED_FUNCTION_P (fun) && !DECL_DELETING_DESTRUCTOR_P (fun))
2669 fun = DECL_CLONED_FUNCTION (fun);
2671 if (is_ubsan_builtin_p (fun))
2672 return void_node;
2674 if (fndecl_built_in_p (fun))
2675 return cxx_eval_builtin_function_call (ctx, t, fun,
2676 lval, non_constant_p, overflow_p);
2677 if (DECL_THUNK_P (fun))
2678 return cxx_eval_thunk_call (ctx, t, fun, lval, non_constant_p, overflow_p);
2679 if (!maybe_constexpr_fn (fun))
2681 if (TREE_CODE (t) == CALL_EXPR
2682 && cxx_replaceable_global_alloc_fn (fun)
2683 && (CALL_FROM_NEW_OR_DELETE_P (t)
2684 || is_std_allocator_allocate (ctx->call)))
2686 const int nargs = call_expr_nargs (t);
2687 tree arg0 = NULL_TREE;
2688 for (int i = 0; i < nargs; ++i)
2690 tree arg = CALL_EXPR_ARG (t, i);
2691 arg = cxx_eval_constant_expression (ctx, arg, vc_prvalue,
2692 non_constant_p, overflow_p);
2693 VERIFY_CONSTANT (arg);
2694 if (i == 0)
2695 arg0 = arg;
2697 gcc_assert (arg0);
2698 if (IDENTIFIER_NEW_OP_P (DECL_NAME (fun)))
2700 tree type = build_array_type_nelts (char_type_node,
2701 tree_to_uhwi (arg0));
2702 tree var = build_decl (loc, VAR_DECL,
2703 (IDENTIFIER_OVL_OP_FLAGS (DECL_NAME (fun))
2704 & OVL_OP_FLAG_VEC)
2705 ? heap_vec_uninit_identifier
2706 : heap_uninit_identifier,
2707 type);
2708 DECL_ARTIFICIAL (var) = 1;
2709 TREE_STATIC (var) = 1;
2710 // Temporarily register the artificial var in varpool,
2711 // so that comparisons of its address against NULL are folded
2712 // through nonzero_address even with
2713 // -fno-delete-null-pointer-checks or that comparison of
2714 // addresses of different heap artificial vars is folded too.
2715 // See PR98988 and PR99031.
2716 varpool_node::finalize_decl (var);
2717 ctx->global->heap_vars.safe_push (var);
2718 ctx->global->put_value (var, NULL_TREE);
2719 return fold_convert (ptr_type_node, build_address (var));
2721 else
2723 STRIP_NOPS (arg0);
2724 if (TREE_CODE (arg0) == ADDR_EXPR
2725 && VAR_P (TREE_OPERAND (arg0, 0)))
2727 tree var = TREE_OPERAND (arg0, 0);
2728 if (DECL_NAME (var) == heap_uninit_identifier
2729 || DECL_NAME (var) == heap_identifier)
2731 if (IDENTIFIER_OVL_OP_FLAGS (DECL_NAME (fun))
2732 & OVL_OP_FLAG_VEC)
2734 if (!ctx->quiet)
2736 error_at (loc, "array deallocation of object "
2737 "allocated with non-array "
2738 "allocation");
2739 inform (DECL_SOURCE_LOCATION (var),
2740 "allocation performed here");
2742 *non_constant_p = true;
2743 return t;
2745 DECL_NAME (var) = heap_deleted_identifier;
2746 ctx->global->remove_value (var);
2747 ctx->global->heap_dealloc_count++;
2748 return void_node;
2750 else if (DECL_NAME (var) == heap_vec_uninit_identifier
2751 || DECL_NAME (var) == heap_vec_identifier)
2753 if ((IDENTIFIER_OVL_OP_FLAGS (DECL_NAME (fun))
2754 & OVL_OP_FLAG_VEC) == 0)
2756 if (!ctx->quiet)
2758 error_at (loc, "non-array deallocation of "
2759 "object allocated with array "
2760 "allocation");
2761 inform (DECL_SOURCE_LOCATION (var),
2762 "allocation performed here");
2764 *non_constant_p = true;
2765 return t;
2767 DECL_NAME (var) = heap_deleted_identifier;
2768 ctx->global->remove_value (var);
2769 ctx->global->heap_dealloc_count++;
2770 return void_node;
2772 else if (DECL_NAME (var) == heap_deleted_identifier)
2774 if (!ctx->quiet)
2775 error_at (loc, "deallocation of already deallocated "
2776 "storage");
2777 *non_constant_p = true;
2778 return t;
2781 if (!ctx->quiet)
2782 error_at (loc, "deallocation of storage that was "
2783 "not previously allocated");
2784 *non_constant_p = true;
2785 return t;
2788 /* Allow placement new in std::construct_at, just return the second
2789 argument. */
2790 if (TREE_CODE (t) == CALL_EXPR
2791 && cxx_placement_new_fn (fun)
2792 && is_std_construct_at (ctx->call))
2794 const int nargs = call_expr_nargs (t);
2795 tree arg1 = NULL_TREE;
2796 for (int i = 0; i < nargs; ++i)
2798 tree arg = CALL_EXPR_ARG (t, i);
2799 arg = cxx_eval_constant_expression (ctx, arg, vc_prvalue,
2800 non_constant_p, overflow_p);
2801 if (i == 1)
2802 arg1 = arg;
2803 else
2804 VERIFY_CONSTANT (arg);
2806 gcc_assert (arg1);
2807 return arg1;
2809 else if (cxx_dynamic_cast_fn_p (fun))
2810 return cxx_eval_dynamic_cast_fn (ctx, t, non_constant_p, overflow_p);
2812 if (!ctx->quiet)
2814 if (!lambda_static_thunk_p (fun))
2815 error_at (loc, "call to non-%<constexpr%> function %qD", fun);
2816 explain_invalid_constexpr_fn (fun);
2818 *non_constant_p = true;
2819 return t;
2822 constexpr_ctx new_ctx = *ctx;
2823 if (DECL_CONSTRUCTOR_P (fun) && !ctx->object
2824 && TREE_CODE (t) == AGGR_INIT_EXPR)
2826 /* We want to have an initialization target for an AGGR_INIT_EXPR.
2827 If we don't already have one in CTX, use the AGGR_INIT_EXPR_SLOT. */
2828 new_ctx.object = AGGR_INIT_EXPR_SLOT (t);
2829 tree ctor = new_ctx.ctor = build_constructor (DECL_CONTEXT (fun), NULL);
2830 CONSTRUCTOR_NO_CLEARING (ctor) = true;
2831 ctx->global->put_value (new_ctx.object, ctor);
2832 ctx = &new_ctx;
2835 /* Shortcut trivial constructor/op=. */
2836 if (trivial_fn_p (fun))
2838 tree init = NULL_TREE;
2839 if (call_expr_nargs (t) == 2)
2840 init = convert_from_reference (get_nth_callarg (t, 1));
2841 else if (TREE_CODE (t) == AGGR_INIT_EXPR
2842 && AGGR_INIT_ZERO_FIRST (t))
2843 init = build_zero_init (DECL_CONTEXT (fun), NULL_TREE, false);
2844 if (init)
2846 tree op = get_nth_callarg (t, 0);
2847 if (is_dummy_object (op))
2848 op = ctx->object;
2849 else
2850 op = build1 (INDIRECT_REF, TREE_TYPE (TREE_TYPE (op)), op);
2851 tree set = build2 (MODIFY_EXPR, TREE_TYPE (op), op, init);
2852 new_ctx.call = &new_call;
2853 return cxx_eval_constant_expression (&new_ctx, set, lval,
2854 non_constant_p, overflow_p);
2858 bool non_constant_args = false;
2859 new_call.bindings
2860 = cxx_bind_parameters_in_call (ctx, t, fun, non_constant_p,
2861 overflow_p, &non_constant_args);
2863 /* We build up the bindings list before we know whether we already have this
2864 call cached. If we don't end up saving these bindings, ggc_free them when
2865 this function exits. */
2866 class free_bindings
2868 tree *bindings;
2869 public:
2870 free_bindings (tree &b): bindings (&b) { }
2871 ~free_bindings () { if (bindings) ggc_free (*bindings); }
2872 void preserve () { bindings = NULL; }
2873 } fb (new_call.bindings);
2875 if (*non_constant_p)
2876 return t;
2878 /* We can't defer instantiating the function any longer. */
2879 if (!DECL_INITIAL (fun)
2880 && DECL_TEMPLOID_INSTANTIATION (fun)
2881 && !uid_sensitive_constexpr_evaluation_p ())
2883 location_t save_loc = input_location;
2884 input_location = loc;
2885 ++function_depth;
2886 if (ctx->manifestly_const_eval)
2887 FNDECL_MANIFESTLY_CONST_EVALUATED (fun) = true;
2888 instantiate_decl (fun, /*defer_ok*/false, /*expl_inst*/false);
2889 --function_depth;
2890 input_location = save_loc;
2893 /* If in direct recursive call, optimize definition search. */
2894 if (ctx && ctx->call && ctx->call->fundef && ctx->call->fundef->decl == fun)
2895 new_call.fundef = ctx->call->fundef;
2896 else
2898 new_call.fundef = retrieve_constexpr_fundef (fun);
2899 if (new_call.fundef == NULL || new_call.fundef->body == NULL
2900 || new_call.fundef->result == error_mark_node
2901 || fun == current_function_decl)
2903 if (!ctx->quiet)
2905 /* We need to check for current_function_decl here in case we're
2906 being called during cp_fold_function, because at that point
2907 DECL_INITIAL is set properly and we have a fundef but we
2908 haven't lowered invisirefs yet (c++/70344). */
2909 if (DECL_INITIAL (fun) == error_mark_node
2910 || fun == current_function_decl)
2911 error_at (loc, "%qD called in a constant expression before its "
2912 "definition is complete", fun);
2913 else if (DECL_INITIAL (fun))
2915 /* The definition of fun was somehow unsuitable. But pretend
2916 that lambda static thunks don't exist. */
2917 if (!lambda_static_thunk_p (fun))
2918 error_at (loc, "%qD called in a constant expression", fun);
2919 explain_invalid_constexpr_fn (fun);
2921 else
2922 error_at (loc, "%qD used before its definition", fun);
2924 *non_constant_p = true;
2925 return t;
2929 depth_ok = push_cx_call_context (t);
2931 /* Remember the object we are constructing or destructing. */
2932 tree new_obj = NULL_TREE;
2933 if (DECL_CONSTRUCTOR_P (fun) || DECL_DESTRUCTOR_P (fun))
2935 /* In a cdtor, it should be the first `this' argument.
2936 At this point it has already been evaluated in the call
2937 to cxx_bind_parameters_in_call. */
2938 new_obj = TREE_VEC_ELT (new_call.bindings, 0);
2939 new_obj = cxx_fold_indirect_ref (ctx, loc, DECL_CONTEXT (fun), new_obj);
2941 if (ctx->call && ctx->call->fundef
2942 && DECL_CONSTRUCTOR_P (ctx->call->fundef->decl))
2944 tree cur_obj = TREE_VEC_ELT (ctx->call->bindings, 0);
2945 STRIP_NOPS (cur_obj);
2946 if (TREE_CODE (cur_obj) == ADDR_EXPR)
2947 cur_obj = TREE_OPERAND (cur_obj, 0);
2948 if (new_obj == cur_obj)
2949 /* We're calling the target constructor of a delegating
2950 constructor, or accessing a base subobject through a
2951 NOP_EXPR as part of a call to a base constructor, so
2952 there is no new (sub)object. */
2953 new_obj = NULL_TREE;
2957 tree result = NULL_TREE;
2959 constexpr_call *entry = NULL;
2960 if (depth_ok && !non_constant_args && ctx->strict)
2962 new_call.hash = constexpr_fundef_hasher::hash (new_call.fundef);
2963 new_call.hash
2964 = iterative_hash_template_arg (new_call.bindings, new_call.hash);
2965 new_call.hash
2966 = iterative_hash_object (ctx->manifestly_const_eval, new_call.hash);
2968 /* If we have seen this call before, we are done. */
2969 maybe_initialize_constexpr_call_table ();
2970 constexpr_call **slot
2971 = constexpr_call_table->find_slot (&new_call, INSERT);
2972 entry = *slot;
2973 if (entry == NULL)
2975 /* Only cache up to constexpr_cache_depth to limit memory use. */
2976 if (depth_ok < constexpr_cache_depth)
2978 /* We need to keep a pointer to the entry, not just the slot, as
2979 the slot can move during evaluation of the body. */
2980 *slot = entry = ggc_alloc<constexpr_call> ();
2981 *entry = new_call;
2982 fb.preserve ();
2985 /* Calls that are in progress have their result set to NULL, so that we
2986 can detect circular dependencies. Now that we only cache up to
2987 constexpr_cache_depth this won't catch circular dependencies that
2988 start deeper, but they'll hit the recursion or ops limit. */
2989 else if (entry->result == NULL)
2991 if (!ctx->quiet)
2992 error ("call has circular dependency");
2993 *non_constant_p = true;
2994 entry->result = result = error_mark_node;
2996 else
2997 result = entry->result;
3000 if (!depth_ok)
3002 if (!ctx->quiet)
3003 error ("%<constexpr%> evaluation depth exceeds maximum of %d (use "
3004 "%<-fconstexpr-depth=%> to increase the maximum)",
3005 max_constexpr_depth);
3006 *non_constant_p = true;
3007 result = error_mark_node;
3009 else
3011 bool cacheable = true;
3012 if (result && result != error_mark_node)
3013 /* OK */;
3014 else if (!DECL_SAVED_TREE (fun))
3016 /* When at_eof >= 2, cgraph has started throwing away
3017 DECL_SAVED_TREE, so fail quietly. FIXME we get here because of
3018 late code generation for VEC_INIT_EXPR, which needs to be
3019 completely reconsidered. */
3020 gcc_assert (at_eof >= 2 && ctx->quiet);
3021 *non_constant_p = true;
3023 else if (tree copy = get_fundef_copy (new_call.fundef))
3025 tree body, parms, res;
3026 releasing_vec ctors;
3028 /* Reuse or create a new unshared copy of this function's body. */
3029 body = TREE_PURPOSE (copy);
3030 parms = TREE_VALUE (copy);
3031 res = TREE_TYPE (copy);
3033 /* Associate the bindings with the remapped parms. */
3034 tree bound = new_call.bindings;
3035 tree remapped = parms;
3036 for (int i = 0; i < TREE_VEC_LENGTH (bound); ++i)
3038 tree arg = TREE_VEC_ELT (bound, i);
3039 if (entry)
3041 /* Unshare args going into the hash table to separate them
3042 from the caller's context, for better GC and to avoid
3043 problems with verify_gimple. */
3044 arg = unshare_expr_without_location (arg);
3045 TREE_VEC_ELT (bound, i) = arg;
3047 /* And then unshare again so the callee doesn't change the
3048 argument values in the hash table. XXX Could we unshare
3049 lazily in cxx_eval_store_expression? */
3050 arg = unshare_constructor (arg);
3051 if (TREE_CODE (arg) == CONSTRUCTOR)
3052 vec_safe_push (ctors, arg);
3054 ctx->global->put_value (remapped, arg);
3055 remapped = DECL_CHAIN (remapped);
3057 /* Add the RESULT_DECL to the values map, too. */
3058 gcc_assert (!DECL_BY_REFERENCE (res));
3059 ctx->global->put_value (res, NULL_TREE);
3061 /* Track the callee's evaluated SAVE_EXPRs and TARGET_EXPRs so that
3062 we can forget their values after the call. */
3063 constexpr_ctx ctx_with_save_exprs = *ctx;
3064 auto_vec<tree, 10> save_exprs;
3065 ctx_with_save_exprs.save_exprs = &save_exprs;
3066 ctx_with_save_exprs.call = &new_call;
3067 unsigned save_heap_alloc_count = ctx->global->heap_vars.length ();
3068 unsigned save_heap_dealloc_count = ctx->global->heap_dealloc_count;
3070 /* If this is a constexpr destructor, the object's const and volatile
3071 semantics are no longer in effect; see [class.dtor]p5. */
3072 if (new_obj && DECL_DESTRUCTOR_P (fun))
3073 cxx_set_object_constness (ctx, new_obj, /*readonly_p=*/false,
3074 non_constant_p, overflow_p);
3076 tree jump_target = NULL_TREE;
3077 cxx_eval_constant_expression (&ctx_with_save_exprs, body,
3078 vc_discard, non_constant_p, overflow_p,
3079 &jump_target);
3081 if (DECL_CONSTRUCTOR_P (fun))
3083 /* This can be null for a subobject constructor call, in
3084 which case what we care about is the initialization
3085 side-effects rather than the value. We could get at the
3086 value by evaluating *this, but we don't bother; there's
3087 no need to put such a call in the hash table. */
3088 result = lval ? ctx->object : ctx->ctor;
3090 /* If we've just evaluated a subobject constructor call for an
3091 empty union member, it might not have produced a side effect
3092 that actually activated the union member. So produce such a
3093 side effect now to ensure the union appears initialized. */
3094 if (!result && new_obj
3095 && TREE_CODE (new_obj) == COMPONENT_REF
3096 && TREE_CODE (TREE_TYPE
3097 (TREE_OPERAND (new_obj, 0))) == UNION_TYPE
3098 && is_really_empty_class (TREE_TYPE (new_obj),
3099 /*ignore_vptr*/false))
3101 tree activate = build2 (MODIFY_EXPR, TREE_TYPE (new_obj),
3102 new_obj,
3103 build_constructor (TREE_TYPE (new_obj),
3104 NULL));
3105 cxx_eval_constant_expression (ctx, activate, lval,
3106 non_constant_p, overflow_p);
3107 ggc_free (activate);
3110 else if (VOID_TYPE_P (TREE_TYPE (res)))
3111 result = void_node;
3112 else
3114 result = ctx->global->get_value (res);
3115 if (result == NULL_TREE && !*non_constant_p
3116 && !DECL_DESTRUCTOR_P (fun))
3118 if (!ctx->quiet)
3119 error ("%<constexpr%> call flows off the end "
3120 "of the function");
3121 *non_constant_p = true;
3125 /* At this point, the object's constructor will have run, so
3126 the object is no longer under construction, and its possible
3127 'const' semantics now apply. Make a note of this fact by
3128 marking the CONSTRUCTOR TREE_READONLY. */
3129 if (new_obj && DECL_CONSTRUCTOR_P (fun))
3130 cxx_set_object_constness (ctx, new_obj, /*readonly_p=*/true,
3131 non_constant_p, overflow_p);
3133 /* Forget the saved values of the callee's SAVE_EXPRs and
3134 TARGET_EXPRs. */
3135 for (tree save_expr : save_exprs)
3136 ctx->global->remove_value (save_expr);
3138 /* Remove the parms/result from the values map. Is it worth
3139 bothering to do this when the map itself is only live for
3140 one constexpr evaluation? If so, maybe also clear out
3141 other vars from call, maybe in BIND_EXPR handling? */
3142 ctx->global->remove_value (res);
3143 for (tree parm = parms; parm; parm = TREE_CHAIN (parm))
3144 ctx->global->remove_value (parm);
3146 /* Free any parameter CONSTRUCTORs we aren't returning directly. */
3147 while (!ctors->is_empty ())
3149 tree c = ctors->pop ();
3150 if (c != result)
3151 free_constructor (c);
3154 /* Make the unshared function copy we used available for re-use. */
3155 save_fundef_copy (fun, copy);
3157 /* If the call allocated some heap object that hasn't been
3158 deallocated during the call, or if it deallocated some heap
3159 object it has not allocated, the call isn't really stateless
3160 for the constexpr evaluation and should not be cached.
3161 It is fine if the call allocates something and deallocates it
3162 too. */
3163 if (entry
3164 && (save_heap_alloc_count != ctx->global->heap_vars.length ()
3165 || (save_heap_dealloc_count
3166 != ctx->global->heap_dealloc_count)))
3168 tree heap_var;
3169 unsigned int i;
3170 if ((ctx->global->heap_vars.length ()
3171 - ctx->global->heap_dealloc_count)
3172 != save_heap_alloc_count - save_heap_dealloc_count)
3173 cacheable = false;
3174 else
3175 FOR_EACH_VEC_ELT_FROM (ctx->global->heap_vars, i, heap_var,
3176 save_heap_alloc_count)
3177 if (DECL_NAME (heap_var) != heap_deleted_identifier)
3179 cacheable = false;
3180 break;
3182 /* Also don't cache a call that returns a deallocated pointer. */
3183 if (cacheable && (cp_walk_tree_without_duplicates
3184 (&result, find_heap_var_refs, NULL)))
3185 cacheable = false;
3188 /* Rewrite all occurrences of the function's RESULT_DECL with the
3189 current object under construction. */
3190 if (!*non_constant_p && ctx->object
3191 && CLASS_TYPE_P (TREE_TYPE (res))
3192 && !is_empty_class (TREE_TYPE (res)))
3193 if (replace_decl (&result, res, ctx->object))
3194 cacheable = false;
3196 else
3197 /* Couldn't get a function copy to evaluate. */
3198 *non_constant_p = true;
3200 if (result == error_mark_node)
3201 *non_constant_p = true;
3202 if (*non_constant_p || *overflow_p)
3203 result = error_mark_node;
3204 else if (!result)
3205 result = void_node;
3206 if (entry)
3207 entry->result = cacheable ? result : error_mark_node;
3210 /* The result of a constexpr function must be completely initialized.
3212 However, in C++20, a constexpr constructor doesn't necessarily have
3213 to initialize all the fields, so we don't clear CONSTRUCTOR_NO_CLEARING
3214 in order to detect reading an unitialized object in constexpr instead
3215 of value-initializing it. (reduced_constant_expression_p is expected to
3216 take care of clearing the flag.) */
3217 if (TREE_CODE (result) == CONSTRUCTOR
3218 && (cxx_dialect < cxx20
3219 || !DECL_CONSTRUCTOR_P (fun)))
3220 clear_no_implicit_zero (result);
3222 pop_cx_call_context ();
3223 return result;
3226 /* Return true if T is a valid constant initializer. If a CONSTRUCTOR
3227 initializes all the members, the CONSTRUCTOR_NO_CLEARING flag will be
3228 cleared.
3229 FIXME speed this up, it's taking 16% of compile time on sieve testcase. */
3231 bool
3232 reduced_constant_expression_p (tree t)
3234 if (t == NULL_TREE)
3235 return false;
3237 switch (TREE_CODE (t))
3239 case PTRMEM_CST:
3240 /* Even if we can't lower this yet, it's constant. */
3241 return true;
3243 case CONSTRUCTOR:
3244 /* And we need to handle PTRMEM_CST wrapped in a CONSTRUCTOR. */
3245 tree field;
3246 if (TREE_CODE (TREE_TYPE (t)) == VECTOR_TYPE)
3247 /* An initialized vector would have a VECTOR_CST. */
3248 return false;
3249 if (CONSTRUCTOR_NO_CLEARING (t))
3251 if (TREE_CODE (TREE_TYPE (t)) == ARRAY_TYPE)
3253 /* There must be a valid constant initializer at every array
3254 index. */
3255 tree min = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (t)));
3256 tree max = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (t)));
3257 tree cursor = min;
3258 for (auto &e: CONSTRUCTOR_ELTS (t))
3260 if (!reduced_constant_expression_p (e.value))
3261 return false;
3262 if (array_index_cmp (cursor, e.index) != 0)
3263 return false;
3264 if (TREE_CODE (e.index) == RANGE_EXPR)
3265 cursor = TREE_OPERAND (e.index, 1);
3266 cursor = int_const_binop (PLUS_EXPR, cursor, size_one_node);
3268 if (find_array_ctor_elt (t, max) == -1)
3269 return false;
3270 goto ok;
3272 else if (cxx_dialect >= cxx20
3273 && TREE_CODE (TREE_TYPE (t)) == UNION_TYPE)
3275 if (CONSTRUCTOR_NELTS (t) == 0)
3276 /* An initialized union has a constructor element. */
3277 return false;
3278 /* And it only initializes one member. */
3279 field = NULL_TREE;
3281 else
3282 field = next_subobject_field (TYPE_FIELDS (TREE_TYPE (t)));
3284 else
3285 field = NULL_TREE;
3286 for (auto &e: CONSTRUCTOR_ELTS (t))
3288 /* If VAL is null, we're in the middle of initializing this
3289 element. */
3290 if (!reduced_constant_expression_p (e.value))
3291 return false;
3292 /* We want to remove initializers for empty fields in a struct to
3293 avoid confusing output_constructor. */
3294 if (is_empty_field (e.index)
3295 && TREE_CODE (TREE_TYPE (t)) == RECORD_TYPE)
3296 return false;
3297 /* Check for non-empty fields between initialized fields when
3298 CONSTRUCTOR_NO_CLEARING. */
3299 for (; field && e.index != field;
3300 field = next_subobject_field (DECL_CHAIN (field)))
3301 if (!is_really_empty_class (TREE_TYPE (field),
3302 /*ignore_vptr*/false))
3303 return false;
3304 if (field)
3305 field = next_subobject_field (DECL_CHAIN (field));
3307 /* There could be a non-empty field at the end. */
3308 for (; field; field = next_subobject_field (DECL_CHAIN (field)))
3309 if (!is_really_empty_class (TREE_TYPE (field), /*ignore_vptr*/false))
3310 return false;
3312 if (CONSTRUCTOR_NO_CLEARING (t))
3313 /* All the fields are initialized. */
3314 CONSTRUCTOR_NO_CLEARING (t) = false;
3315 return true;
3317 default:
3318 /* FIXME are we calling this too much? */
3319 return initializer_constant_valid_p (t, TREE_TYPE (t)) != NULL_TREE;
3323 /* Some expressions may have constant operands but are not constant
3324 themselves, such as 1/0. Call this function to check for that
3325 condition.
3327 We only call this in places that require an arithmetic constant, not in
3328 places where we might have a non-constant expression that can be a
3329 component of a constant expression, such as the address of a constexpr
3330 variable that might be dereferenced later. */
3332 static bool
3333 verify_constant (tree t, bool allow_non_constant, bool *non_constant_p,
3334 bool *overflow_p)
3336 if (!*non_constant_p && !reduced_constant_expression_p (t)
3337 && t != void_node)
3339 if (!allow_non_constant)
3340 error ("%q+E is not a constant expression", t);
3341 *non_constant_p = true;
3343 if (TREE_OVERFLOW_P (t))
3345 if (!allow_non_constant)
3347 permerror (input_location, "overflow in constant expression");
3348 /* If we're being permissive (and are in an enforcing
3349 context), ignore the overflow. */
3350 if (flag_permissive)
3351 return *non_constant_p;
3353 *overflow_p = true;
3355 return *non_constant_p;
3358 /* Check whether the shift operation with code CODE and type TYPE on LHS
3359 and RHS is undefined. If it is, give an error with an explanation,
3360 and return true; return false otherwise. */
3362 static bool
3363 cxx_eval_check_shift_p (location_t loc, const constexpr_ctx *ctx,
3364 enum tree_code code, tree type, tree lhs, tree rhs)
3366 if ((code != LSHIFT_EXPR && code != RSHIFT_EXPR)
3367 || TREE_CODE (lhs) != INTEGER_CST
3368 || TREE_CODE (rhs) != INTEGER_CST)
3369 return false;
3371 tree lhstype = TREE_TYPE (lhs);
3372 unsigned HOST_WIDE_INT uprec = TYPE_PRECISION (TREE_TYPE (lhs));
3374 /* [expr.shift] The behavior is undefined if the right operand
3375 is negative, or greater than or equal to the length in bits
3376 of the promoted left operand. */
3377 if (tree_int_cst_sgn (rhs) == -1)
3379 if (!ctx->quiet)
3380 permerror (loc, "right operand of shift expression %q+E is negative",
3381 build2_loc (loc, code, type, lhs, rhs));
3382 return (!flag_permissive || ctx->quiet);
3384 if (compare_tree_int (rhs, uprec) >= 0)
3386 if (!ctx->quiet)
3387 permerror (loc, "right operand of shift expression %q+E is greater "
3388 "than or equal to the precision %wu of the left operand",
3389 build2_loc (loc, code, type, lhs, rhs), uprec);
3390 return (!flag_permissive || ctx->quiet);
3393 /* The value of E1 << E2 is E1 left-shifted E2 bit positions; [...]
3394 if E1 has a signed type and non-negative value, and E1x2^E2 is
3395 representable in the corresponding unsigned type of the result type,
3396 then that value, converted to the result type, is the resulting value;
3397 otherwise, the behavior is undefined.
3398 For C++20:
3399 The value of E1 << E2 is the unique value congruent to E1 x 2^E2 modulo
3400 2^N, where N is the range exponent of the type of the result. */
3401 if (code == LSHIFT_EXPR
3402 && !TYPE_OVERFLOW_WRAPS (lhstype)
3403 && cxx_dialect >= cxx11
3404 && cxx_dialect < cxx20)
3406 if (tree_int_cst_sgn (lhs) == -1)
3408 if (!ctx->quiet)
3409 permerror (loc,
3410 "left operand of shift expression %q+E is negative",
3411 build2_loc (loc, code, type, lhs, rhs));
3412 return (!flag_permissive || ctx->quiet);
3414 /* For signed x << y the following:
3415 (unsigned) x >> ((prec (lhs) - 1) - y)
3416 if > 1, is undefined. The right-hand side of this formula
3417 is the highest bit of the LHS that can be set (starting from 0),
3418 so that the shift doesn't overflow. We then right-shift the LHS
3419 to see whether any other bit is set making the original shift
3420 undefined -- the result is not representable in the corresponding
3421 unsigned type. */
3422 tree t = build_int_cst (unsigned_type_node, uprec - 1);
3423 t = fold_build2 (MINUS_EXPR, unsigned_type_node, t, rhs);
3424 tree ulhs = fold_convert (unsigned_type_for (lhstype), lhs);
3425 t = fold_build2 (RSHIFT_EXPR, TREE_TYPE (ulhs), ulhs, t);
3426 if (tree_int_cst_lt (integer_one_node, t))
3428 if (!ctx->quiet)
3429 permerror (loc, "shift expression %q+E overflows",
3430 build2_loc (loc, code, type, lhs, rhs));
3431 return (!flag_permissive || ctx->quiet);
3434 return false;
3437 /* Subroutine of cxx_eval_constant_expression.
3438 Attempt to reduce the unary expression tree T to a compile time value.
3439 If successful, return the value. Otherwise issue a diagnostic
3440 and return error_mark_node. */
3442 static tree
3443 cxx_eval_unary_expression (const constexpr_ctx *ctx, tree t,
3444 bool /*lval*/,
3445 bool *non_constant_p, bool *overflow_p)
3447 tree r;
3448 tree orig_arg = TREE_OPERAND (t, 0);
3449 tree arg = cxx_eval_constant_expression (ctx, orig_arg, vc_prvalue,
3450 non_constant_p, overflow_p);
3451 VERIFY_CONSTANT (arg);
3452 location_t loc = EXPR_LOCATION (t);
3453 enum tree_code code = TREE_CODE (t);
3454 tree type = TREE_TYPE (t);
3455 r = fold_unary_loc (loc, code, type, arg);
3456 if (r == NULL_TREE)
3458 if (arg == orig_arg)
3459 r = t;
3460 else
3461 r = build1_loc (loc, code, type, arg);
3463 VERIFY_CONSTANT (r);
3464 return r;
3467 /* Helper function for cxx_eval_binary_expression. Try to optimize
3468 original POINTER_PLUS_EXPR T, LHS p+ RHS, return NULL_TREE if the
3469 generic folding should be used. */
3471 static tree
3472 cxx_fold_pointer_plus_expression (const constexpr_ctx *ctx, tree t,
3473 tree lhs, tree rhs, bool *non_constant_p,
3474 bool *overflow_p)
3476 STRIP_NOPS (lhs);
3477 if (TREE_CODE (lhs) != ADDR_EXPR)
3478 return NULL_TREE;
3480 lhs = TREE_OPERAND (lhs, 0);
3482 /* &A[i] p+ j => &A[i + j] */
3483 if (TREE_CODE (lhs) == ARRAY_REF
3484 && TREE_CODE (TREE_OPERAND (lhs, 1)) == INTEGER_CST
3485 && TREE_CODE (rhs) == INTEGER_CST
3486 && TYPE_SIZE_UNIT (TREE_TYPE (lhs))
3487 && TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (lhs))) == INTEGER_CST)
3489 tree orig_type = TREE_TYPE (t);
3490 location_t loc = EXPR_LOCATION (t);
3491 tree type = TREE_TYPE (lhs);
3493 t = fold_convert_loc (loc, ssizetype, TREE_OPERAND (lhs, 1));
3494 tree nelts = array_type_nelts_top (TREE_TYPE (TREE_OPERAND (lhs, 0)));
3495 nelts = cxx_eval_constant_expression (ctx, nelts, vc_prvalue,
3496 non_constant_p, overflow_p);
3497 if (*non_constant_p)
3498 return NULL_TREE;
3499 /* Don't fold an out-of-bound access. */
3500 if (!tree_int_cst_le (t, nelts))
3501 return NULL_TREE;
3502 rhs = cp_fold_convert (ssizetype, rhs);
3503 /* Don't fold if rhs can't be divided exactly by TYPE_SIZE_UNIT.
3504 constexpr int A[1]; ... (char *)&A[0] + 1 */
3505 if (!integer_zerop (fold_build2_loc (loc, TRUNC_MOD_EXPR, sizetype,
3506 rhs, TYPE_SIZE_UNIT (type))))
3507 return NULL_TREE;
3508 /* Make sure to treat the second operand of POINTER_PLUS_EXPR
3509 as signed. */
3510 rhs = fold_build2_loc (loc, EXACT_DIV_EXPR, ssizetype, rhs,
3511 TYPE_SIZE_UNIT (type));
3512 t = size_binop_loc (loc, PLUS_EXPR, rhs, t);
3513 t = build4_loc (loc, ARRAY_REF, type, TREE_OPERAND (lhs, 0),
3514 t, NULL_TREE, NULL_TREE);
3515 t = cp_build_addr_expr (t, tf_warning_or_error);
3516 t = cp_fold_convert (orig_type, t);
3517 return cxx_eval_constant_expression (ctx, t, vc_prvalue,
3518 non_constant_p, overflow_p);
3521 return NULL_TREE;
3524 /* Try to fold expressions like
3525 (struct S *) (&a[0].D.2378 + 12)
3526 into
3527 &MEM <struct T> [(void *)&a + 12B]
3528 This is something normally done by gimple_fold_stmt_to_constant_1
3529 on GIMPLE, but is undesirable on GENERIC if we are e.g. going to
3530 dereference the address because some details are lost.
3531 For pointer comparisons we want such folding though so that
3532 match.pd address_compare optimization works. */
3534 static tree
3535 cxx_maybe_fold_addr_pointer_plus (tree t)
3537 while (CONVERT_EXPR_P (t)
3538 && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (t, 0))))
3539 t = TREE_OPERAND (t, 0);
3540 if (TREE_CODE (t) != POINTER_PLUS_EXPR)
3541 return NULL_TREE;
3542 tree op0 = TREE_OPERAND (t, 0);
3543 tree op1 = TREE_OPERAND (t, 1);
3544 if (TREE_CODE (op1) != INTEGER_CST)
3545 return NULL_TREE;
3546 while (CONVERT_EXPR_P (op0)
3547 && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (op0, 0))))
3548 op0 = TREE_OPERAND (op0, 0);
3549 if (TREE_CODE (op0) != ADDR_EXPR)
3550 return NULL_TREE;
3551 op1 = fold_convert (ptr_type_node, op1);
3552 tree r = fold_build2 (MEM_REF, TREE_TYPE (TREE_TYPE (op0)), op0, op1);
3553 return build1_loc (EXPR_LOCATION (t), ADDR_EXPR, TREE_TYPE (op0), r);
3556 /* Subroutine of cxx_eval_constant_expression.
3557 Like cxx_eval_unary_expression, except for binary expressions. */
3559 static tree
3560 cxx_eval_binary_expression (const constexpr_ctx *ctx, tree t,
3561 value_cat lval,
3562 bool *non_constant_p, bool *overflow_p)
3564 tree r = NULL_TREE;
3565 tree orig_lhs = TREE_OPERAND (t, 0);
3566 tree orig_rhs = TREE_OPERAND (t, 1);
3567 tree lhs, rhs;
3568 lhs = cxx_eval_constant_expression (ctx, orig_lhs, vc_prvalue,
3569 non_constant_p, overflow_p);
3570 /* Don't VERIFY_CONSTANT here, it's unnecessary and will break pointer
3571 subtraction. */
3572 if (*non_constant_p)
3573 return t;
3574 rhs = cxx_eval_constant_expression (ctx, orig_rhs, vc_prvalue,
3575 non_constant_p, overflow_p);
3576 if (*non_constant_p)
3577 return t;
3579 location_t loc = EXPR_LOCATION (t);
3580 enum tree_code code = TREE_CODE (t);
3581 tree type = TREE_TYPE (t);
3583 if (code == EQ_EXPR || code == NE_EXPR)
3585 bool is_code_eq = (code == EQ_EXPR);
3587 if (TREE_CODE (lhs) == PTRMEM_CST
3588 && TREE_CODE (rhs) == PTRMEM_CST)
3590 tree lmem = PTRMEM_CST_MEMBER (lhs);
3591 tree rmem = PTRMEM_CST_MEMBER (rhs);
3592 bool eq;
3593 if (TREE_CODE (lmem) == TREE_CODE (rmem)
3594 && TREE_CODE (lmem) == FIELD_DECL
3595 && TREE_CODE (DECL_CONTEXT (lmem)) == UNION_TYPE
3596 && same_type_p (DECL_CONTEXT (lmem),
3597 DECL_CONTEXT (rmem)))
3598 /* If both refer to (possibly different) members of the same union
3599 (12.3), they compare equal. */
3600 eq = true;
3601 else
3602 eq = cp_tree_equal (lhs, rhs);
3603 r = constant_boolean_node (eq == is_code_eq, type);
3605 else if ((TREE_CODE (lhs) == PTRMEM_CST
3606 || TREE_CODE (rhs) == PTRMEM_CST)
3607 && (null_member_pointer_value_p (lhs)
3608 || null_member_pointer_value_p (rhs)))
3609 r = constant_boolean_node (!is_code_eq, type);
3610 else if (TREE_CODE (lhs) == PTRMEM_CST)
3611 lhs = cplus_expand_constant (lhs);
3612 else if (TREE_CODE (rhs) == PTRMEM_CST)
3613 rhs = cplus_expand_constant (rhs);
3615 if (r == NULL_TREE
3616 && TREE_CODE_CLASS (code) == tcc_comparison
3617 && POINTER_TYPE_P (TREE_TYPE (lhs)))
3619 if (tree lhso = cxx_maybe_fold_addr_pointer_plus (lhs))
3620 lhs = fold_convert (TREE_TYPE (lhs), lhso);
3621 if (tree rhso = cxx_maybe_fold_addr_pointer_plus (rhs))
3622 rhs = fold_convert (TREE_TYPE (rhs), rhso);
3624 if (code == POINTER_PLUS_EXPR && !*non_constant_p
3625 && integer_zerop (lhs) && !integer_zerop (rhs))
3627 if (!ctx->quiet)
3628 error ("arithmetic involving a null pointer in %qE", lhs);
3629 *non_constant_p = true;
3630 return t;
3632 else if (code == POINTER_PLUS_EXPR)
3633 r = cxx_fold_pointer_plus_expression (ctx, t, lhs, rhs, non_constant_p,
3634 overflow_p);
3635 else if (code == SPACESHIP_EXPR)
3637 r = genericize_spaceship (loc, type, lhs, rhs);
3638 return cxx_eval_constant_expression (ctx, r, lval, non_constant_p,
3639 overflow_p);
3642 if (r == NULL_TREE)
3644 if (ctx->manifestly_const_eval
3645 && (flag_constexpr_fp_except
3646 || TREE_CODE (type) != REAL_TYPE))
3648 auto ofcc = make_temp_override (folding_cxx_constexpr, true);
3649 r = fold_binary_initializer_loc (loc, code, type, lhs, rhs);
3651 else
3652 r = fold_binary_loc (loc, code, type, lhs, rhs);
3655 if (r == NULL_TREE
3656 && (code == LSHIFT_EXPR || code == RSHIFT_EXPR)
3657 && TREE_CODE (lhs) == INTEGER_CST
3658 && TREE_CODE (rhs) == INTEGER_CST
3659 && wi::neg_p (wi::to_wide (rhs)))
3661 /* For diagnostics and -fpermissive emulate previous behavior of
3662 handling shifts by negative amount. */
3663 tree nrhs = const_unop (NEGATE_EXPR, TREE_TYPE (rhs), rhs);
3664 if (nrhs)
3665 r = fold_binary_loc (loc,
3666 code == LSHIFT_EXPR ? RSHIFT_EXPR : LSHIFT_EXPR,
3667 type, lhs, nrhs);
3670 if (r == NULL_TREE)
3672 if (lhs == orig_lhs && rhs == orig_rhs)
3673 r = t;
3674 else
3675 r = build2_loc (loc, code, type, lhs, rhs);
3677 else if (cxx_eval_check_shift_p (loc, ctx, code, type, lhs, rhs))
3678 *non_constant_p = true;
3679 /* Don't VERIFY_CONSTANT if this might be dealing with a pointer to
3680 a local array in a constexpr function. */
3681 bool ptr = INDIRECT_TYPE_P (TREE_TYPE (lhs));
3682 if (!ptr)
3683 VERIFY_CONSTANT (r);
3684 return r;
3687 /* Subroutine of cxx_eval_constant_expression.
3688 Attempt to evaluate condition expressions. Dead branches are not
3689 looked into. */
3691 static tree
3692 cxx_eval_conditional_expression (const constexpr_ctx *ctx, tree t,
3693 value_cat lval,
3694 bool *non_constant_p, bool *overflow_p,
3695 tree *jump_target)
3697 tree val = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
3698 vc_prvalue,
3699 non_constant_p, overflow_p);
3700 VERIFY_CONSTANT (val);
3701 if (TREE_CODE (t) == IF_STMT && IF_STMT_CONSTEVAL_P (t))
3703 /* Evaluate the condition as if it was
3704 if (__builtin_is_constant_evaluated ()), i.e. defer it if not
3705 ctx->manifestly_const_eval (as sometimes we try to constant evaluate
3706 without manifestly_const_eval even expressions or parts thereof which
3707 will later be manifestly const_eval evaluated), otherwise fold it to
3708 true. */
3709 if (ctx->manifestly_const_eval)
3710 val = boolean_true_node;
3711 else
3713 *non_constant_p = true;
3714 return t;
3717 /* Don't VERIFY_CONSTANT the other operands. */
3718 if (integer_zerop (val))
3719 val = TREE_OPERAND (t, 2);
3720 else
3721 val = TREE_OPERAND (t, 1);
3722 if (TREE_CODE (t) == IF_STMT && !val)
3723 val = void_node;
3724 /* A TARGET_EXPR may be nested inside another TARGET_EXPR, but still
3725 serve as the initializer for the same object as the outer TARGET_EXPR,
3726 as in
3727 A a = true ? A{} : A{};
3728 so strip the inner TARGET_EXPR so we don't materialize a temporary. */
3729 if (TREE_CODE (val) == TARGET_EXPR)
3730 val = TARGET_EXPR_INITIAL (val);
3731 return cxx_eval_constant_expression (ctx, val, lval, non_constant_p,
3732 overflow_p, jump_target);
3735 /* Subroutine of cxx_eval_constant_expression.
3736 Attempt to evaluate vector condition expressions. Unlike
3737 cxx_eval_conditional_expression, VEC_COND_EXPR acts like a normal
3738 ternary arithmetics operation, where all 3 arguments have to be
3739 evaluated as constants and then folding computes the result from
3740 them. */
3742 static tree
3743 cxx_eval_vector_conditional_expression (const constexpr_ctx *ctx, tree t,
3744 bool *non_constant_p, bool *overflow_p)
3746 tree arg1 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
3747 vc_prvalue,
3748 non_constant_p, overflow_p);
3749 VERIFY_CONSTANT (arg1);
3750 tree arg2 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
3751 vc_prvalue,
3752 non_constant_p, overflow_p);
3753 VERIFY_CONSTANT (arg2);
3754 tree arg3 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 2),
3755 vc_prvalue,
3756 non_constant_p, overflow_p);
3757 VERIFY_CONSTANT (arg3);
3758 location_t loc = EXPR_LOCATION (t);
3759 tree type = TREE_TYPE (t);
3760 tree r = fold_ternary_loc (loc, VEC_COND_EXPR, type, arg1, arg2, arg3);
3761 if (r == NULL_TREE)
3763 if (arg1 == TREE_OPERAND (t, 0)
3764 && arg2 == TREE_OPERAND (t, 1)
3765 && arg3 == TREE_OPERAND (t, 2))
3766 r = t;
3767 else
3768 r = build3_loc (loc, VEC_COND_EXPR, type, arg1, arg2, arg3);
3770 VERIFY_CONSTANT (r);
3771 return r;
3774 /* Returns less than, equal to, or greater than zero if KEY is found to be
3775 less than, to match, or to be greater than the constructor_elt's INDEX. */
3777 static int
3778 array_index_cmp (tree key, tree index)
3780 gcc_assert (TREE_CODE (key) == INTEGER_CST);
3782 switch (TREE_CODE (index))
3784 case INTEGER_CST:
3785 return tree_int_cst_compare (key, index);
3786 case RANGE_EXPR:
3788 tree lo = TREE_OPERAND (index, 0);
3789 tree hi = TREE_OPERAND (index, 1);
3790 if (tree_int_cst_lt (key, lo))
3791 return -1;
3792 else if (tree_int_cst_lt (hi, key))
3793 return 1;
3794 else
3795 return 0;
3797 default:
3798 gcc_unreachable ();
3802 /* Returns the index of the constructor_elt of ARY which matches DINDEX, or -1
3803 if none. If INSERT is true, insert a matching element rather than fail. */
3805 static HOST_WIDE_INT
3806 find_array_ctor_elt (tree ary, tree dindex, bool insert)
3808 if (tree_int_cst_sgn (dindex) < 0)
3809 return -1;
3811 unsigned HOST_WIDE_INT i = tree_to_uhwi (dindex);
3812 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ary);
3813 unsigned HOST_WIDE_INT len = vec_safe_length (elts);
3815 unsigned HOST_WIDE_INT end = len;
3816 unsigned HOST_WIDE_INT begin = 0;
3818 /* If the last element of the CONSTRUCTOR has its own index, we can assume
3819 that the same is true of the other elements and index directly. */
3820 if (end > 0)
3822 tree cindex = (*elts)[end - 1].index;
3823 if (cindex == NULL_TREE)
3825 /* Verify that if the last index is missing, all indexes
3826 are missing. */
3827 if (flag_checking)
3828 for (unsigned int j = 0; j < len - 1; ++j)
3829 gcc_assert ((*elts)[j].index == NULL_TREE);
3830 if (i < end)
3831 return i;
3832 else
3834 begin = end;
3835 if (i == end)
3836 /* If the element is to be added right at the end,
3837 make sure it is added with cleared index too. */
3838 dindex = NULL_TREE;
3839 else if (insert)
3840 /* Otherwise, in order not to break the assumption
3841 that CONSTRUCTOR either has all indexes or none,
3842 we need to add indexes to all elements. */
3843 for (unsigned int j = 0; j < len; ++j)
3844 (*elts)[j].index = build_int_cst (TREE_TYPE (dindex), j);
3847 else if (TREE_CODE (cindex) == INTEGER_CST
3848 && compare_tree_int (cindex, end - 1) == 0)
3850 if (i < end)
3851 return i;
3852 else
3853 begin = end;
3857 /* Otherwise, find a matching index by means of a binary search. */
3858 while (begin != end)
3860 unsigned HOST_WIDE_INT middle = (begin + end) / 2;
3861 constructor_elt &elt = (*elts)[middle];
3862 tree idx = elt.index;
3864 int cmp = array_index_cmp (dindex, idx);
3865 if (cmp < 0)
3866 end = middle;
3867 else if (cmp > 0)
3868 begin = middle + 1;
3869 else
3871 if (insert && TREE_CODE (idx) == RANGE_EXPR)
3873 /* We need to split the range. */
3874 constructor_elt e;
3875 tree lo = TREE_OPERAND (idx, 0);
3876 tree hi = TREE_OPERAND (idx, 1);
3877 tree value = elt.value;
3878 dindex = fold_convert (sizetype, dindex);
3879 if (tree_int_cst_lt (lo, dindex))
3881 /* There are still some lower elts; shorten the range. */
3882 tree new_hi = int_const_binop (MINUS_EXPR, dindex,
3883 size_one_node);
3884 if (tree_int_cst_equal (lo, new_hi))
3885 /* Only one element left, no longer a range. */
3886 elt.index = lo;
3887 else
3888 TREE_OPERAND (idx, 1) = new_hi;
3889 /* Append the element we want to insert. */
3890 ++middle;
3891 e.index = dindex;
3892 e.value = unshare_constructor (value);
3893 vec_safe_insert (CONSTRUCTOR_ELTS (ary), middle, e);
3895 else
3896 /* No lower elts, the range elt is now ours. */
3897 elt.index = dindex;
3899 if (tree_int_cst_lt (dindex, hi))
3901 /* There are still some higher elts; append a range. */
3902 tree new_lo = int_const_binop (PLUS_EXPR, dindex,
3903 size_one_node);
3904 if (tree_int_cst_equal (new_lo, hi))
3905 e.index = hi;
3906 else
3907 e.index = build2 (RANGE_EXPR, sizetype, new_lo, hi);
3908 e.value = unshare_constructor (value);
3909 vec_safe_insert (CONSTRUCTOR_ELTS (ary), middle + 1, e);
3912 return middle;
3916 if (insert)
3918 constructor_elt e = { dindex, NULL_TREE };
3919 vec_safe_insert (CONSTRUCTOR_ELTS (ary), end, e);
3920 return end;
3923 return -1;
3926 /* Return a pointer to the constructor_elt of CTOR which matches INDEX. If no
3927 matching constructor_elt exists, then add one to CTOR.
3929 As an optimization, if POS_HINT is non-negative then it is used as a guess
3930 for the (integer) index of the matching constructor_elt within CTOR. */
3932 static constructor_elt *
3933 get_or_insert_ctor_field (tree ctor, tree index, int pos_hint = -1)
3935 /* Check the hint first. */
3936 if (pos_hint >= 0 && (unsigned)pos_hint < CONSTRUCTOR_NELTS (ctor)
3937 && CONSTRUCTOR_ELT (ctor, pos_hint)->index == index)
3938 return CONSTRUCTOR_ELT (ctor, pos_hint);
3940 tree type = TREE_TYPE (ctor);
3941 if (TREE_CODE (type) == VECTOR_TYPE && index == NULL_TREE)
3943 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (ctor), index, NULL_TREE);
3944 return &CONSTRUCTOR_ELTS (ctor)->last();
3946 else if (TREE_CODE (type) == ARRAY_TYPE || TREE_CODE (type) == VECTOR_TYPE)
3948 if (TREE_CODE (index) == RANGE_EXPR)
3950 /* Support for RANGE_EXPR index lookups is currently limited to
3951 accessing an existing element via POS_HINT, or appending a new
3952 element to the end of CTOR. ??? Support for other access
3953 patterns may also be needed. */
3954 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ctor);
3955 if (vec_safe_length (elts))
3957 tree lo = TREE_OPERAND (index, 0);
3958 gcc_assert (array_index_cmp (elts->last().index, lo) < 0);
3960 CONSTRUCTOR_APPEND_ELT (elts, index, NULL_TREE);
3961 return &elts->last();
3964 HOST_WIDE_INT i = find_array_ctor_elt (ctor, index, /*insert*/true);
3965 gcc_assert (i >= 0);
3966 constructor_elt *cep = CONSTRUCTOR_ELT (ctor, i);
3967 gcc_assert (cep->index == NULL_TREE
3968 || TREE_CODE (cep->index) != RANGE_EXPR);
3969 return cep;
3971 else
3973 gcc_assert (TREE_CODE (index) == FIELD_DECL
3974 && (same_type_ignoring_top_level_qualifiers_p
3975 (DECL_CONTEXT (index), TREE_TYPE (ctor))));
3977 /* We must keep the CONSTRUCTOR's ELTS in FIELD order.
3978 Usually we meet initializers in that order, but it is
3979 possible for base types to be placed not in program
3980 order. */
3981 tree fields = TYPE_FIELDS (DECL_CONTEXT (index));
3982 unsigned HOST_WIDE_INT idx = 0;
3983 constructor_elt *cep = NULL;
3985 /* Check if we're changing the active member of a union. */
3986 if (TREE_CODE (type) == UNION_TYPE && CONSTRUCTOR_NELTS (ctor)
3987 && CONSTRUCTOR_ELT (ctor, 0)->index != index)
3988 vec_safe_truncate (CONSTRUCTOR_ELTS (ctor), 0);
3989 /* If the bit offset of INDEX is larger than that of the last
3990 constructor_elt, then we can just immediately append a new
3991 constructor_elt to the end of CTOR. */
3992 else if (CONSTRUCTOR_NELTS (ctor)
3993 && tree_int_cst_compare (bit_position (index),
3994 bit_position (CONSTRUCTOR_ELTS (ctor)
3995 ->last().index)) > 0)
3997 idx = CONSTRUCTOR_NELTS (ctor);
3998 goto insert;
4001 /* Otherwise, we need to iterate over CTOR to find or insert INDEX
4002 appropriately. */
4004 for (; vec_safe_iterate (CONSTRUCTOR_ELTS (ctor), idx, &cep);
4005 idx++, fields = DECL_CHAIN (fields))
4007 if (index == cep->index)
4008 goto found;
4010 /* The field we're initializing must be on the field
4011 list. Look to see if it is present before the
4012 field the current ELT initializes. */
4013 for (; fields != cep->index; fields = DECL_CHAIN (fields))
4014 if (index == fields)
4015 goto insert;
4017 /* We fell off the end of the CONSTRUCTOR, so insert a new
4018 entry at the end. */
4020 insert:
4022 constructor_elt ce = { index, NULL_TREE };
4024 vec_safe_insert (CONSTRUCTOR_ELTS (ctor), idx, ce);
4025 cep = CONSTRUCTOR_ELT (ctor, idx);
4027 found:;
4029 return cep;
4033 /* Under the control of CTX, issue a detailed diagnostic for
4034 an out-of-bounds subscript INDEX into the expression ARRAY. */
4036 static void
4037 diag_array_subscript (location_t loc, const constexpr_ctx *ctx, tree array, tree index)
4039 if (!ctx->quiet)
4041 tree arraytype = TREE_TYPE (array);
4043 /* Convert the unsigned array subscript to a signed integer to avoid
4044 printing huge numbers for small negative values. */
4045 tree sidx = fold_convert (ssizetype, index);
4046 STRIP_ANY_LOCATION_WRAPPER (array);
4047 if (DECL_P (array))
4049 if (TYPE_DOMAIN (arraytype))
4050 error_at (loc, "array subscript value %qE is outside the bounds "
4051 "of array %qD of type %qT", sidx, array, arraytype);
4052 else
4053 error_at (loc, "nonzero array subscript %qE is used with array %qD of "
4054 "type %qT with unknown bounds", sidx, array, arraytype);
4055 inform (DECL_SOURCE_LOCATION (array), "declared here");
4057 else if (TYPE_DOMAIN (arraytype))
4058 error_at (loc, "array subscript value %qE is outside the bounds "
4059 "of array type %qT", sidx, arraytype);
4060 else
4061 error_at (loc, "nonzero array subscript %qE is used with array of type %qT "
4062 "with unknown bounds", sidx, arraytype);
4066 /* Return the number of elements for TYPE (which is an ARRAY_TYPE or
4067 a VECTOR_TYPE). */
4069 static tree
4070 get_array_or_vector_nelts (const constexpr_ctx *ctx, tree type,
4071 bool *non_constant_p, bool *overflow_p)
4073 tree nelts;
4074 if (TREE_CODE (type) == ARRAY_TYPE)
4076 if (TYPE_DOMAIN (type))
4077 nelts = array_type_nelts_top (type);
4078 else
4079 nelts = size_zero_node;
4081 else if (VECTOR_TYPE_P (type))
4082 nelts = size_int (TYPE_VECTOR_SUBPARTS (type));
4083 else
4084 gcc_unreachable ();
4086 /* For VLAs, the number of elements won't be an integer constant. */
4087 nelts = cxx_eval_constant_expression (ctx, nelts, vc_prvalue,
4088 non_constant_p, overflow_p);
4089 return nelts;
4092 /* Extract element INDEX consisting of CHARS_PER_ELT chars from
4093 STRING_CST STRING. */
4095 static tree
4096 extract_string_elt (tree string, unsigned chars_per_elt, unsigned index)
4098 tree type = cv_unqualified (TREE_TYPE (TREE_TYPE (string)));
4099 tree r;
4101 if (chars_per_elt == 1)
4102 r = build_int_cst (type, TREE_STRING_POINTER (string)[index]);
4103 else
4105 const unsigned char *ptr
4106 = ((const unsigned char *)TREE_STRING_POINTER (string)
4107 + index * chars_per_elt);
4108 r = native_interpret_expr (type, ptr, chars_per_elt);
4110 return r;
4113 /* Subroutine of cxx_eval_array_reference. T is an ARRAY_REF; evaluate the
4114 subscript, diagnose any problems with it, and return the result. */
4116 static tree
4117 eval_and_check_array_index (const constexpr_ctx *ctx,
4118 tree t, bool allow_one_past,
4119 bool *non_constant_p, bool *overflow_p)
4121 location_t loc = cp_expr_loc_or_input_loc (t);
4122 tree ary = TREE_OPERAND (t, 0);
4123 t = TREE_OPERAND (t, 1);
4124 tree index = cxx_eval_constant_expression (ctx, t, vc_prvalue,
4125 non_constant_p, overflow_p);
4126 VERIFY_CONSTANT (index);
4128 if (!tree_fits_shwi_p (index)
4129 || tree_int_cst_sgn (index) < 0)
4131 diag_array_subscript (loc, ctx, ary, index);
4132 *non_constant_p = true;
4133 return t;
4136 tree nelts = get_array_or_vector_nelts (ctx, TREE_TYPE (ary), non_constant_p,
4137 overflow_p);
4138 VERIFY_CONSTANT (nelts);
4139 if (allow_one_past
4140 ? !tree_int_cst_le (index, nelts)
4141 : !tree_int_cst_lt (index, nelts))
4143 diag_array_subscript (loc, ctx, ary, index);
4144 *non_constant_p = true;
4145 return t;
4148 return index;
4151 /* Subroutine of cxx_eval_constant_expression.
4152 Attempt to reduce a reference to an array slot. */
4154 static tree
4155 cxx_eval_array_reference (const constexpr_ctx *ctx, tree t,
4156 value_cat lval,
4157 bool *non_constant_p, bool *overflow_p)
4159 tree oldary = TREE_OPERAND (t, 0);
4160 tree ary = cxx_eval_constant_expression (ctx, oldary,
4161 lval,
4162 non_constant_p, overflow_p);
4163 if (*non_constant_p)
4164 return t;
4165 if (!lval
4166 && TREE_CODE (ary) == VIEW_CONVERT_EXPR
4167 && VECTOR_TYPE_P (TREE_TYPE (TREE_OPERAND (ary, 0)))
4168 && TREE_TYPE (t) == TREE_TYPE (TREE_TYPE (TREE_OPERAND (ary, 0))))
4169 ary = TREE_OPERAND (ary, 0);
4171 tree oldidx = TREE_OPERAND (t, 1);
4172 tree index = eval_and_check_array_index (ctx, t, lval,
4173 non_constant_p, overflow_p);
4174 if (*non_constant_p)
4175 return t;
4177 if (lval && ary == oldary && index == oldidx)
4178 return t;
4179 else if (lval == vc_discard)
4180 return t;
4181 else if (lval)
4182 return build4 (ARRAY_REF, TREE_TYPE (t), ary, index, NULL, NULL);
4184 unsigned len = 0, elem_nchars = 1;
4185 tree elem_type = TREE_TYPE (TREE_TYPE (ary));
4186 if (TREE_CODE (ary) == CONSTRUCTOR)
4187 len = CONSTRUCTOR_NELTS (ary);
4188 else if (TREE_CODE (ary) == STRING_CST)
4190 elem_nchars = (TYPE_PRECISION (elem_type)
4191 / TYPE_PRECISION (char_type_node));
4192 len = (unsigned) TREE_STRING_LENGTH (ary) / elem_nchars;
4194 else if (TREE_CODE (ary) == VECTOR_CST)
4195 /* We don't create variable-length VECTOR_CSTs. */
4196 len = VECTOR_CST_NELTS (ary).to_constant ();
4197 else
4199 /* We can't do anything with other tree codes, so use
4200 VERIFY_CONSTANT to complain and fail. */
4201 VERIFY_CONSTANT (ary);
4202 gcc_unreachable ();
4205 bool found;
4206 HOST_WIDE_INT i = 0;
4207 if (TREE_CODE (ary) == CONSTRUCTOR)
4209 HOST_WIDE_INT ix = find_array_ctor_elt (ary, index);
4210 found = (ix >= 0);
4211 if (found)
4212 i = ix;
4214 else
4216 i = tree_to_shwi (index);
4217 found = (i < len);
4220 if (found)
4222 tree r;
4223 if (TREE_CODE (ary) == CONSTRUCTOR)
4224 r = (*CONSTRUCTOR_ELTS (ary))[i].value;
4225 else if (TREE_CODE (ary) == VECTOR_CST)
4226 r = VECTOR_CST_ELT (ary, i);
4227 else
4228 r = extract_string_elt (ary, elem_nchars, i);
4230 if (r)
4231 /* Don't VERIFY_CONSTANT here. */
4232 return r;
4234 /* Otherwise the element doesn't have a value yet. */
4237 /* Not found. */
4239 if (TREE_CODE (ary) == CONSTRUCTOR
4240 && CONSTRUCTOR_NO_CLEARING (ary))
4242 /* 'ary' is part of the aggregate initializer we're currently
4243 building; if there's no initializer for this element yet,
4244 that's an error. */
4245 if (!ctx->quiet)
4246 error ("accessing uninitialized array element");
4247 *non_constant_p = true;
4248 return t;
4251 /* If it's within the array bounds but doesn't have an explicit
4252 initializer, it's initialized from {}. But use build_value_init
4253 directly for non-aggregates to avoid creating a garbage CONSTRUCTOR. */
4254 tree val;
4255 constexpr_ctx new_ctx;
4256 if (is_really_empty_class (elem_type, /*ignore_vptr*/false))
4257 return build_constructor (elem_type, NULL);
4258 else if (CP_AGGREGATE_TYPE_P (elem_type))
4260 tree empty_ctor = build_constructor (init_list_type_node, NULL);
4261 val = digest_init (elem_type, empty_ctor, tf_warning_or_error);
4263 else
4264 val = build_value_init (elem_type, tf_warning_or_error);
4266 if (!SCALAR_TYPE_P (elem_type))
4268 new_ctx = *ctx;
4269 if (ctx->object)
4270 /* If there was no object, don't add one: it could confuse us
4271 into thinking we're modifying a const object. */
4272 new_ctx.object = t;
4273 new_ctx.ctor = build_constructor (elem_type, NULL);
4274 ctx = &new_ctx;
4276 t = cxx_eval_constant_expression (ctx, val, lval, non_constant_p,
4277 overflow_p);
4278 if (!SCALAR_TYPE_P (elem_type) && t != ctx->ctor)
4279 free_constructor (ctx->ctor);
4280 return t;
4283 /* Subroutine of cxx_eval_constant_expression.
4284 Attempt to reduce a field access of a value of class type. */
4286 static tree
4287 cxx_eval_component_reference (const constexpr_ctx *ctx, tree t,
4288 value_cat lval,
4289 bool *non_constant_p, bool *overflow_p)
4291 unsigned HOST_WIDE_INT i;
4292 tree field;
4293 tree value;
4294 tree part = TREE_OPERAND (t, 1);
4295 tree orig_whole = TREE_OPERAND (t, 0);
4296 tree whole = cxx_eval_constant_expression (ctx, orig_whole,
4297 lval,
4298 non_constant_p, overflow_p);
4299 if (*non_constant_p)
4300 return t;
4301 if (INDIRECT_REF_P (whole)
4302 && integer_zerop (TREE_OPERAND (whole, 0)))
4304 if (!ctx->quiet)
4305 error ("dereferencing a null pointer in %qE", orig_whole);
4306 *non_constant_p = true;
4307 return t;
4310 if (TREE_CODE (whole) == PTRMEM_CST)
4311 whole = cplus_expand_constant (whole);
4312 if (whole == orig_whole)
4313 return t;
4314 if (lval == vc_discard)
4315 return t;
4316 if (lval)
4317 return fold_build3 (COMPONENT_REF, TREE_TYPE (t),
4318 whole, part, NULL_TREE);
4319 /* Don't VERIFY_CONSTANT here; we only want to check that we got a
4320 CONSTRUCTOR. */
4321 if (TREE_CODE (whole) != CONSTRUCTOR)
4323 if (!ctx->quiet)
4324 error ("%qE is not a constant expression", orig_whole);
4325 *non_constant_p = true;
4326 return t;
4328 if ((cxx_dialect < cxx14 || CONSTRUCTOR_MUTABLE_POISON (whole))
4329 && DECL_MUTABLE_P (part))
4331 if (!ctx->quiet)
4332 error ("mutable %qD is not usable in a constant expression", part);
4333 *non_constant_p = true;
4334 return t;
4336 bool pmf = TYPE_PTRMEMFUNC_P (TREE_TYPE (whole));
4337 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
4339 /* Use name match for PMF fields, as a variant will have a
4340 different FIELD_DECL with a different type. */
4341 if (pmf ? DECL_NAME (field) == DECL_NAME (part)
4342 : field == part)
4344 if (value)
4346 STRIP_ANY_LOCATION_WRAPPER (value);
4347 return value;
4349 else
4350 /* We're in the middle of initializing it. */
4351 break;
4354 if (TREE_CODE (TREE_TYPE (whole)) == UNION_TYPE
4355 && CONSTRUCTOR_NELTS (whole) > 0)
4357 /* DR 1188 says we don't have to deal with this. */
4358 if (!ctx->quiet)
4360 constructor_elt *cep = CONSTRUCTOR_ELT (whole, 0);
4361 if (cep->value == NULL_TREE)
4362 error ("accessing uninitialized member %qD", part);
4363 else
4364 error ("accessing %qD member instead of initialized %qD member in "
4365 "constant expression", part, cep->index);
4367 *non_constant_p = true;
4368 return t;
4371 /* We only create a CONSTRUCTOR for a subobject when we modify it, so empty
4372 classes never get represented; throw together a value now. */
4373 if (is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
4374 return build_constructor (TREE_TYPE (t), NULL);
4376 gcc_assert (DECL_CONTEXT (part) == TYPE_MAIN_VARIANT (TREE_TYPE (whole)));
4378 if (CONSTRUCTOR_NO_CLEARING (whole))
4380 /* 'whole' is part of the aggregate initializer we're currently
4381 building; if there's no initializer for this member yet, that's an
4382 error. */
4383 if (!ctx->quiet)
4384 error ("accessing uninitialized member %qD", part);
4385 *non_constant_p = true;
4386 return t;
4389 /* If there's no explicit init for this field, it's value-initialized. */
4390 value = build_value_init (TREE_TYPE (t), tf_warning_or_error);
4391 return cxx_eval_constant_expression (ctx, value,
4392 lval,
4393 non_constant_p, overflow_p);
4396 /* Subroutine of cxx_eval_constant_expression.
4397 Attempt to reduce a field access of a value of class type that is
4398 expressed as a BIT_FIELD_REF. */
4400 static tree
4401 cxx_eval_bit_field_ref (const constexpr_ctx *ctx, tree t,
4402 value_cat lval,
4403 bool *non_constant_p, bool *overflow_p)
4405 tree orig_whole = TREE_OPERAND (t, 0);
4406 tree retval, fldval, utype, mask;
4407 bool fld_seen = false;
4408 HOST_WIDE_INT istart, isize;
4409 tree whole = cxx_eval_constant_expression (ctx, orig_whole,
4410 lval,
4411 non_constant_p, overflow_p);
4412 tree start, field, value;
4413 unsigned HOST_WIDE_INT i;
4415 if (whole == orig_whole)
4416 return t;
4417 /* Don't VERIFY_CONSTANT here; we only want to check that we got a
4418 CONSTRUCTOR. */
4419 if (!*non_constant_p
4420 && TREE_CODE (whole) != VECTOR_CST
4421 && TREE_CODE (whole) != CONSTRUCTOR)
4423 if (!ctx->quiet)
4424 error ("%qE is not a constant expression", orig_whole);
4425 *non_constant_p = true;
4427 if (*non_constant_p)
4428 return t;
4430 if (TREE_CODE (whole) == VECTOR_CST || !INTEGRAL_TYPE_P (TREE_TYPE (t)))
4432 if (tree r = fold_ternary (BIT_FIELD_REF, TREE_TYPE (t), whole,
4433 TREE_OPERAND (t, 1), TREE_OPERAND (t, 2)))
4434 return r;
4435 if (!ctx->quiet)
4436 error ("%qE is not a constant expression", orig_whole);
4437 *non_constant_p = true;
4438 return t;
4441 start = TREE_OPERAND (t, 2);
4442 istart = tree_to_shwi (start);
4443 isize = tree_to_shwi (TREE_OPERAND (t, 1));
4444 utype = TREE_TYPE (t);
4445 if (!TYPE_UNSIGNED (utype))
4446 utype = build_nonstandard_integer_type (TYPE_PRECISION (utype), 1);
4447 retval = build_int_cst (utype, 0);
4448 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
4450 tree bitpos = bit_position (field);
4451 STRIP_ANY_LOCATION_WRAPPER (value);
4452 if (bitpos == start && DECL_SIZE (field) == TREE_OPERAND (t, 1))
4453 return value;
4454 if (TREE_CODE (TREE_TYPE (field)) == INTEGER_TYPE
4455 && TREE_CODE (value) == INTEGER_CST
4456 && tree_fits_shwi_p (bitpos)
4457 && tree_fits_shwi_p (DECL_SIZE (field)))
4459 HOST_WIDE_INT bit = tree_to_shwi (bitpos);
4460 HOST_WIDE_INT sz = tree_to_shwi (DECL_SIZE (field));
4461 HOST_WIDE_INT shift;
4462 if (bit >= istart && bit + sz <= istart + isize)
4464 fldval = fold_convert (utype, value);
4465 mask = build_int_cst_type (utype, -1);
4466 mask = fold_build2 (LSHIFT_EXPR, utype, mask,
4467 size_int (TYPE_PRECISION (utype) - sz));
4468 mask = fold_build2 (RSHIFT_EXPR, utype, mask,
4469 size_int (TYPE_PRECISION (utype) - sz));
4470 fldval = fold_build2 (BIT_AND_EXPR, utype, fldval, mask);
4471 shift = bit - istart;
4472 if (BYTES_BIG_ENDIAN)
4473 shift = TYPE_PRECISION (utype) - shift - sz;
4474 fldval = fold_build2 (LSHIFT_EXPR, utype, fldval,
4475 size_int (shift));
4476 retval = fold_build2 (BIT_IOR_EXPR, utype, retval, fldval);
4477 fld_seen = true;
4481 if (fld_seen)
4482 return fold_convert (TREE_TYPE (t), retval);
4483 gcc_unreachable ();
4484 return error_mark_node;
4487 /* Helper for cxx_eval_bit_cast.
4488 Check [bit.cast]/3 rules, bit_cast is constexpr only if the To and From
4489 types and types of all subobjects have is_union_v<T>, is_pointer_v<T>,
4490 is_member_pointer_v<T>, is_volatile_v<T> false and has no non-static
4491 data members of reference type. */
4493 static bool
4494 check_bit_cast_type (const constexpr_ctx *ctx, location_t loc, tree type,
4495 tree orig_type)
4497 if (TREE_CODE (type) == UNION_TYPE)
4499 if (!ctx->quiet)
4501 if (type == orig_type)
4502 error_at (loc, "%qs is not a constant expression because %qT is "
4503 "a union type", "__builtin_bit_cast", type);
4504 else
4505 error_at (loc, "%qs is not a constant expression because %qT "
4506 "contains a union type", "__builtin_bit_cast",
4507 orig_type);
4509 return true;
4511 if (TREE_CODE (type) == POINTER_TYPE)
4513 if (!ctx->quiet)
4515 if (type == orig_type)
4516 error_at (loc, "%qs is not a constant expression because %qT is "
4517 "a pointer type", "__builtin_bit_cast", type);
4518 else
4519 error_at (loc, "%qs is not a constant expression because %qT "
4520 "contains a pointer type", "__builtin_bit_cast",
4521 orig_type);
4523 return true;
4525 if (TREE_CODE (type) == REFERENCE_TYPE)
4527 if (!ctx->quiet)
4529 if (type == orig_type)
4530 error_at (loc, "%qs is not a constant expression because %qT is "
4531 "a reference type", "__builtin_bit_cast", type);
4532 else
4533 error_at (loc, "%qs is not a constant expression because %qT "
4534 "contains a reference type", "__builtin_bit_cast",
4535 orig_type);
4537 return true;
4539 if (TYPE_PTRMEM_P (type))
4541 if (!ctx->quiet)
4543 if (type == orig_type)
4544 error_at (loc, "%qs is not a constant expression because %qT is "
4545 "a pointer to member type", "__builtin_bit_cast",
4546 type);
4547 else
4548 error_at (loc, "%qs is not a constant expression because %qT "
4549 "contains a pointer to member type",
4550 "__builtin_bit_cast", orig_type);
4552 return true;
4554 if (TYPE_VOLATILE (type))
4556 if (!ctx->quiet)
4558 if (type == orig_type)
4559 error_at (loc, "%qs is not a constant expression because %qT is "
4560 "volatile", "__builtin_bit_cast", type);
4561 else
4562 error_at (loc, "%qs is not a constant expression because %qT "
4563 "contains a volatile subobject",
4564 "__builtin_bit_cast", orig_type);
4566 return true;
4568 if (TREE_CODE (type) == RECORD_TYPE)
4569 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
4570 if (TREE_CODE (field) == FIELD_DECL
4571 && check_bit_cast_type (ctx, loc, TREE_TYPE (field), orig_type))
4572 return true;
4573 return false;
4576 /* Helper function for cxx_eval_bit_cast. For unsigned char or
4577 std::byte members of CONSTRUCTOR (recursively) if they contain
4578 some indeterminate bits (as set in MASK), remove the ctor elts,
4579 mark the CONSTRUCTOR as CONSTRUCTOR_NO_CLEARING and clear the
4580 bits in MASK. */
4582 static void
4583 clear_uchar_or_std_byte_in_mask (location_t loc, tree t, unsigned char *mask)
4585 if (TREE_CODE (t) != CONSTRUCTOR)
4586 return;
4588 unsigned i, j = 0;
4589 tree index, value;
4590 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (t), i, index, value)
4592 tree type = TREE_TYPE (value);
4593 if (TREE_CODE (TREE_TYPE (t)) != ARRAY_TYPE
4594 && DECL_BIT_FIELD_TYPE (index) != NULL_TREE)
4596 if (is_byte_access_type_not_plain_char (DECL_BIT_FIELD_TYPE (index)))
4598 HOST_WIDE_INT fldsz = TYPE_PRECISION (TREE_TYPE (index));
4599 gcc_assert (fldsz != 0);
4600 HOST_WIDE_INT pos = int_byte_position (index);
4601 HOST_WIDE_INT bpos
4602 = tree_to_uhwi (DECL_FIELD_BIT_OFFSET (index));
4603 bpos %= BITS_PER_UNIT;
4604 HOST_WIDE_INT end
4605 = ROUND_UP (bpos + fldsz, BITS_PER_UNIT) / BITS_PER_UNIT;
4606 gcc_assert (end == 1 || end == 2);
4607 unsigned char *p = mask + pos;
4608 unsigned char mask_save[2];
4609 mask_save[0] = mask[pos];
4610 mask_save[1] = end == 2 ? mask[pos + 1] : 0;
4611 if (BYTES_BIG_ENDIAN != WORDS_BIG_ENDIAN)
4612 sorry_at (loc, "PDP11 bit-field handling unsupported"
4613 " in %qs", "__builtin_bit_cast");
4614 else if (BYTES_BIG_ENDIAN)
4616 /* Big endian. */
4617 if (bpos + fldsz <= BITS_PER_UNIT)
4618 *p &= ~(((1 << fldsz) - 1)
4619 << (BITS_PER_UNIT - bpos - fldsz));
4620 else
4622 gcc_assert (bpos);
4623 *p &= ~(((1U << BITS_PER_UNIT) - 1) >> bpos);
4624 p++;
4625 fldsz -= BITS_PER_UNIT - bpos;
4626 gcc_assert (fldsz && fldsz < BITS_PER_UNIT);
4627 *p &= ((1U << BITS_PER_UNIT) - 1) >> fldsz;
4630 else
4632 /* Little endian. */
4633 if (bpos + fldsz <= BITS_PER_UNIT)
4634 *p &= ~(((1 << fldsz) - 1) << bpos);
4635 else
4637 gcc_assert (bpos);
4638 *p &= ~(((1 << BITS_PER_UNIT) - 1) << bpos);
4639 p++;
4640 fldsz -= BITS_PER_UNIT - bpos;
4641 gcc_assert (fldsz && fldsz < BITS_PER_UNIT);
4642 *p &= ~((1 << fldsz) - 1);
4645 if (mask_save[0] != mask[pos]
4646 || (end == 2 && mask_save[1] != mask[pos + 1]))
4648 CONSTRUCTOR_NO_CLEARING (t) = 1;
4649 continue;
4653 else if (is_byte_access_type_not_plain_char (type))
4655 HOST_WIDE_INT pos;
4656 if (TREE_CODE (TREE_TYPE (t)) == ARRAY_TYPE)
4657 pos = tree_to_shwi (index);
4658 else
4659 pos = int_byte_position (index);
4660 if (mask[pos])
4662 CONSTRUCTOR_NO_CLEARING (t) = 1;
4663 mask[pos] = 0;
4664 continue;
4667 if (TREE_CODE (value) == CONSTRUCTOR)
4669 HOST_WIDE_INT pos;
4670 if (TREE_CODE (TREE_TYPE (t)) == ARRAY_TYPE)
4671 pos = tree_to_shwi (index)
4672 * tree_to_shwi (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (t))));
4673 else
4674 pos = int_byte_position (index);
4675 clear_uchar_or_std_byte_in_mask (loc, value, mask + pos);
4677 if (i != j)
4679 CONSTRUCTOR_ELT (t, j)->index = index;
4680 CONSTRUCTOR_ELT (t, j)->value = value;
4682 ++j;
4684 if (CONSTRUCTOR_NELTS (t) != j)
4685 vec_safe_truncate (CONSTRUCTOR_ELTS (t), j);
4688 /* Subroutine of cxx_eval_constant_expression.
4689 Attempt to evaluate a BIT_CAST_EXPR. */
4691 static tree
4692 cxx_eval_bit_cast (const constexpr_ctx *ctx, tree t, bool *non_constant_p,
4693 bool *overflow_p)
4695 if (check_bit_cast_type (ctx, EXPR_LOCATION (t), TREE_TYPE (t),
4696 TREE_TYPE (t))
4697 || check_bit_cast_type (ctx, cp_expr_loc_or_loc (TREE_OPERAND (t, 0),
4698 EXPR_LOCATION (t)),
4699 TREE_TYPE (TREE_OPERAND (t, 0)),
4700 TREE_TYPE (TREE_OPERAND (t, 0))))
4702 *non_constant_p = true;
4703 return t;
4706 tree op = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), vc_prvalue,
4707 non_constant_p, overflow_p);
4708 if (*non_constant_p)
4709 return t;
4711 location_t loc = EXPR_LOCATION (t);
4712 if (BITS_PER_UNIT != 8 || CHAR_BIT != 8)
4714 if (!ctx->quiet)
4715 sorry_at (loc, "%qs cannot be constant evaluated on the target",
4716 "__builtin_bit_cast");
4717 *non_constant_p = true;
4718 return t;
4721 if (!tree_fits_shwi_p (TYPE_SIZE_UNIT (TREE_TYPE (t))))
4723 if (!ctx->quiet)
4724 sorry_at (loc, "%qs cannot be constant evaluated because the "
4725 "type is too large", "__builtin_bit_cast");
4726 *non_constant_p = true;
4727 return t;
4730 HOST_WIDE_INT len = tree_to_shwi (TYPE_SIZE_UNIT (TREE_TYPE (t)));
4731 if (len < 0 || (int) len != len)
4733 if (!ctx->quiet)
4734 sorry_at (loc, "%qs cannot be constant evaluated because the "
4735 "type is too large", "__builtin_bit_cast");
4736 *non_constant_p = true;
4737 return t;
4740 unsigned char buf[64];
4741 unsigned char *ptr, *mask;
4742 size_t alen = (size_t) len * 2;
4743 if (alen <= sizeof (buf))
4744 ptr = buf;
4745 else
4746 ptr = XNEWVEC (unsigned char, alen);
4747 mask = ptr + (size_t) len;
4748 /* At the beginning consider everything indeterminate. */
4749 memset (mask, ~0, (size_t) len);
4751 if (native_encode_initializer (op, ptr, len, 0, mask) != len)
4753 if (!ctx->quiet)
4754 sorry_at (loc, "%qs cannot be constant evaluated because the "
4755 "argument cannot be encoded", "__builtin_bit_cast");
4756 *non_constant_p = true;
4757 if (ptr != buf)
4758 XDELETE (ptr);
4759 return t;
4762 tree r = NULL_TREE;
4763 if (can_native_interpret_type_p (TREE_TYPE (t)))
4765 r = native_interpret_expr (TREE_TYPE (t), ptr, len);
4766 if (is_byte_access_type_not_plain_char (TREE_TYPE (t)))
4768 gcc_assert (len == 1);
4769 if (mask[0])
4771 memset (mask, 0, len);
4772 r = build_constructor (TREE_TYPE (r), NULL);
4773 CONSTRUCTOR_NO_CLEARING (r) = 1;
4777 else if (TREE_CODE (TREE_TYPE (t)) == RECORD_TYPE)
4779 r = native_interpret_aggregate (TREE_TYPE (t), ptr, 0, len);
4780 if (r != NULL_TREE)
4782 clear_type_padding_in_mask (TREE_TYPE (t), mask);
4783 clear_uchar_or_std_byte_in_mask (loc, r, mask);
4787 if (r != NULL_TREE)
4789 for (int i = 0; i < len; i++)
4790 if (mask[i])
4792 if (!ctx->quiet)
4793 error_at (loc, "%qs accessing uninitialized byte at offset %d",
4794 "__builtin_bit_cast", i);
4795 *non_constant_p = true;
4796 r = t;
4797 break;
4799 if (ptr != buf)
4800 XDELETE (ptr);
4801 return r;
4804 if (!ctx->quiet)
4805 sorry_at (loc, "%qs cannot be constant evaluated because the "
4806 "argument cannot be interpreted", "__builtin_bit_cast");
4807 *non_constant_p = true;
4808 if (ptr != buf)
4809 XDELETE (ptr);
4810 return t;
4813 /* Subroutine of cxx_eval_constant_expression.
4814 Evaluate a short-circuited logical expression T in the context
4815 of a given constexpr CALL. BAILOUT_VALUE is the value for
4816 early return. CONTINUE_VALUE is used here purely for
4817 sanity check purposes. */
4819 static tree
4820 cxx_eval_logical_expression (const constexpr_ctx *ctx, tree t,
4821 tree bailout_value, tree continue_value,
4822 bool *non_constant_p, bool *overflow_p)
4824 tree r;
4825 tree lhs = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
4826 vc_prvalue, non_constant_p,
4827 overflow_p);
4828 VERIFY_CONSTANT (lhs);
4829 if (tree_int_cst_equal (lhs, bailout_value))
4830 return lhs;
4831 gcc_assert (tree_int_cst_equal (lhs, continue_value));
4832 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
4833 vc_prvalue, non_constant_p,
4834 overflow_p);
4835 VERIFY_CONSTANT (r);
4836 return r;
4839 /* REF is a COMPONENT_REF designating a particular field. V is a vector of
4840 CONSTRUCTOR elements to initialize (part of) an object containing that
4841 field. Return a pointer to the constructor_elt corresponding to the
4842 initialization of the field. */
4844 static constructor_elt *
4845 base_field_constructor_elt (vec<constructor_elt, va_gc> *v, tree ref)
4847 tree aggr = TREE_OPERAND (ref, 0);
4848 tree field = TREE_OPERAND (ref, 1);
4849 HOST_WIDE_INT i;
4850 constructor_elt *ce;
4852 gcc_assert (TREE_CODE (ref) == COMPONENT_REF);
4854 if (TREE_CODE (aggr) == COMPONENT_REF)
4856 constructor_elt *base_ce
4857 = base_field_constructor_elt (v, aggr);
4858 v = CONSTRUCTOR_ELTS (base_ce->value);
4861 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
4862 if (ce->index == field)
4863 return ce;
4865 gcc_unreachable ();
4866 return NULL;
4869 /* Some of the expressions fed to the constexpr mechanism are calls to
4870 constructors, which have type void. In that case, return the type being
4871 initialized by the constructor. */
4873 static tree
4874 initialized_type (tree t)
4876 if (TYPE_P (t))
4877 return t;
4878 tree type = TREE_TYPE (t);
4879 if (TREE_CODE (t) == CALL_EXPR)
4881 /* A constructor call has void type, so we need to look deeper. */
4882 tree fn = get_function_named_in_call (t);
4883 if (fn && TREE_CODE (fn) == FUNCTION_DECL
4884 && DECL_CXX_CONSTRUCTOR_P (fn))
4885 type = DECL_CONTEXT (fn);
4887 else if (TREE_CODE (t) == COMPOUND_EXPR)
4888 return initialized_type (TREE_OPERAND (t, 1));
4889 else if (TREE_CODE (t) == AGGR_INIT_EXPR)
4890 type = TREE_TYPE (AGGR_INIT_EXPR_SLOT (t));
4891 return cv_unqualified (type);
4894 /* We're about to initialize element INDEX of an array or class from VALUE.
4895 Set up NEW_CTX appropriately by adjusting .object to refer to the
4896 subobject and creating a new CONSTRUCTOR if the element is itself
4897 a class or array. */
4899 static void
4900 init_subob_ctx (const constexpr_ctx *ctx, constexpr_ctx &new_ctx,
4901 tree index, tree &value)
4903 new_ctx = *ctx;
4905 if (index && TREE_CODE (index) != INTEGER_CST
4906 && TREE_CODE (index) != FIELD_DECL
4907 && TREE_CODE (index) != RANGE_EXPR)
4908 /* This won't have an element in the new CONSTRUCTOR. */
4909 return;
4911 tree type = initialized_type (value);
4912 if (!AGGREGATE_TYPE_P (type) && !VECTOR_TYPE_P (type))
4913 /* A non-aggregate member doesn't get its own CONSTRUCTOR. */
4914 return;
4915 if (VECTOR_TYPE_P (type)
4916 && VECTOR_TYPE_P (TREE_TYPE (ctx->ctor))
4917 && index == NULL_TREE)
4918 /* A vector inside of a vector CONSTRUCTOR, e.g. when a larger
4919 vector is constructed from smaller vectors, doesn't get its own
4920 CONSTRUCTOR either. */
4921 return;
4923 /* The sub-aggregate initializer might contain a placeholder;
4924 update object to refer to the subobject and ctor to refer to
4925 the (newly created) sub-initializer. */
4926 if (ctx->object)
4928 if (index == NULL_TREE || TREE_CODE (index) == RANGE_EXPR)
4929 /* There's no well-defined subobject for this index. */
4930 new_ctx.object = NULL_TREE;
4931 else
4932 new_ctx.object = build_ctor_subob_ref (index, type, ctx->object);
4935 if (is_empty_class (type))
4936 /* Leave ctor null for an empty subobject, they aren't represented in the
4937 result of evaluation. */
4938 new_ctx.ctor = NULL_TREE;
4939 else
4941 tree elt = build_constructor (type, NULL);
4942 CONSTRUCTOR_NO_CLEARING (elt) = true;
4943 new_ctx.ctor = elt;
4946 if (TREE_CODE (value) == TARGET_EXPR)
4947 /* Avoid creating another CONSTRUCTOR when we expand the TARGET_EXPR. */
4948 value = TARGET_EXPR_INITIAL (value);
4951 /* We're about to process an initializer for a class or array TYPE. Make
4952 sure that CTX is set up appropriately. */
4954 static void
4955 verify_ctor_sanity (const constexpr_ctx *ctx, tree type)
4957 /* We don't bother building a ctor for an empty base subobject. */
4958 if (is_empty_class (type))
4959 return;
4961 /* We're in the middle of an initializer that might involve placeholders;
4962 our caller should have created a CONSTRUCTOR for us to put the
4963 initializer into. We will either return that constructor or T. */
4964 gcc_assert (ctx->ctor);
4965 gcc_assert (same_type_ignoring_top_level_qualifiers_p
4966 (type, TREE_TYPE (ctx->ctor)));
4967 /* We used to check that ctx->ctor was empty, but that isn't the case when
4968 the object is zero-initialized before calling the constructor. */
4969 if (ctx->object)
4971 tree otype = TREE_TYPE (ctx->object);
4972 gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, otype)
4973 /* Handle flexible array members. */
4974 || (TREE_CODE (otype) == ARRAY_TYPE
4975 && TYPE_DOMAIN (otype) == NULL_TREE
4976 && TREE_CODE (type) == ARRAY_TYPE
4977 && (same_type_ignoring_top_level_qualifiers_p
4978 (TREE_TYPE (type), TREE_TYPE (otype)))));
4980 gcc_assert (!ctx->object || !DECL_P (ctx->object)
4981 || ctx->global->get_value (ctx->object) == ctx->ctor);
4984 /* Subroutine of cxx_eval_constant_expression.
4985 The expression tree T denotes a C-style array or a C-style
4986 aggregate. Reduce it to a constant expression. */
4988 static tree
4989 cxx_eval_bare_aggregate (const constexpr_ctx *ctx, tree t,
4990 value_cat lval,
4991 bool *non_constant_p, bool *overflow_p)
4993 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
4994 bool changed = false;
4995 gcc_assert (!BRACE_ENCLOSED_INITIALIZER_P (t));
4996 tree type = TREE_TYPE (t);
4998 constexpr_ctx new_ctx;
4999 if (TYPE_PTRMEMFUNC_P (type) || VECTOR_TYPE_P (type))
5001 /* We don't really need the ctx->ctor business for a PMF or
5002 vector, but it's simpler to use the same code. */
5003 new_ctx = *ctx;
5004 new_ctx.ctor = build_constructor (type, NULL);
5005 new_ctx.object = NULL_TREE;
5006 ctx = &new_ctx;
5008 verify_ctor_sanity (ctx, type);
5009 vec<constructor_elt, va_gc> **p = nullptr;
5010 if (ctx->ctor)
5012 p = &CONSTRUCTOR_ELTS (ctx->ctor);
5013 vec_alloc (*p, vec_safe_length (v));
5014 if (CONSTRUCTOR_PLACEHOLDER_BOUNDARY (t))
5015 CONSTRUCTOR_PLACEHOLDER_BOUNDARY (ctx->ctor) = 1;
5018 unsigned i;
5019 tree index, value;
5020 bool constant_p = true;
5021 bool side_effects_p = false;
5022 FOR_EACH_CONSTRUCTOR_ELT (v, i, index, value)
5024 tree orig_value = value;
5025 /* Like in cxx_eval_store_expression, omit entries for empty fields. */
5026 bool no_slot = TREE_CODE (type) == RECORD_TYPE && is_empty_field (index);
5027 init_subob_ctx (ctx, new_ctx, index, value);
5028 int pos_hint = -1;
5029 if (new_ctx.ctor != ctx->ctor && !no_slot)
5031 /* If we built a new CONSTRUCTOR, attach it now so that other
5032 initializers can refer to it. */
5033 constructor_elt *cep = get_or_insert_ctor_field (ctx->ctor, index);
5034 cep->value = new_ctx.ctor;
5035 pos_hint = cep - (*p)->begin();
5037 else if (TREE_CODE (type) == UNION_TYPE)
5038 /* Otherwise if we're constructing a non-aggregate union member, set
5039 the active union member now so that we can later detect and diagnose
5040 if its initializer attempts to activate another member. */
5041 get_or_insert_ctor_field (ctx->ctor, index);
5042 tree elt = cxx_eval_constant_expression (&new_ctx, value,
5043 lval,
5044 non_constant_p, overflow_p);
5045 /* Don't VERIFY_CONSTANT here. */
5046 if (ctx->quiet && *non_constant_p)
5047 break;
5048 if (elt != orig_value)
5049 changed = true;
5051 if (!TREE_CONSTANT (elt))
5052 constant_p = false;
5053 if (TREE_SIDE_EFFECTS (elt))
5054 side_effects_p = true;
5055 if (index && TREE_CODE (index) == COMPONENT_REF)
5057 /* This is an initialization of a vfield inside a base
5058 subaggregate that we already initialized; push this
5059 initialization into the previous initialization. */
5060 constructor_elt *inner = base_field_constructor_elt (*p, index);
5061 inner->value = elt;
5062 changed = true;
5064 else if (no_slot)
5065 /* This is an initializer for an empty field; now that we've
5066 checked that it's constant, we can ignore it. */
5067 changed = true;
5068 else if (index
5069 && (TREE_CODE (index) == NOP_EXPR
5070 || TREE_CODE (index) == POINTER_PLUS_EXPR))
5072 /* Old representation of empty bases. FIXME remove. */
5073 gcc_checking_assert (false);
5074 gcc_assert (is_empty_class (TREE_TYPE (TREE_TYPE (index))));
5075 changed = true;
5077 else
5079 if (TREE_CODE (type) == UNION_TYPE
5080 && (*p)->last().index != index)
5081 /* The initializer erroneously changed the active union member that
5082 we're initializing. */
5083 gcc_assert (*non_constant_p);
5084 else
5086 /* The initializer might have mutated the underlying CONSTRUCTOR,
5087 so recompute the location of the target constructer_elt. */
5088 constructor_elt *cep
5089 = get_or_insert_ctor_field (ctx->ctor, index, pos_hint);
5090 cep->value = elt;
5093 /* Adding or replacing an element might change the ctor's flags. */
5094 TREE_CONSTANT (ctx->ctor) = constant_p;
5095 TREE_SIDE_EFFECTS (ctx->ctor) = side_effects_p;
5098 if (*non_constant_p)
5099 return t;
5100 if (!changed)
5102 if (VECTOR_TYPE_P (type))
5103 t = fold (t);
5104 return t;
5106 t = ctx->ctor;
5107 if (!t)
5108 t = build_constructor (type, NULL);
5109 /* We're done building this CONSTRUCTOR, so now we can interpret an
5110 element without an explicit initializer as value-initialized. */
5111 CONSTRUCTOR_NO_CLEARING (t) = false;
5112 TREE_CONSTANT (t) = constant_p;
5113 TREE_SIDE_EFFECTS (t) = side_effects_p;
5114 if (VECTOR_TYPE_P (type))
5115 t = fold (t);
5116 return t;
5119 /* Subroutine of cxx_eval_constant_expression.
5120 The expression tree T is a VEC_INIT_EXPR which denotes the desired
5121 initialization of a non-static data member of array type. Reduce it to a
5122 CONSTRUCTOR.
5124 Note that apart from value-initialization (when VALUE_INIT is true),
5125 this is only intended to support value-initialization and the
5126 initializations done by defaulted constructors for classes with
5127 non-static data members of array type. In this case, VEC_INIT_EXPR_INIT
5128 will either be NULL_TREE for the default constructor, or a COMPONENT_REF
5129 for the copy/move constructor. */
5131 static tree
5132 cxx_eval_vec_init_1 (const constexpr_ctx *ctx, tree atype, tree init,
5133 bool value_init, value_cat lval,
5134 bool *non_constant_p, bool *overflow_p)
5136 tree elttype = TREE_TYPE (atype);
5137 verify_ctor_sanity (ctx, atype);
5138 vec<constructor_elt, va_gc> **p = &CONSTRUCTOR_ELTS (ctx->ctor);
5139 bool pre_init = false;
5140 unsigned HOST_WIDE_INT i;
5141 tsubst_flags_t complain = ctx->quiet ? tf_none : tf_warning_or_error;
5143 if (init && TREE_CODE (init) == CONSTRUCTOR)
5144 return cxx_eval_bare_aggregate (ctx, init, lval,
5145 non_constant_p, overflow_p);
5147 /* For the default constructor, build up a call to the default
5148 constructor of the element type. We only need to handle class types
5149 here, as for a constructor to be constexpr, all members must be
5150 initialized, which for a defaulted default constructor means they must
5151 be of a class type with a constexpr default constructor. */
5152 if (TREE_CODE (elttype) == ARRAY_TYPE)
5153 /* We only do this at the lowest level. */;
5154 else if (value_init)
5156 init = build_value_init (elttype, complain);
5157 pre_init = true;
5159 else if (!init)
5161 releasing_vec argvec;
5162 init = build_special_member_call (NULL_TREE, complete_ctor_identifier,
5163 &argvec, elttype, LOOKUP_NORMAL,
5164 complain);
5165 init = build_aggr_init_expr (elttype, init);
5166 pre_init = true;
5169 bool zeroed_out = false;
5170 if (!CONSTRUCTOR_NO_CLEARING (ctx->ctor))
5172 /* We're initializing an array object that had been zero-initialized
5173 earlier. Truncate ctx->ctor, and propagate its zeroed state by
5174 clearing CONSTRUCTOR_NO_CLEARING on each of the aggregate element
5175 initializers we append to it. */
5176 gcc_checking_assert (initializer_zerop (ctx->ctor));
5177 zeroed_out = true;
5178 vec_safe_truncate (*p, 0);
5181 tree nelts = get_array_or_vector_nelts (ctx, atype, non_constant_p,
5182 overflow_p);
5183 unsigned HOST_WIDE_INT max = tree_to_uhwi (nelts);
5184 for (i = 0; i < max; ++i)
5186 tree idx = build_int_cst (size_type_node, i);
5187 tree eltinit;
5188 bool reuse = false;
5189 constexpr_ctx new_ctx;
5190 init_subob_ctx (ctx, new_ctx, idx, pre_init ? init : elttype);
5191 if (new_ctx.ctor != ctx->ctor)
5193 if (zeroed_out)
5194 CONSTRUCTOR_NO_CLEARING (new_ctx.ctor) = false;
5195 CONSTRUCTOR_APPEND_ELT (*p, idx, new_ctx.ctor);
5197 if (TREE_CODE (elttype) == ARRAY_TYPE)
5199 /* A multidimensional array; recurse. */
5200 if (value_init || init == NULL_TREE)
5202 eltinit = NULL_TREE;
5203 reuse = i == 0;
5205 else
5206 eltinit = cp_build_array_ref (input_location, init, idx, complain);
5207 eltinit = cxx_eval_vec_init_1 (&new_ctx, elttype, eltinit, value_init,
5208 lval,
5209 non_constant_p, overflow_p);
5211 else if (pre_init)
5213 /* Initializing an element using value or default initialization
5214 we just pre-built above. */
5215 if (init == void_node)
5216 /* Trivial default-init, don't do anything to the CONSTRUCTOR. */
5217 return ctx->ctor;
5218 eltinit = cxx_eval_constant_expression (&new_ctx, init, lval,
5219 non_constant_p, overflow_p);
5220 reuse = i == 0;
5222 else
5224 /* Copying an element. */
5225 gcc_assert (same_type_ignoring_top_level_qualifiers_p
5226 (atype, TREE_TYPE (init)));
5227 eltinit = cp_build_array_ref (input_location, init, idx, complain);
5228 if (!lvalue_p (init))
5229 eltinit = move (eltinit);
5230 eltinit = force_rvalue (eltinit, complain);
5231 eltinit = cxx_eval_constant_expression (&new_ctx, eltinit, lval,
5232 non_constant_p, overflow_p);
5234 if (*non_constant_p)
5235 break;
5236 if (new_ctx.ctor != ctx->ctor)
5238 /* We appended this element above; update the value. */
5239 gcc_assert ((*p)->last().index == idx);
5240 (*p)->last().value = eltinit;
5242 else
5243 CONSTRUCTOR_APPEND_ELT (*p, idx, eltinit);
5244 /* Reuse the result of cxx_eval_constant_expression call
5245 from the first iteration to all others if it is a constant
5246 initializer that doesn't require relocations. */
5247 if (reuse
5248 && max > 1
5249 && (eltinit == NULL_TREE
5250 || (initializer_constant_valid_p (eltinit, TREE_TYPE (eltinit))
5251 == null_pointer_node)))
5253 if (new_ctx.ctor != ctx->ctor)
5254 eltinit = new_ctx.ctor;
5255 tree range = build2 (RANGE_EXPR, size_type_node,
5256 build_int_cst (size_type_node, 1),
5257 build_int_cst (size_type_node, max - 1));
5258 CONSTRUCTOR_APPEND_ELT (*p, range, unshare_constructor (eltinit));
5259 break;
5261 else if (i == 0)
5262 vec_safe_reserve (*p, max);
5265 if (!*non_constant_p)
5267 init = ctx->ctor;
5268 CONSTRUCTOR_NO_CLEARING (init) = false;
5270 return init;
5273 static tree
5274 cxx_eval_vec_init (const constexpr_ctx *ctx, tree t,
5275 value_cat lval,
5276 bool *non_constant_p, bool *overflow_p)
5278 tree atype = TREE_TYPE (t);
5279 tree init = VEC_INIT_EXPR_INIT (t);
5280 bool value_init = VEC_INIT_EXPR_VALUE_INIT (t);
5281 if (!init || !BRACE_ENCLOSED_INITIALIZER_P (init))
5283 else if (CONSTRUCTOR_NELTS (init) == 0
5284 && !CP_AGGREGATE_TYPE_P (strip_array_types (atype)))
5286 /* Handle {} as value-init. */
5287 init = NULL_TREE;
5288 value_init = true;
5290 else
5292 /* This is a more complicated case, like needing to loop over trailing
5293 elements; call build_vec_init and evaluate the result. */
5294 tsubst_flags_t complain = ctx->quiet ? tf_none : tf_warning_or_error;
5295 constexpr_ctx new_ctx = *ctx;
5296 if (!ctx->object)
5298 /* We want to have an initialization target for an VEC_INIT_EXPR.
5299 If we don't already have one in CTX, use the VEC_INIT_EXPR_SLOT. */
5300 new_ctx.object = VEC_INIT_EXPR_SLOT (t);
5301 tree ctor = new_ctx.ctor = build_constructor (atype, NULL);
5302 CONSTRUCTOR_NO_CLEARING (ctor) = true;
5303 ctx->global->put_value (new_ctx.object, ctor);
5304 ctx = &new_ctx;
5306 init = expand_vec_init_expr (ctx->object, t, complain);
5307 return cxx_eval_constant_expression (ctx, init, lval, non_constant_p,
5308 overflow_p);
5310 tree r = cxx_eval_vec_init_1 (ctx, atype, init, value_init,
5311 lval, non_constant_p, overflow_p);
5312 if (*non_constant_p)
5313 return t;
5314 else
5315 return r;
5318 /* Like same_type_ignoring_top_level_qualifiers_p, but also handle the case
5319 where the desired type is an array of unknown bounds because the variable
5320 has had its bounds deduced since the wrapping expression was created. */
5322 static bool
5323 same_type_ignoring_tlq_and_bounds_p (tree type1, tree type2)
5325 while (TREE_CODE (type1) == ARRAY_TYPE
5326 && TREE_CODE (type2) == ARRAY_TYPE
5327 && (!TYPE_DOMAIN (type1) || !TYPE_DOMAIN (type2)))
5329 type1 = TREE_TYPE (type1);
5330 type2 = TREE_TYPE (type2);
5332 return same_type_ignoring_top_level_qualifiers_p (type1, type2);
5335 /* Try to determine the currently active union member for an expression
5336 with UNION_TYPE. If it can be determined, return the FIELD_DECL,
5337 otherwise return NULL_TREE. */
5339 static tree
5340 cxx_union_active_member (const constexpr_ctx *ctx, tree t)
5342 constexpr_ctx new_ctx = *ctx;
5343 new_ctx.quiet = true;
5344 bool non_constant_p = false, overflow_p = false;
5345 tree ctor = cxx_eval_constant_expression (&new_ctx, t, vc_prvalue,
5346 &non_constant_p,
5347 &overflow_p);
5348 if (TREE_CODE (ctor) == CONSTRUCTOR
5349 && CONSTRUCTOR_NELTS (ctor) == 1
5350 && CONSTRUCTOR_ELT (ctor, 0)->index
5351 && TREE_CODE (CONSTRUCTOR_ELT (ctor, 0)->index) == FIELD_DECL)
5352 return CONSTRUCTOR_ELT (ctor, 0)->index;
5353 return NULL_TREE;
5356 /* Helper function for cxx_fold_indirect_ref_1, called recursively. */
5358 static tree
5359 cxx_fold_indirect_ref_1 (const constexpr_ctx *ctx, location_t loc, tree type,
5360 tree op, unsigned HOST_WIDE_INT off, bool *empty_base)
5362 tree optype = TREE_TYPE (op);
5363 unsigned HOST_WIDE_INT const_nunits;
5364 if (off == 0 && similar_type_p (optype, type))
5365 return op;
5366 else if (TREE_CODE (optype) == COMPLEX_TYPE
5367 && similar_type_p (type, TREE_TYPE (optype)))
5369 /* *(foo *)&complexfoo => __real__ complexfoo */
5370 if (off == 0)
5371 return build1_loc (loc, REALPART_EXPR, type, op);
5372 /* ((foo*)&complexfoo)[1] => __imag__ complexfoo */
5373 else if (tree_to_uhwi (TYPE_SIZE_UNIT (type)) == off)
5374 return build1_loc (loc, IMAGPART_EXPR, type, op);
5376 /* ((foo*)&vectorfoo)[x] => BIT_FIELD_REF<vectorfoo,...> */
5377 else if (VECTOR_TYPE_P (optype)
5378 && similar_type_p (type, TREE_TYPE (optype))
5379 && TYPE_VECTOR_SUBPARTS (optype).is_constant (&const_nunits))
5381 unsigned HOST_WIDE_INT part_width = tree_to_uhwi (TYPE_SIZE_UNIT (type));
5382 unsigned HOST_WIDE_INT max_offset = part_width * const_nunits;
5383 if (off < max_offset && off % part_width == 0)
5385 tree index = bitsize_int (off * BITS_PER_UNIT);
5386 return build3_loc (loc, BIT_FIELD_REF, type, op,
5387 TYPE_SIZE (type), index);
5390 /* ((foo *)&fooarray)[x] => fooarray[x] */
5391 else if (TREE_CODE (optype) == ARRAY_TYPE
5392 && tree_fits_uhwi_p (TYPE_SIZE_UNIT (TREE_TYPE (optype)))
5393 && !integer_zerop (TYPE_SIZE_UNIT (TREE_TYPE (optype))))
5395 tree type_domain = TYPE_DOMAIN (optype);
5396 tree min_val = size_zero_node;
5397 if (type_domain && TYPE_MIN_VALUE (type_domain))
5398 min_val = TYPE_MIN_VALUE (type_domain);
5399 unsigned HOST_WIDE_INT el_sz
5400 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (optype)));
5401 unsigned HOST_WIDE_INT idx = off / el_sz;
5402 unsigned HOST_WIDE_INT rem = off % el_sz;
5403 if (tree_fits_uhwi_p (min_val))
5405 tree index = size_int (idx + tree_to_uhwi (min_val));
5406 op = build4_loc (loc, ARRAY_REF, TREE_TYPE (optype), op, index,
5407 NULL_TREE, NULL_TREE);
5408 return cxx_fold_indirect_ref_1 (ctx, loc, type, op, rem,
5409 empty_base);
5412 /* ((foo *)&struct_with_foo_field)[x] => COMPONENT_REF */
5413 else if (TREE_CODE (optype) == RECORD_TYPE
5414 || TREE_CODE (optype) == UNION_TYPE)
5416 if (TREE_CODE (optype) == UNION_TYPE)
5417 /* For unions prefer the currently active member. */
5418 if (tree field = cxx_union_active_member (ctx, op))
5420 unsigned HOST_WIDE_INT el_sz
5421 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (field)));
5422 if (off < el_sz)
5424 tree cop = build3 (COMPONENT_REF, TREE_TYPE (field),
5425 op, field, NULL_TREE);
5426 if (tree ret = cxx_fold_indirect_ref_1 (ctx, loc, type, cop,
5427 off, empty_base))
5428 return ret;
5431 for (tree field = TYPE_FIELDS (optype);
5432 field; field = DECL_CHAIN (field))
5433 if (TREE_CODE (field) == FIELD_DECL
5434 && TREE_TYPE (field) != error_mark_node
5435 && tree_fits_uhwi_p (TYPE_SIZE_UNIT (TREE_TYPE (field))))
5437 tree pos = byte_position (field);
5438 if (!tree_fits_uhwi_p (pos))
5439 continue;
5440 unsigned HOST_WIDE_INT upos = tree_to_uhwi (pos);
5441 unsigned HOST_WIDE_INT el_sz
5442 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (field)));
5443 if (upos <= off && off < upos + el_sz)
5445 tree cop = build3 (COMPONENT_REF, TREE_TYPE (field),
5446 op, field, NULL_TREE);
5447 if (tree ret = cxx_fold_indirect_ref_1 (ctx, loc, type, cop,
5448 off - upos,
5449 empty_base))
5450 return ret;
5453 /* Also handle conversion to an empty base class, which
5454 is represented with a NOP_EXPR. */
5455 if (is_empty_class (type)
5456 && CLASS_TYPE_P (optype)
5457 && DERIVED_FROM_P (type, optype))
5459 if (empty_base)
5460 *empty_base = true;
5461 return op;
5465 return NULL_TREE;
5468 /* A less strict version of fold_indirect_ref_1, which requires cv-quals to
5469 match. We want to be less strict for simple *& folding; if we have a
5470 non-const temporary that we access through a const pointer, that should
5471 work. We handle this here rather than change fold_indirect_ref_1
5472 because we're dealing with things like ADDR_EXPR of INTEGER_CST which
5473 don't really make sense outside of constant expression evaluation. Also
5474 we want to allow folding to COMPONENT_REF, which could cause trouble
5475 with TBAA in fold_indirect_ref_1. */
5477 static tree
5478 cxx_fold_indirect_ref (const constexpr_ctx *ctx, location_t loc, tree type,
5479 tree op0, bool *empty_base /* = NULL*/)
5481 tree sub = op0;
5482 tree subtype;
5483 poly_uint64 const_op01;
5485 /* STRIP_NOPS, but stop if REINTERPRET_CAST_P. */
5486 while (CONVERT_EXPR_P (sub) || TREE_CODE (sub) == NON_LVALUE_EXPR
5487 || TREE_CODE (sub) == VIEW_CONVERT_EXPR)
5489 if (TREE_CODE (sub) == NOP_EXPR
5490 && REINTERPRET_CAST_P (sub))
5491 return NULL_TREE;
5492 sub = TREE_OPERAND (sub, 0);
5495 subtype = TREE_TYPE (sub);
5496 if (!INDIRECT_TYPE_P (subtype))
5497 return NULL_TREE;
5499 /* Canonicalizes the given OBJ/OFF pair by iteratively absorbing
5500 the innermost component into the offset until it would make the
5501 offset positive, so that cxx_fold_indirect_ref_1 can identify
5502 more folding opportunities. */
5503 auto canonicalize_obj_off = [] (tree& obj, tree& off) {
5504 while (TREE_CODE (obj) == COMPONENT_REF
5505 && (tree_int_cst_sign_bit (off) || integer_zerop (off)))
5507 tree field = TREE_OPERAND (obj, 1);
5508 tree pos = byte_position (field);
5509 if (integer_zerop (off) && integer_nonzerop (pos))
5510 /* If the offset is already 0, keep going as long as the
5511 component is at position 0. */
5512 break;
5513 off = int_const_binop (PLUS_EXPR, off, pos);
5514 obj = TREE_OPERAND (obj, 0);
5518 if (TREE_CODE (sub) == ADDR_EXPR)
5520 tree op = TREE_OPERAND (sub, 0);
5521 tree optype = TREE_TYPE (op);
5523 /* *&CONST_DECL -> to the value of the const decl. */
5524 if (TREE_CODE (op) == CONST_DECL)
5525 return DECL_INITIAL (op);
5526 /* *&p => p; make sure to handle *&"str"[cst] here. */
5527 if (similar_type_p (optype, type))
5529 tree fop = fold_read_from_constant_string (op);
5530 if (fop)
5531 return fop;
5532 else
5533 return op;
5535 else
5537 tree off = integer_zero_node;
5538 canonicalize_obj_off (op, off);
5539 gcc_assert (integer_zerop (off));
5540 return cxx_fold_indirect_ref_1 (ctx, loc, type, op, 0, empty_base);
5543 else if (TREE_CODE (sub) == POINTER_PLUS_EXPR
5544 && tree_fits_uhwi_p (TREE_OPERAND (sub, 1)))
5546 tree op00 = TREE_OPERAND (sub, 0);
5547 tree off = TREE_OPERAND (sub, 1);
5549 STRIP_NOPS (op00);
5550 if (TREE_CODE (op00) == ADDR_EXPR)
5552 tree obj = TREE_OPERAND (op00, 0);
5553 canonicalize_obj_off (obj, off);
5554 return cxx_fold_indirect_ref_1 (ctx, loc, type, obj,
5555 tree_to_uhwi (off), empty_base);
5558 /* *(foo *)fooarrptr => (*fooarrptr)[0] */
5559 else if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
5560 && similar_type_p (type, TREE_TYPE (TREE_TYPE (subtype))))
5562 tree type_domain;
5563 tree min_val = size_zero_node;
5564 tree newsub
5565 = cxx_fold_indirect_ref (ctx, loc, TREE_TYPE (subtype), sub, NULL);
5566 if (newsub)
5567 sub = newsub;
5568 else
5569 sub = build1_loc (loc, INDIRECT_REF, TREE_TYPE (subtype), sub);
5570 type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
5571 if (type_domain && TYPE_MIN_VALUE (type_domain))
5572 min_val = TYPE_MIN_VALUE (type_domain);
5573 return build4_loc (loc, ARRAY_REF, type, sub, min_val, NULL_TREE,
5574 NULL_TREE);
5577 return NULL_TREE;
5580 static tree
5581 cxx_eval_indirect_ref (const constexpr_ctx *ctx, tree t,
5582 value_cat lval,
5583 bool *non_constant_p, bool *overflow_p)
5585 tree orig_op0 = TREE_OPERAND (t, 0);
5586 bool empty_base = false;
5588 /* We can handle a MEM_REF like an INDIRECT_REF, if MEM_REF's second
5589 operand is an integer-zero. Otherwise reject the MEM_REF for now. */
5591 if (TREE_CODE (t) == MEM_REF
5592 && (!TREE_OPERAND (t, 1) || !integer_zerop (TREE_OPERAND (t, 1))))
5594 gcc_assert (ctx->quiet);
5595 *non_constant_p = true;
5596 return t;
5599 /* First try to simplify it directly. */
5600 tree r = cxx_fold_indirect_ref (ctx, EXPR_LOCATION (t), TREE_TYPE (t),
5601 orig_op0, &empty_base);
5602 if (!r)
5604 /* If that didn't work, evaluate the operand first. */
5605 tree op0 = cxx_eval_constant_expression (ctx, orig_op0,
5606 vc_prvalue, non_constant_p,
5607 overflow_p);
5608 /* Don't VERIFY_CONSTANT here. */
5609 if (*non_constant_p)
5610 return t;
5612 if (!lval && integer_zerop (op0))
5614 if (!ctx->quiet)
5615 error ("dereferencing a null pointer");
5616 *non_constant_p = true;
5617 return t;
5620 r = cxx_fold_indirect_ref (ctx, EXPR_LOCATION (t), TREE_TYPE (t), op0,
5621 &empty_base);
5622 if (r == NULL_TREE)
5624 /* We couldn't fold to a constant value. Make sure it's not
5625 something we should have been able to fold. */
5626 tree sub = op0;
5627 STRIP_NOPS (sub);
5628 if (TREE_CODE (sub) == ADDR_EXPR)
5630 gcc_assert (!similar_type_p
5631 (TREE_TYPE (TREE_TYPE (sub)), TREE_TYPE (t)));
5632 /* DR 1188 says we don't have to deal with this. */
5633 if (!ctx->quiet)
5634 error_at (cp_expr_loc_or_input_loc (t),
5635 "accessing value of %qE through a %qT glvalue in a "
5636 "constant expression", build_fold_indirect_ref (sub),
5637 TREE_TYPE (t));
5638 *non_constant_p = true;
5639 return t;
5642 if (lval == vc_glvalue && op0 != orig_op0)
5643 return build1 (INDIRECT_REF, TREE_TYPE (t), op0);
5644 if (!lval)
5645 VERIFY_CONSTANT (t);
5646 return t;
5650 r = cxx_eval_constant_expression (ctx, r,
5651 lval, non_constant_p, overflow_p);
5652 if (*non_constant_p)
5653 return t;
5655 /* If we're pulling out the value of an empty base, just return an empty
5656 CONSTRUCTOR. */
5657 if (empty_base && !lval)
5659 r = build_constructor (TREE_TYPE (t), NULL);
5660 TREE_CONSTANT (r) = true;
5663 return r;
5666 /* Complain about R, a VAR_DECL, not being usable in a constant expression.
5667 FUNDEF_P is true if we're checking a constexpr function body.
5668 Shared between potential_constant_expression and
5669 cxx_eval_constant_expression. */
5671 static void
5672 non_const_var_error (location_t loc, tree r, bool fundef_p)
5674 auto_diagnostic_group d;
5675 tree type = TREE_TYPE (r);
5676 if (DECL_NAME (r) == heap_uninit_identifier
5677 || DECL_NAME (r) == heap_identifier
5678 || DECL_NAME (r) == heap_vec_uninit_identifier
5679 || DECL_NAME (r) == heap_vec_identifier)
5681 if (constexpr_error (loc, fundef_p, "the content of uninitialized "
5682 "storage is not usable in a constant expression"))
5683 inform (DECL_SOURCE_LOCATION (r), "allocated here");
5684 return;
5686 if (DECL_NAME (r) == heap_deleted_identifier)
5688 if (constexpr_error (loc, fundef_p, "use of allocated storage after "
5689 "deallocation in a constant expression"))
5690 inform (DECL_SOURCE_LOCATION (r), "allocated here");
5691 return;
5693 if (!constexpr_error (loc, fundef_p, "the value of %qD is not usable in "
5694 "a constant expression", r))
5695 return;
5696 /* Avoid error cascade. */
5697 if (DECL_INITIAL (r) == error_mark_node)
5698 return;
5699 if (DECL_DECLARED_CONSTEXPR_P (r))
5700 inform (DECL_SOURCE_LOCATION (r),
5701 "%qD used in its own initializer", r);
5702 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5704 if (!CP_TYPE_CONST_P (type))
5705 inform (DECL_SOURCE_LOCATION (r),
5706 "%q#D is not const", r);
5707 else if (CP_TYPE_VOLATILE_P (type))
5708 inform (DECL_SOURCE_LOCATION (r),
5709 "%q#D is volatile", r);
5710 else if (!DECL_INITIAL (r)
5711 || !TREE_CONSTANT (DECL_INITIAL (r))
5712 || !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r))
5713 inform (DECL_SOURCE_LOCATION (r),
5714 "%qD was not initialized with a constant "
5715 "expression", r);
5716 else
5717 gcc_unreachable ();
5719 else if (TYPE_REF_P (type))
5720 inform (DECL_SOURCE_LOCATION (r),
5721 "%qD was not initialized with a constant "
5722 "expression", r);
5723 else
5725 if (cxx_dialect >= cxx11 && !DECL_DECLARED_CONSTEXPR_P (r))
5726 inform (DECL_SOURCE_LOCATION (r),
5727 "%qD was not declared %<constexpr%>", r);
5728 else
5729 inform (DECL_SOURCE_LOCATION (r),
5730 "%qD does not have integral or enumeration type",
5735 /* Subroutine of cxx_eval_constant_expression.
5736 Like cxx_eval_unary_expression, except for trinary expressions. */
5738 static tree
5739 cxx_eval_trinary_expression (const constexpr_ctx *ctx, tree t,
5740 value_cat lval,
5741 bool *non_constant_p, bool *overflow_p)
5743 int i;
5744 tree args[3];
5745 tree val;
5747 for (i = 0; i < 3; i++)
5749 args[i] = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, i),
5750 lval,
5751 non_constant_p, overflow_p);
5752 VERIFY_CONSTANT (args[i]);
5755 val = fold_ternary_loc (EXPR_LOCATION (t), TREE_CODE (t), TREE_TYPE (t),
5756 args[0], args[1], args[2]);
5757 if (val == NULL_TREE)
5758 return t;
5759 VERIFY_CONSTANT (val);
5760 return val;
5763 /* True if T was declared in a function declared to be constexpr, and
5764 therefore potentially constant in C++14. */
5766 bool
5767 var_in_constexpr_fn (tree t)
5769 tree ctx = DECL_CONTEXT (t);
5770 return (ctx && TREE_CODE (ctx) == FUNCTION_DECL
5771 && DECL_DECLARED_CONSTEXPR_P (ctx));
5774 /* True if a function might be constexpr: either a function that was
5775 declared constexpr, or a C++17 lambda op(). */
5777 bool
5778 maybe_constexpr_fn (tree t)
5780 return (DECL_DECLARED_CONSTEXPR_P (t)
5781 || (cxx_dialect >= cxx17 && LAMBDA_FUNCTION_P (t))
5782 || (flag_implicit_constexpr
5783 && DECL_DECLARED_INLINE_P (STRIP_TEMPLATE (t))));
5786 /* True if T was declared in a function that might be constexpr: either a
5787 function that was declared constexpr, or a C++17 lambda op(). */
5789 bool
5790 var_in_maybe_constexpr_fn (tree t)
5792 return (DECL_FUNCTION_SCOPE_P (t)
5793 && maybe_constexpr_fn (DECL_CONTEXT (t)));
5796 /* We're assigning INIT to TARGET. In do_build_copy_constructor and
5797 build_over_call we implement trivial copy of a class with tail padding using
5798 assignment of character arrays, which is valid in normal code, but not in
5799 constexpr evaluation. We don't need to worry about clobbering tail padding
5800 in constexpr evaluation, so strip the type punning. */
5802 static void
5803 maybe_simplify_trivial_copy (tree &target, tree &init)
5805 if (TREE_CODE (target) == MEM_REF
5806 && TREE_CODE (init) == MEM_REF
5807 && TREE_TYPE (target) == TREE_TYPE (init)
5808 && TREE_CODE (TREE_TYPE (target)) == ARRAY_TYPE
5809 && TREE_TYPE (TREE_TYPE (target)) == unsigned_char_type_node)
5811 target = build_fold_indirect_ref (TREE_OPERAND (target, 0));
5812 init = build_fold_indirect_ref (TREE_OPERAND (init, 0));
5816 /* Returns true if REF, which is a COMPONENT_REF, has any fields
5817 of constant type. This does not check for 'mutable', so the
5818 caller is expected to be mindful of that. */
5820 static bool
5821 cref_has_const_field (tree ref)
5823 while (TREE_CODE (ref) == COMPONENT_REF)
5825 if (CP_TYPE_CONST_P (TREE_TYPE (TREE_OPERAND (ref, 1))))
5826 return true;
5827 ref = TREE_OPERAND (ref, 0);
5829 return false;
5832 /* Return true if we are modifying something that is const during constant
5833 expression evaluation. CODE is the code of the statement, OBJ is the
5834 object in question, MUTABLE_P is true if one of the subobjects were
5835 declared mutable. */
5837 static bool
5838 modifying_const_object_p (tree_code code, tree obj, bool mutable_p)
5840 /* If this is initialization, there's no problem. */
5841 if (code != MODIFY_EXPR)
5842 return false;
5844 /* [basic.type.qualifier] "A const object is an object of type
5845 const T or a non-mutable subobject of a const object." */
5846 if (mutable_p)
5847 return false;
5849 if (TREE_READONLY (obj))
5850 return true;
5852 if (CP_TYPE_CONST_P (TREE_TYPE (obj)))
5854 /* Although a COMPONENT_REF may have a const type, we should
5855 only consider it modifying a const object when any of the
5856 field components is const. This can happen when using
5857 constructs such as const_cast<const T &>(m), making something
5858 const even though it wasn't declared const. */
5859 if (TREE_CODE (obj) == COMPONENT_REF)
5860 return cref_has_const_field (obj);
5861 else
5862 return true;
5865 return false;
5868 /* Evaluate an INIT_EXPR or MODIFY_EXPR. */
5870 static tree
5871 cxx_eval_store_expression (const constexpr_ctx *ctx, tree t,
5872 value_cat lval,
5873 bool *non_constant_p, bool *overflow_p)
5875 constexpr_ctx new_ctx = *ctx;
5877 tree init = TREE_OPERAND (t, 1);
5878 if (TREE_CLOBBER_P (init))
5879 /* Just ignore clobbers. */
5880 return void_node;
5882 /* First we figure out where we're storing to. */
5883 tree target = TREE_OPERAND (t, 0);
5885 maybe_simplify_trivial_copy (target, init);
5887 tree type = TREE_TYPE (target);
5888 bool preeval = SCALAR_TYPE_P (type) || TREE_CODE (t) == MODIFY_EXPR;
5889 if (preeval)
5891 /* Evaluate the value to be stored without knowing what object it will be
5892 stored in, so that any side-effects happen first. */
5893 if (!SCALAR_TYPE_P (type))
5894 new_ctx.ctor = new_ctx.object = NULL_TREE;
5895 init = cxx_eval_constant_expression (&new_ctx, init, vc_prvalue,
5896 non_constant_p, overflow_p);
5897 if (*non_constant_p)
5898 return t;
5901 bool evaluated = false;
5902 if (lval == vc_glvalue)
5904 /* If we want to return a reference to the target, we need to evaluate it
5905 as a whole; otherwise, only evaluate the innermost piece to avoid
5906 building up unnecessary *_REFs. */
5907 target = cxx_eval_constant_expression (ctx, target, lval,
5908 non_constant_p, overflow_p);
5909 evaluated = true;
5910 if (*non_constant_p)
5911 return t;
5914 /* Find the underlying variable. */
5915 releasing_vec refs;
5916 tree object = NULL_TREE;
5917 /* If we're modifying a const object, save it. */
5918 tree const_object_being_modified = NULL_TREE;
5919 bool mutable_p = false;
5920 for (tree probe = target; object == NULL_TREE; )
5922 switch (TREE_CODE (probe))
5924 case BIT_FIELD_REF:
5925 case COMPONENT_REF:
5926 case ARRAY_REF:
5928 tree ob = TREE_OPERAND (probe, 0);
5929 tree elt = TREE_OPERAND (probe, 1);
5930 if (TREE_CODE (elt) == FIELD_DECL && DECL_MUTABLE_P (elt))
5931 mutable_p = true;
5932 if (TREE_CODE (probe) == ARRAY_REF)
5934 elt = eval_and_check_array_index (ctx, probe, false,
5935 non_constant_p, overflow_p);
5936 if (*non_constant_p)
5937 return t;
5939 /* We don't check modifying_const_object_p for ARRAY_REFs. Given
5940 "int a[10]", an ARRAY_REF "a[2]" can be "const int", even though
5941 the array isn't const. Instead, check "a" in the next iteration;
5942 that will detect modifying "const int a[10]". */
5943 else if (evaluated
5944 && modifying_const_object_p (TREE_CODE (t), probe,
5945 mutable_p)
5946 && const_object_being_modified == NULL_TREE)
5947 const_object_being_modified = probe;
5948 vec_safe_push (refs, elt);
5949 vec_safe_push (refs, TREE_TYPE (probe));
5950 probe = ob;
5952 break;
5954 case REALPART_EXPR:
5955 gcc_assert (probe == target);
5956 vec_safe_push (refs, probe);
5957 vec_safe_push (refs, TREE_TYPE (probe));
5958 probe = TREE_OPERAND (probe, 0);
5959 break;
5961 case IMAGPART_EXPR:
5962 gcc_assert (probe == target);
5963 vec_safe_push (refs, probe);
5964 vec_safe_push (refs, TREE_TYPE (probe));
5965 probe = TREE_OPERAND (probe, 0);
5966 break;
5968 default:
5969 if (evaluated)
5970 object = probe;
5971 else
5973 probe = cxx_eval_constant_expression (ctx, probe, vc_glvalue,
5974 non_constant_p, overflow_p);
5975 evaluated = true;
5976 if (*non_constant_p)
5977 return t;
5979 break;
5983 if (modifying_const_object_p (TREE_CODE (t), object, mutable_p)
5984 && const_object_being_modified == NULL_TREE)
5985 const_object_being_modified = object;
5987 /* And then find/build up our initializer for the path to the subobject
5988 we're initializing. */
5989 tree *valp;
5990 if (DECL_P (object))
5991 valp = ctx->global->get_value_ptr (object);
5992 else
5993 valp = NULL;
5994 if (!valp)
5996 /* A constant-expression cannot modify objects from outside the
5997 constant-expression. */
5998 if (!ctx->quiet)
5999 error ("modification of %qE is not a constant expression", object);
6000 *non_constant_p = true;
6001 return t;
6003 type = TREE_TYPE (object);
6004 bool no_zero_init = true;
6006 auto_vec<tree *> ctors;
6007 releasing_vec indexes;
6008 auto_vec<int> index_pos_hints;
6009 bool activated_union_member_p = false;
6010 bool empty_base = false;
6011 while (!refs->is_empty ())
6013 if (*valp == NULL_TREE)
6015 *valp = build_constructor (type, NULL);
6016 CONSTRUCTOR_NO_CLEARING (*valp) = no_zero_init;
6018 else if (TREE_CODE (*valp) == STRING_CST)
6020 /* An array was initialized with a string constant, and now
6021 we're writing into one of its elements. Explode the
6022 single initialization into a set of element
6023 initializations. */
6024 gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
6026 tree string = *valp;
6027 tree elt_type = TREE_TYPE (type);
6028 unsigned chars_per_elt = (TYPE_PRECISION (elt_type)
6029 / TYPE_PRECISION (char_type_node));
6030 unsigned num_elts = TREE_STRING_LENGTH (string) / chars_per_elt;
6031 tree ary_ctor = build_constructor (type, NULL);
6033 vec_safe_reserve (CONSTRUCTOR_ELTS (ary_ctor), num_elts);
6034 for (unsigned ix = 0; ix != num_elts; ix++)
6036 constructor_elt elt =
6038 build_int_cst (size_type_node, ix),
6039 extract_string_elt (string, chars_per_elt, ix)
6041 CONSTRUCTOR_ELTS (ary_ctor)->quick_push (elt);
6044 *valp = ary_ctor;
6047 enum tree_code code = TREE_CODE (type);
6048 tree reftype = refs->pop();
6049 tree index = refs->pop();
6051 if (code == COMPLEX_TYPE)
6053 if (TREE_CODE (*valp) == COMPLEX_CST)
6054 *valp = build2 (COMPLEX_EXPR, type, TREE_REALPART (*valp),
6055 TREE_IMAGPART (*valp));
6056 else if (TREE_CODE (*valp) == CONSTRUCTOR
6057 && CONSTRUCTOR_NELTS (*valp) == 0
6058 && CONSTRUCTOR_NO_CLEARING (*valp))
6060 tree r = build_constructor (reftype, NULL);
6061 CONSTRUCTOR_NO_CLEARING (r) = 1;
6062 *valp = build2 (COMPLEX_EXPR, type, r, r);
6064 gcc_assert (TREE_CODE (*valp) == COMPLEX_EXPR);
6065 ctors.safe_push (valp);
6066 vec_safe_push (indexes, index);
6067 valp = &TREE_OPERAND (*valp, TREE_CODE (index) == IMAGPART_EXPR);
6068 gcc_checking_assert (refs->is_empty ());
6069 type = reftype;
6070 break;
6073 /* If the value of object is already zero-initialized, any new ctors for
6074 subobjects will also be zero-initialized. */
6075 no_zero_init = CONSTRUCTOR_NO_CLEARING (*valp);
6077 if (code == RECORD_TYPE && is_empty_field (index))
6078 /* Don't build a sub-CONSTRUCTOR for an empty base or field, as they
6079 have no data and might have an offset lower than previously declared
6080 fields, which confuses the middle-end. The code below will notice
6081 that we don't have a CONSTRUCTOR for our inner target and just
6082 return init. */
6084 empty_base = true;
6085 break;
6088 type = reftype;
6090 if (code == UNION_TYPE && CONSTRUCTOR_NELTS (*valp)
6091 && CONSTRUCTOR_ELT (*valp, 0)->index != index)
6093 if (cxx_dialect < cxx20)
6095 if (!ctx->quiet)
6096 error_at (cp_expr_loc_or_input_loc (t),
6097 "change of the active member of a union "
6098 "from %qD to %qD",
6099 CONSTRUCTOR_ELT (*valp, 0)->index,
6100 index);
6101 *non_constant_p = true;
6103 else if (TREE_CODE (t) == MODIFY_EXPR
6104 && CONSTRUCTOR_NO_CLEARING (*valp))
6106 /* Diagnose changing the active union member while the union
6107 is in the process of being initialized. */
6108 if (!ctx->quiet)
6109 error_at (cp_expr_loc_or_input_loc (t),
6110 "change of the active member of a union "
6111 "from %qD to %qD during initialization",
6112 CONSTRUCTOR_ELT (*valp, 0)->index,
6113 index);
6114 *non_constant_p = true;
6116 no_zero_init = true;
6119 ctors.safe_push (valp);
6120 vec_safe_push (indexes, index);
6122 constructor_elt *cep
6123 = get_or_insert_ctor_field (*valp, index);
6124 index_pos_hints.safe_push (cep - CONSTRUCTOR_ELTS (*valp)->begin());
6126 if (code == UNION_TYPE)
6127 activated_union_member_p = true;
6129 valp = &cep->value;
6132 /* For initialization of an empty base, the original target will be
6133 *(base*)this, evaluation of which resolves to the object
6134 argument, which has the derived type rather than the base type. */
6135 if (!empty_base && !(same_type_ignoring_top_level_qualifiers_p
6136 (initialized_type (init), type)))
6138 gcc_assert (is_empty_class (TREE_TYPE (target)));
6139 empty_base = true;
6142 /* Detect modifying a constant object in constexpr evaluation.
6143 We have found a const object that is being modified. Figure out
6144 if we need to issue an error. Consider
6146 struct A {
6147 int n;
6148 constexpr A() : n(1) { n = 2; } // #1
6150 struct B {
6151 const A a;
6152 constexpr B() { a.n = 3; } // #2
6154 constexpr B b{};
6156 #1 is OK, since we're modifying an object under construction, but
6157 #2 is wrong, since "a" is const and has been fully constructed.
6158 To track it, we use the TREE_READONLY bit in the object's CONSTRUCTOR
6159 which means that the object is read-only. For the example above, the
6160 *ctors stack at the point of #2 will look like:
6162 ctors[0] = {.a={.n=2}} TREE_READONLY = 0
6163 ctors[1] = {.n=2} TREE_READONLY = 1
6165 and we're modifying "b.a", so we search the stack and see if the
6166 constructor for "b.a" has already run. */
6167 if (const_object_being_modified)
6169 bool fail = false;
6170 tree const_objtype
6171 = strip_array_types (TREE_TYPE (const_object_being_modified));
6172 if (!CLASS_TYPE_P (const_objtype))
6173 fail = true;
6174 else
6176 /* [class.ctor]p5 "A constructor can be invoked for a const,
6177 volatile, or const volatile object. const and volatile
6178 semantics are not applied on an object under construction.
6179 They come into effect when the constructor for the most
6180 derived object ends." */
6181 for (tree *elt : ctors)
6182 if (same_type_ignoring_top_level_qualifiers_p
6183 (TREE_TYPE (const_object_being_modified), TREE_TYPE (*elt)))
6185 fail = TREE_READONLY (*elt);
6186 break;
6189 if (fail)
6191 if (!ctx->quiet)
6192 modifying_const_object_error (t, const_object_being_modified);
6193 *non_constant_p = true;
6194 return t;
6198 if (!preeval)
6200 /* We're handling an INIT_EXPR of class type, so the value of the
6201 initializer can depend on the object it's initializing. */
6203 /* Create a new CONSTRUCTOR in case evaluation of the initializer
6204 wants to modify it. */
6205 if (*valp == NULL_TREE)
6207 *valp = build_constructor (type, NULL);
6208 CONSTRUCTOR_NO_CLEARING (*valp) = no_zero_init;
6210 new_ctx.ctor = empty_base ? NULL_TREE : *valp;
6211 new_ctx.object = target;
6212 /* Avoid temporary materialization when initializing from a TARGET_EXPR.
6213 We don't need to mess with AGGR_EXPR_SLOT/VEC_INIT_EXPR_SLOT because
6214 expansion of those trees uses ctx instead. */
6215 if (TREE_CODE (init) == TARGET_EXPR)
6216 if (tree tinit = TARGET_EXPR_INITIAL (init))
6217 init = tinit;
6218 init = cxx_eval_constant_expression (&new_ctx, init, vc_prvalue,
6219 non_constant_p, overflow_p);
6220 /* The hash table might have moved since the get earlier, and the
6221 initializer might have mutated the underlying CONSTRUCTORs, so we must
6222 recompute VALP. */
6223 valp = ctx->global->get_value_ptr (object);
6224 for (unsigned i = 0; i < vec_safe_length (indexes); i++)
6226 ctors[i] = valp;
6227 constructor_elt *cep
6228 = get_or_insert_ctor_field (*valp, indexes[i], index_pos_hints[i]);
6229 valp = &cep->value;
6233 if (*non_constant_p)
6234 return t;
6236 /* Don't share a CONSTRUCTOR that might be changed later. */
6237 init = unshare_constructor (init);
6239 gcc_checking_assert (!*valp || (same_type_ignoring_top_level_qualifiers_p
6240 (TREE_TYPE (*valp), type)));
6241 if (empty_base)
6243 /* Just evaluate the initializer and return, since there's no actual data
6244 to store, and we didn't build a CONSTRUCTOR. */
6245 if (!*valp)
6247 /* But do make sure we have something in *valp. */
6248 *valp = build_constructor (type, nullptr);
6249 CONSTRUCTOR_NO_CLEARING (*valp) = no_zero_init;
6252 else if (*valp && TREE_CODE (*valp) == CONSTRUCTOR
6253 && TREE_CODE (init) == CONSTRUCTOR)
6255 /* An outer ctx->ctor might be pointing to *valp, so replace
6256 its contents. */
6257 CONSTRUCTOR_ELTS (*valp) = CONSTRUCTOR_ELTS (init);
6258 TREE_CONSTANT (*valp) = TREE_CONSTANT (init);
6259 TREE_SIDE_EFFECTS (*valp) = TREE_SIDE_EFFECTS (init);
6260 CONSTRUCTOR_NO_CLEARING (*valp)
6261 = CONSTRUCTOR_NO_CLEARING (init);
6263 else
6264 *valp = init;
6266 /* After initialization, 'const' semantics apply to the value of the
6267 object. Make a note of this fact by marking the CONSTRUCTOR
6268 TREE_READONLY. */
6269 if (TREE_CODE (t) == INIT_EXPR
6270 && TREE_CODE (*valp) == CONSTRUCTOR
6271 && TYPE_READONLY (type))
6273 if (INDIRECT_REF_P (target)
6274 && (is_this_parameter
6275 (tree_strip_nop_conversions (TREE_OPERAND (target, 0)))))
6276 /* We've just initialized '*this' (perhaps via the target
6277 constructor of a delegating constructor). Leave it up to the
6278 caller that set 'this' to set TREE_READONLY appropriately. */
6279 gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
6280 (TREE_TYPE (target), type) || empty_base);
6281 else
6282 TREE_READONLY (*valp) = true;
6285 /* Update TREE_CONSTANT and TREE_SIDE_EFFECTS on enclosing
6286 CONSTRUCTORs, if any. */
6287 bool c = TREE_CONSTANT (init);
6288 bool s = TREE_SIDE_EFFECTS (init);
6289 if (!indexes->is_empty ())
6291 tree last = indexes->last ();
6292 if (TREE_CODE (last) == REALPART_EXPR
6293 || TREE_CODE (last) == IMAGPART_EXPR)
6295 /* And canonicalize COMPLEX_EXPR into COMPLEX_CST if
6296 possible. */
6297 tree *cexpr = ctors.last ();
6298 if (tree c = const_binop (COMPLEX_EXPR, TREE_TYPE (*cexpr),
6299 TREE_OPERAND (*cexpr, 0),
6300 TREE_OPERAND (*cexpr, 1)))
6301 *cexpr = c;
6302 else
6304 TREE_CONSTANT (*cexpr)
6305 = (TREE_CONSTANT (TREE_OPERAND (*cexpr, 0))
6306 & TREE_CONSTANT (TREE_OPERAND (*cexpr, 1)));
6307 TREE_SIDE_EFFECTS (*cexpr)
6308 = (TREE_SIDE_EFFECTS (TREE_OPERAND (*cexpr, 0))
6309 | TREE_SIDE_EFFECTS (TREE_OPERAND (*cexpr, 1)));
6311 c = TREE_CONSTANT (*cexpr);
6312 s = TREE_SIDE_EFFECTS (*cexpr);
6315 if (!c || s || activated_union_member_p)
6316 for (tree *elt : ctors)
6318 if (TREE_CODE (*elt) != CONSTRUCTOR)
6319 continue;
6320 if (!c)
6321 TREE_CONSTANT (*elt) = false;
6322 if (s)
6323 TREE_SIDE_EFFECTS (*elt) = true;
6324 /* Clear CONSTRUCTOR_NO_CLEARING since we've activated a member of
6325 this union. */
6326 if (TREE_CODE (TREE_TYPE (*elt)) == UNION_TYPE)
6327 CONSTRUCTOR_NO_CLEARING (*elt) = false;
6330 if (lval)
6331 return target;
6332 else
6333 return init;
6336 /* Evaluate a ++ or -- expression. */
6338 static tree
6339 cxx_eval_increment_expression (const constexpr_ctx *ctx, tree t,
6340 value_cat lval,
6341 bool *non_constant_p, bool *overflow_p)
6343 enum tree_code code = TREE_CODE (t);
6344 tree type = TREE_TYPE (t);
6345 tree op = TREE_OPERAND (t, 0);
6346 tree offset = TREE_OPERAND (t, 1);
6347 gcc_assert (TREE_CONSTANT (offset));
6349 /* OFFSET is constant, but perhaps not constant enough. We need to
6350 e.g. bash FLOAT_EXPRs to REAL_CSTs. */
6351 offset = fold_simple (offset);
6353 /* The operand as an lvalue. */
6354 op = cxx_eval_constant_expression (ctx, op, vc_glvalue,
6355 non_constant_p, overflow_p);
6357 /* The operand as an rvalue. */
6358 tree val
6359 = cxx_eval_constant_expression (ctx, op, vc_prvalue,
6360 non_constant_p, overflow_p);
6361 /* Don't VERIFY_CONSTANT if this might be dealing with a pointer to
6362 a local array in a constexpr function. */
6363 bool ptr = INDIRECT_TYPE_P (TREE_TYPE (val));
6364 if (!ptr)
6365 VERIFY_CONSTANT (val);
6367 /* The modified value. */
6368 bool inc = (code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR);
6369 tree mod;
6370 if (INDIRECT_TYPE_P (type))
6372 /* The middle end requires pointers to use POINTER_PLUS_EXPR. */
6373 offset = convert_to_ptrofftype (offset);
6374 if (!inc)
6375 offset = fold_build1 (NEGATE_EXPR, TREE_TYPE (offset), offset);
6376 mod = fold_build2 (POINTER_PLUS_EXPR, type, val, offset);
6378 else if (c_promoting_integer_type_p (type)
6379 && !TYPE_UNSIGNED (type)
6380 && TYPE_PRECISION (type) < TYPE_PRECISION (integer_type_node))
6382 offset = fold_convert (integer_type_node, offset);
6383 mod = fold_convert (integer_type_node, val);
6384 tree t = fold_build2 (inc ? PLUS_EXPR : MINUS_EXPR, integer_type_node,
6385 mod, offset);
6386 mod = fold_convert (type, t);
6387 if (TREE_OVERFLOW_P (mod) && !TREE_OVERFLOW_P (t))
6388 TREE_OVERFLOW (mod) = false;
6390 else
6391 mod = fold_build2 (inc ? PLUS_EXPR : MINUS_EXPR, type, val, offset);
6392 if (!ptr)
6393 VERIFY_CONSTANT (mod);
6395 /* Storing the modified value. */
6396 tree store = build2_loc (cp_expr_loc_or_loc (t, input_location),
6397 MODIFY_EXPR, type, op, mod);
6398 mod = cxx_eval_constant_expression (ctx, store, lval,
6399 non_constant_p, overflow_p);
6400 ggc_free (store);
6401 if (*non_constant_p)
6402 return t;
6404 /* And the value of the expression. */
6405 if (code == PREINCREMENT_EXPR || code == PREDECREMENT_EXPR)
6406 /* Prefix ops are lvalues, but the caller might want an rvalue;
6407 lval has already been taken into account in the store above. */
6408 return mod;
6409 else
6410 /* Postfix ops are rvalues. */
6411 return val;
6414 /* Predicates for the meaning of *jump_target. */
6416 static bool
6417 returns (tree *jump_target)
6419 return *jump_target
6420 && TREE_CODE (*jump_target) == RETURN_EXPR;
6423 static bool
6424 breaks (tree *jump_target)
6426 return *jump_target
6427 && ((TREE_CODE (*jump_target) == LABEL_DECL
6428 && LABEL_DECL_BREAK (*jump_target))
6429 || TREE_CODE (*jump_target) == BREAK_STMT
6430 || TREE_CODE (*jump_target) == EXIT_EXPR);
6433 static bool
6434 continues (tree *jump_target)
6436 return *jump_target
6437 && ((TREE_CODE (*jump_target) == LABEL_DECL
6438 && LABEL_DECL_CONTINUE (*jump_target))
6439 || TREE_CODE (*jump_target) == CONTINUE_STMT);
6443 static bool
6444 switches (tree *jump_target)
6446 return *jump_target
6447 && TREE_CODE (*jump_target) == INTEGER_CST;
6450 /* Subroutine of cxx_eval_statement_list. Determine whether the statement
6451 STMT matches *jump_target. If we're looking for a case label and we see
6452 the default label, note it in ctx->css_state. */
6454 static bool
6455 label_matches (const constexpr_ctx *ctx, tree *jump_target, tree stmt)
6457 switch (TREE_CODE (*jump_target))
6459 case LABEL_DECL:
6460 if (TREE_CODE (stmt) == LABEL_EXPR
6461 && LABEL_EXPR_LABEL (stmt) == *jump_target)
6462 return true;
6463 break;
6465 case INTEGER_CST:
6466 if (TREE_CODE (stmt) == CASE_LABEL_EXPR)
6468 gcc_assert (ctx->css_state != NULL);
6469 if (!CASE_LOW (stmt))
6471 /* default: should appear just once in a SWITCH_EXPR
6472 body (excluding nested SWITCH_EXPR). */
6473 gcc_assert (*ctx->css_state != css_default_seen);
6474 /* When evaluating SWITCH_EXPR body for the second time,
6475 return true for the default: label. */
6476 if (*ctx->css_state == css_default_processing)
6477 return true;
6478 *ctx->css_state = css_default_seen;
6480 else if (CASE_HIGH (stmt))
6482 if (tree_int_cst_le (CASE_LOW (stmt), *jump_target)
6483 && tree_int_cst_le (*jump_target, CASE_HIGH (stmt)))
6484 return true;
6486 else if (tree_int_cst_equal (*jump_target, CASE_LOW (stmt)))
6487 return true;
6489 break;
6491 case BREAK_STMT:
6492 case CONTINUE_STMT:
6493 /* These two are handled directly in cxx_eval_loop_expr by testing
6494 breaks (jump_target) or continues (jump_target). */
6495 break;
6497 default:
6498 gcc_unreachable ();
6500 return false;
6503 /* Evaluate a STATEMENT_LIST for side-effects. Handles various jump
6504 semantics, for switch, break, continue, and return. */
6506 static tree
6507 cxx_eval_statement_list (const constexpr_ctx *ctx, tree t,
6508 bool *non_constant_p, bool *overflow_p,
6509 tree *jump_target)
6511 tree local_target;
6512 /* In a statement-expression we want to return the last value.
6513 For empty statement expression return void_node. */
6514 tree r = void_node;
6515 if (!jump_target)
6517 local_target = NULL_TREE;
6518 jump_target = &local_target;
6520 for (tree_stmt_iterator i = tsi_start (t); !tsi_end_p (i); ++i)
6522 tree stmt = *i;
6524 /* We've found a continue, so skip everything until we reach
6525 the label its jumping to. */
6526 if (continues (jump_target))
6528 if (label_matches (ctx, jump_target, stmt))
6529 /* Found it. */
6530 *jump_target = NULL_TREE;
6531 else
6532 continue;
6534 if (TREE_CODE (stmt) == DEBUG_BEGIN_STMT)
6535 continue;
6537 value_cat lval = vc_discard;
6538 /* The result of a statement-expression is not wrapped in EXPR_STMT. */
6539 if (tsi_one_before_end_p (i) && TREE_CODE (stmt) != EXPR_STMT)
6540 lval = vc_prvalue;
6542 r = cxx_eval_constant_expression (ctx, stmt, lval,
6543 non_constant_p, overflow_p,
6544 jump_target);
6545 if (*non_constant_p)
6546 break;
6547 if (returns (jump_target) || breaks (jump_target))
6548 break;
6550 if (*jump_target && jump_target == &local_target)
6552 /* We aren't communicating the jump to our caller, so give up. We don't
6553 need to support evaluation of jumps out of statement-exprs. */
6554 if (!ctx->quiet)
6555 error_at (cp_expr_loc_or_input_loc (r),
6556 "statement is not a constant expression");
6557 *non_constant_p = true;
6559 return r;
6562 /* Evaluate a LOOP_EXPR for side-effects. Handles break and return
6563 semantics; continue semantics are covered by cxx_eval_statement_list. */
6565 static tree
6566 cxx_eval_loop_expr (const constexpr_ctx *ctx, tree t,
6567 bool *non_constant_p, bool *overflow_p,
6568 tree *jump_target)
6570 constexpr_ctx new_ctx = *ctx;
6571 tree local_target;
6572 if (!jump_target)
6574 local_target = NULL_TREE;
6575 jump_target = &local_target;
6578 tree body, cond = NULL_TREE, expr = NULL_TREE;
6579 int count = 0;
6580 switch (TREE_CODE (t))
6582 case LOOP_EXPR:
6583 body = LOOP_EXPR_BODY (t);
6584 break;
6585 case DO_STMT:
6586 body = DO_BODY (t);
6587 cond = DO_COND (t);
6588 break;
6589 case WHILE_STMT:
6590 body = WHILE_BODY (t);
6591 cond = WHILE_COND (t);
6592 count = -1;
6593 break;
6594 case FOR_STMT:
6595 if (FOR_INIT_STMT (t))
6596 cxx_eval_constant_expression (ctx, FOR_INIT_STMT (t), vc_discard,
6597 non_constant_p, overflow_p, jump_target);
6598 if (*non_constant_p)
6599 return NULL_TREE;
6600 body = FOR_BODY (t);
6601 cond = FOR_COND (t);
6602 expr = FOR_EXPR (t);
6603 count = -1;
6604 break;
6605 default:
6606 gcc_unreachable ();
6608 auto_vec<tree, 10> save_exprs;
6609 new_ctx.save_exprs = &save_exprs;
6612 if (count != -1)
6614 if (body)
6615 cxx_eval_constant_expression (&new_ctx, body, vc_discard,
6616 non_constant_p, overflow_p,
6617 jump_target);
6618 if (breaks (jump_target))
6620 *jump_target = NULL_TREE;
6621 break;
6624 if (TREE_CODE (t) != LOOP_EXPR && continues (jump_target))
6625 *jump_target = NULL_TREE;
6627 if (expr)
6628 cxx_eval_constant_expression (&new_ctx, expr, vc_prvalue,
6629 non_constant_p, overflow_p,
6630 jump_target);
6633 if (cond)
6635 tree res
6636 = cxx_eval_constant_expression (&new_ctx, cond, vc_prvalue,
6637 non_constant_p, overflow_p,
6638 jump_target);
6639 if (res)
6641 if (verify_constant (res, ctx->quiet, non_constant_p,
6642 overflow_p))
6643 break;
6644 if (integer_zerop (res))
6645 break;
6647 else
6648 gcc_assert (*jump_target);
6651 /* Forget saved values of SAVE_EXPRs and TARGET_EXPRs. */
6652 for (tree save_expr : save_exprs)
6653 ctx->global->remove_value (save_expr);
6654 save_exprs.truncate (0);
6656 if (++count >= constexpr_loop_limit)
6658 if (!ctx->quiet)
6659 error_at (cp_expr_loc_or_input_loc (t),
6660 "%<constexpr%> loop iteration count exceeds limit of %d "
6661 "(use %<-fconstexpr-loop-limit=%> to increase the limit)",
6662 constexpr_loop_limit);
6663 *non_constant_p = true;
6664 break;
6667 while (!returns (jump_target)
6668 && !breaks (jump_target)
6669 && !continues (jump_target)
6670 && (!switches (jump_target) || count == 0)
6671 && !*non_constant_p);
6673 /* Forget saved values of SAVE_EXPRs and TARGET_EXPRs. */
6674 for (tree save_expr : save_exprs)
6675 ctx->global->remove_value (save_expr);
6677 return NULL_TREE;
6680 /* Evaluate a SWITCH_EXPR for side-effects. Handles switch and break jump
6681 semantics. */
6683 static tree
6684 cxx_eval_switch_expr (const constexpr_ctx *ctx, tree t,
6685 bool *non_constant_p, bool *overflow_p,
6686 tree *jump_target)
6688 tree cond
6689 = TREE_CODE (t) == SWITCH_STMT ? SWITCH_STMT_COND (t) : SWITCH_COND (t);
6690 cond = cxx_eval_constant_expression (ctx, cond, vc_prvalue,
6691 non_constant_p, overflow_p);
6692 VERIFY_CONSTANT (cond);
6693 *jump_target = cond;
6695 tree body
6696 = TREE_CODE (t) == SWITCH_STMT ? SWITCH_STMT_BODY (t) : SWITCH_BODY (t);
6697 constexpr_ctx new_ctx = *ctx;
6698 constexpr_switch_state css = css_default_not_seen;
6699 new_ctx.css_state = &css;
6700 cxx_eval_constant_expression (&new_ctx, body, vc_discard,
6701 non_constant_p, overflow_p, jump_target);
6702 if (switches (jump_target) && css == css_default_seen)
6704 /* If the SWITCH_EXPR body has default: label, process it once again,
6705 this time instructing label_matches to return true for default:
6706 label on switches (jump_target). */
6707 css = css_default_processing;
6708 cxx_eval_constant_expression (&new_ctx, body, vc_discard,
6709 non_constant_p, overflow_p, jump_target);
6711 if (breaks (jump_target) || switches (jump_target))
6712 *jump_target = NULL_TREE;
6713 return NULL_TREE;
6716 /* Find the object of TYPE under initialization in CTX. */
6718 static tree
6719 lookup_placeholder (const constexpr_ctx *ctx, value_cat lval, tree type)
6721 if (!ctx)
6722 return NULL_TREE;
6724 /* Prefer the outermost matching object, but don't cross
6725 CONSTRUCTOR_PLACEHOLDER_BOUNDARY constructors. */
6726 if (ctx->ctor && !CONSTRUCTOR_PLACEHOLDER_BOUNDARY (ctx->ctor))
6727 if (tree outer_ob = lookup_placeholder (ctx->parent, lval, type))
6728 return outer_ob;
6730 /* We could use ctx->object unconditionally, but using ctx->ctor when we
6731 can is a minor optimization. */
6732 if (!lval && ctx->ctor && same_type_p (TREE_TYPE (ctx->ctor), type))
6733 return ctx->ctor;
6735 if (!ctx->object)
6736 return NULL_TREE;
6738 /* Since an object cannot have a field of its own type, we can search outward
6739 from ctx->object to find the unique containing object of TYPE. */
6740 tree ob = ctx->object;
6741 while (ob)
6743 if (same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (ob), type))
6744 break;
6745 if (handled_component_p (ob))
6746 ob = TREE_OPERAND (ob, 0);
6747 else
6748 ob = NULL_TREE;
6751 return ob;
6754 /* Complain about an attempt to evaluate inline assembly. If FUNDEF_P is
6755 true, we're checking a constexpr function body. */
6757 static void
6758 inline_asm_in_constexpr_error (location_t loc, bool fundef_p)
6760 auto_diagnostic_group d;
6761 if (constexpr_error (loc, fundef_p, "inline assembly is not a "
6762 "constant expression"))
6763 inform (loc, "only unevaluated inline assembly is allowed in a "
6764 "%<constexpr%> function in C++20");
6767 /* We're getting the constant value of DECL in a manifestly constant-evaluated
6768 context; maybe complain about that. */
6770 static void
6771 maybe_warn_about_constant_value (location_t loc, tree decl)
6773 static bool explained = false;
6774 if (cxx_dialect >= cxx17
6775 && warn_interference_size
6776 && !OPTION_SET_P (param_destruct_interfere_size)
6777 && DECL_CONTEXT (decl) == std_node
6778 && id_equal (DECL_NAME (decl), "hardware_destructive_interference_size")
6779 && (LOCATION_FILE (input_location) != main_input_filename
6780 || module_exporting_p ())
6781 && warning_at (loc, OPT_Winterference_size, "use of %qD", decl)
6782 && !explained)
6784 explained = true;
6785 inform (loc, "its value can vary between compiler versions or "
6786 "with different %<-mtune%> or %<-mcpu%> flags");
6787 inform (loc, "if this use is part of a public ABI, change it to "
6788 "instead use a constant variable you define");
6789 inform (loc, "the default value for the current CPU tuning "
6790 "is %d bytes", param_destruct_interfere_size);
6791 inform (loc, "you can stabilize this value with %<--param "
6792 "hardware_destructive_interference_size=%d%>, or disable "
6793 "this warning with %<-Wno-interference-size%>",
6794 param_destruct_interfere_size);
6798 /* For element type ELT_TYPE, return the appropriate type of the heap object
6799 containing such element(s). COOKIE_SIZE is NULL or the size of cookie
6800 in bytes. If COOKIE_SIZE is NULL, return array type
6801 ELT_TYPE[FULL_SIZE / sizeof(ELT_TYPE)], otherwise return
6802 struct { size_t[COOKIE_SIZE/sizeof(size_t)]; ELT_TYPE[N]; }
6803 where N is is computed such that the size of the struct fits into FULL_SIZE.
6804 If ARG_SIZE is non-NULL, it is the first argument to the new operator.
6805 It should be passed if ELT_TYPE is zero sized type in which case FULL_SIZE
6806 will be also 0 and so it is not possible to determine the actual array
6807 size. CTX, NON_CONSTANT_P and OVERFLOW_P are used during constant
6808 expression evaluation of subexpressions of ARG_SIZE. */
6810 static tree
6811 build_new_constexpr_heap_type (const constexpr_ctx *ctx, tree elt_type,
6812 tree cookie_size, tree full_size, tree arg_size,
6813 bool *non_constant_p, bool *overflow_p)
6815 gcc_assert (cookie_size == NULL_TREE || tree_fits_uhwi_p (cookie_size));
6816 gcc_assert (tree_fits_uhwi_p (full_size));
6817 unsigned HOST_WIDE_INT csz = cookie_size ? tree_to_uhwi (cookie_size) : 0;
6818 if (arg_size)
6820 STRIP_NOPS (arg_size);
6821 if (cookie_size)
6823 if (TREE_CODE (arg_size) != PLUS_EXPR)
6824 arg_size = NULL_TREE;
6825 else if (TREE_CODE (TREE_OPERAND (arg_size, 0)) == INTEGER_CST
6826 && tree_int_cst_equal (cookie_size,
6827 TREE_OPERAND (arg_size, 0)))
6829 arg_size = TREE_OPERAND (arg_size, 1);
6830 STRIP_NOPS (arg_size);
6832 else if (TREE_CODE (TREE_OPERAND (arg_size, 1)) == INTEGER_CST
6833 && tree_int_cst_equal (cookie_size,
6834 TREE_OPERAND (arg_size, 1)))
6836 arg_size = TREE_OPERAND (arg_size, 0);
6837 STRIP_NOPS (arg_size);
6839 else
6840 arg_size = NULL_TREE;
6842 if (arg_size && TREE_CODE (arg_size) == MULT_EXPR)
6844 tree op0 = TREE_OPERAND (arg_size, 0);
6845 tree op1 = TREE_OPERAND (arg_size, 1);
6846 if (integer_zerop (op0))
6847 arg_size
6848 = cxx_eval_constant_expression (ctx, op1, vc_prvalue,
6849 non_constant_p, overflow_p);
6850 else if (integer_zerop (op1))
6851 arg_size
6852 = cxx_eval_constant_expression (ctx, op0, vc_prvalue,
6853 non_constant_p, overflow_p);
6854 else
6855 arg_size = NULL_TREE;
6857 else
6858 arg_size = NULL_TREE;
6861 unsigned HOST_WIDE_INT fsz = tree_to_uhwi (arg_size ? arg_size : full_size);
6862 if (!arg_size)
6864 unsigned HOST_WIDE_INT esz = int_size_in_bytes (elt_type);
6865 gcc_assert (fsz >= csz);
6866 fsz -= csz;
6867 if (esz)
6868 fsz /= esz;
6870 tree itype2 = build_index_type (size_int (fsz - 1));
6871 if (!cookie_size)
6872 return build_cplus_array_type (elt_type, itype2);
6873 return build_new_constexpr_heap_type (elt_type, cookie_size, itype2);
6876 /* Attempt to reduce the expression T to a constant value.
6877 On failure, issue diagnostic and return error_mark_node. */
6878 /* FIXME unify with c_fully_fold */
6879 /* FIXME overflow_p is too global */
6881 static tree
6882 cxx_eval_constant_expression (const constexpr_ctx *ctx, tree t,
6883 value_cat lval,
6884 bool *non_constant_p, bool *overflow_p,
6885 tree *jump_target /* = NULL */)
6887 if (jump_target && *jump_target)
6889 /* If we are jumping, ignore all statements/expressions except those
6890 that could have LABEL_EXPR or CASE_LABEL_EXPR in their bodies. */
6891 switch (TREE_CODE (t))
6893 case BIND_EXPR:
6894 case STATEMENT_LIST:
6895 case LOOP_EXPR:
6896 case COND_EXPR:
6897 case IF_STMT:
6898 case DO_STMT:
6899 case WHILE_STMT:
6900 case FOR_STMT:
6901 break;
6902 case LABEL_EXPR:
6903 case CASE_LABEL_EXPR:
6904 if (label_matches (ctx, jump_target, t))
6905 /* Found it. */
6906 *jump_target = NULL_TREE;
6907 return NULL_TREE;
6908 default:
6909 return NULL_TREE;
6912 if (error_operand_p (t))
6914 *non_constant_p = true;
6915 return t;
6918 location_t loc = cp_expr_loc_or_input_loc (t);
6920 STRIP_ANY_LOCATION_WRAPPER (t);
6922 if (CONSTANT_CLASS_P (t))
6924 if (TREE_OVERFLOW (t))
6926 if (!ctx->quiet)
6927 permerror (input_location, "overflow in constant expression");
6928 if (!flag_permissive || ctx->quiet)
6929 *overflow_p = true;
6932 if (TREE_CODE (t) == INTEGER_CST
6933 && TYPE_PTR_P (TREE_TYPE (t))
6934 /* INTEGER_CST with pointer-to-method type is only used
6935 for a virtual method in a pointer to member function.
6936 Don't reject those. */
6937 && TREE_CODE (TREE_TYPE (TREE_TYPE (t))) != METHOD_TYPE
6938 && !integer_zerop (t))
6940 if (!ctx->quiet)
6941 error ("value %qE of type %qT is not a constant expression",
6942 t, TREE_TYPE (t));
6943 *non_constant_p = true;
6946 return t;
6949 /* Avoid excessively long constexpr evaluations. */
6950 if (++ctx->global->constexpr_ops_count >= constexpr_ops_limit)
6952 if (!ctx->quiet)
6953 error_at (loc,
6954 "%<constexpr%> evaluation operation count exceeds limit of "
6955 "%wd (use %<-fconstexpr-ops-limit=%> to increase the limit)",
6956 constexpr_ops_limit);
6957 ctx->global->constexpr_ops_count = INTTYPE_MINIMUM (HOST_WIDE_INT);
6958 *non_constant_p = true;
6959 return t;
6962 constexpr_ctx new_ctx;
6963 tree r = t;
6965 tree_code tcode = TREE_CODE (t);
6966 switch (tcode)
6968 case RESULT_DECL:
6969 if (lval)
6970 return t;
6971 /* We ask for an rvalue for the RESULT_DECL when indirecting
6972 through an invisible reference, or in named return value
6973 optimization. */
6974 if (tree v = ctx->global->get_value (t))
6975 return v;
6976 else
6978 if (!ctx->quiet)
6979 error ("%qE is not a constant expression", t);
6980 *non_constant_p = true;
6982 break;
6984 case VAR_DECL:
6985 if (DECL_HAS_VALUE_EXPR_P (t))
6987 if (is_normal_capture_proxy (t)
6988 && current_function_decl == DECL_CONTEXT (t))
6990 /* Function parms aren't constexpr within the function
6991 definition, so don't try to look at the closure. But if the
6992 captured variable is constant, try to evaluate it directly. */
6993 r = DECL_CAPTURED_VARIABLE (t);
6994 tree type = TREE_TYPE (t);
6995 if (TYPE_REF_P (type) != TYPE_REF_P (TREE_TYPE (r)))
6997 /* Adjust r to match the reference-ness of t. */
6998 if (TYPE_REF_P (type))
6999 r = build_address (r);
7000 else
7001 r = convert_from_reference (r);
7004 else
7005 r = DECL_VALUE_EXPR (t);
7006 return cxx_eval_constant_expression (ctx, r, lval, non_constant_p,
7007 overflow_p);
7009 /* fall through */
7010 case CONST_DECL:
7011 /* We used to not check lval for CONST_DECL, but darwin.cc uses
7012 CONST_DECL for aggregate constants. */
7013 if (lval)
7014 return t;
7015 else if (t == ctx->object)
7016 return ctx->ctor;
7017 if (VAR_P (t))
7018 if (tree v = ctx->global->get_value (t))
7020 r = v;
7021 break;
7023 if (ctx->manifestly_const_eval)
7024 maybe_warn_about_constant_value (loc, t);
7025 if (COMPLETE_TYPE_P (TREE_TYPE (t))
7026 && is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
7028 /* If the class is empty, we aren't actually loading anything. */
7029 r = build_constructor (TREE_TYPE (t), NULL);
7030 TREE_CONSTANT (r) = true;
7032 else if (ctx->strict)
7033 r = decl_really_constant_value (t, /*unshare_p=*/false);
7034 else
7035 r = decl_constant_value (t, /*unshare_p=*/false);
7036 if (TREE_CODE (r) == TARGET_EXPR
7037 && TREE_CODE (TARGET_EXPR_INITIAL (r)) == CONSTRUCTOR)
7038 r = TARGET_EXPR_INITIAL (r);
7039 if (DECL_P (r))
7041 if (!ctx->quiet)
7042 non_const_var_error (loc, r, /*fundef_p*/false);
7043 *non_constant_p = true;
7045 break;
7047 case DEBUG_BEGIN_STMT:
7048 /* ??? It might be nice to retain this information somehow, so
7049 as to be able to step into a constexpr function call. */
7050 /* Fall through. */
7052 case FUNCTION_DECL:
7053 case TEMPLATE_DECL:
7054 case LABEL_DECL:
7055 case LABEL_EXPR:
7056 case CASE_LABEL_EXPR:
7057 case PREDICT_EXPR:
7058 return t;
7060 case PARM_DECL:
7061 if (lval && !TYPE_REF_P (TREE_TYPE (t)))
7062 /* glvalue use. */;
7063 else if (tree v = ctx->global->get_value (r))
7064 r = v;
7065 else if (lval)
7066 /* Defer in case this is only used for its type. */;
7067 else if (COMPLETE_TYPE_P (TREE_TYPE (t))
7068 && is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
7070 /* If the class is empty, we aren't actually loading anything. */
7071 r = build_constructor (TREE_TYPE (t), NULL);
7072 TREE_CONSTANT (r) = true;
7074 else
7076 if (!ctx->quiet)
7077 error ("%qE is not a constant expression", t);
7078 *non_constant_p = true;
7080 break;
7082 case CALL_EXPR:
7083 case AGGR_INIT_EXPR:
7084 r = cxx_eval_call_expression (ctx, t, lval,
7085 non_constant_p, overflow_p);
7086 break;
7088 case DECL_EXPR:
7090 r = DECL_EXPR_DECL (t);
7091 if (TREE_CODE (r) == USING_DECL)
7093 r = void_node;
7094 break;
7097 if (VAR_P (r)
7098 && (TREE_STATIC (r)
7099 || (CP_DECL_THREAD_LOCAL_P (r) && !DECL_REALLY_EXTERN (r)))
7100 /* Allow __FUNCTION__ etc. */
7101 && !DECL_ARTIFICIAL (r))
7103 if (!ctx->quiet)
7105 if (CP_DECL_THREAD_LOCAL_P (r))
7106 error_at (loc, "control passes through definition of %qD "
7107 "with thread storage duration", r);
7108 else
7109 error_at (loc, "control passes through definition of %qD "
7110 "with static storage duration", r);
7112 *non_constant_p = true;
7113 break;
7116 if (AGGREGATE_TYPE_P (TREE_TYPE (r))
7117 || VECTOR_TYPE_P (TREE_TYPE (r)))
7119 new_ctx = *ctx;
7120 new_ctx.object = r;
7121 new_ctx.ctor = build_constructor (TREE_TYPE (r), NULL);
7122 CONSTRUCTOR_NO_CLEARING (new_ctx.ctor) = true;
7123 ctx->global->put_value (r, new_ctx.ctor);
7124 ctx = &new_ctx;
7127 if (tree init = DECL_INITIAL (r))
7129 init = cxx_eval_constant_expression (ctx, init, vc_prvalue,
7130 non_constant_p, overflow_p);
7131 /* Don't share a CONSTRUCTOR that might be changed. */
7132 init = unshare_constructor (init);
7133 /* Remember that a constant object's constructor has already
7134 run. */
7135 if (CLASS_TYPE_P (TREE_TYPE (r))
7136 && CP_TYPE_CONST_P (TREE_TYPE (r)))
7137 TREE_READONLY (init) = true;
7138 ctx->global->put_value (r, init);
7140 else if (ctx == &new_ctx)
7141 /* We gave it a CONSTRUCTOR above. */;
7142 else
7143 ctx->global->put_value (r, NULL_TREE);
7145 break;
7147 case TARGET_EXPR:
7149 tree type = TREE_TYPE (t);
7151 if (!literal_type_p (type))
7153 if (!ctx->quiet)
7155 auto_diagnostic_group d;
7156 error ("temporary of non-literal type %qT in a "
7157 "constant expression", type);
7158 explain_non_literal_class (type);
7160 *non_constant_p = true;
7161 break;
7163 gcc_checking_assert (!TARGET_EXPR_DIRECT_INIT_P (t));
7164 /* Avoid evaluating a TARGET_EXPR more than once. */
7165 tree slot = TARGET_EXPR_SLOT (t);
7166 if (tree v = ctx->global->get_value (slot))
7168 if (lval)
7169 return slot;
7170 r = v;
7171 break;
7173 if ((AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type)))
7175 /* We're being expanded without an explicit target, so start
7176 initializing a new object; expansion with an explicit target
7177 strips the TARGET_EXPR before we get here. */
7178 new_ctx = *ctx;
7179 /* Link CTX to NEW_CTX so that lookup_placeholder can resolve
7180 any PLACEHOLDER_EXPR within the initializer that refers to the
7181 former object under construction. */
7182 new_ctx.parent = ctx;
7183 new_ctx.ctor = build_constructor (type, NULL);
7184 CONSTRUCTOR_NO_CLEARING (new_ctx.ctor) = true;
7185 new_ctx.object = slot;
7186 ctx->global->put_value (new_ctx.object, new_ctx.ctor);
7187 ctx = &new_ctx;
7189 /* Pass vc_prvalue because this indicates
7190 initialization of a temporary. */
7191 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1), vc_prvalue,
7192 non_constant_p, overflow_p);
7193 if (*non_constant_p)
7194 break;
7195 /* Adjust the type of the result to the type of the temporary. */
7196 r = adjust_temp_type (type, r);
7197 if (TARGET_EXPR_CLEANUP (t) && !CLEANUP_EH_ONLY (t))
7198 ctx->global->cleanups->safe_push (TARGET_EXPR_CLEANUP (t));
7199 r = unshare_constructor (r);
7200 ctx->global->put_value (slot, r);
7201 if (ctx->save_exprs)
7202 ctx->save_exprs->safe_push (slot);
7203 if (lval)
7204 return slot;
7206 break;
7208 case INIT_EXPR:
7209 case MODIFY_EXPR:
7210 gcc_assert (jump_target == NULL || *jump_target == NULL_TREE);
7211 r = cxx_eval_store_expression (ctx, t, lval,
7212 non_constant_p, overflow_p);
7213 break;
7215 case SCOPE_REF:
7216 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
7217 lval,
7218 non_constant_p, overflow_p);
7219 break;
7221 case RETURN_EXPR:
7222 if (TREE_OPERAND (t, 0) != NULL_TREE)
7223 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
7224 lval,
7225 non_constant_p, overflow_p);
7226 /* FALLTHRU */
7227 case BREAK_STMT:
7228 case CONTINUE_STMT:
7229 if (jump_target)
7230 *jump_target = t;
7231 else
7233 /* Can happen with ({ return true; }) && false; passed to
7234 maybe_constant_value. There is nothing to jump over in this
7235 case, and the bug will be diagnosed later. */
7236 gcc_assert (ctx->quiet);
7237 *non_constant_p = true;
7239 break;
7241 case SAVE_EXPR:
7242 /* Avoid evaluating a SAVE_EXPR more than once. */
7243 if (tree v = ctx->global->get_value (t))
7244 r = v;
7245 else
7247 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), vc_prvalue,
7248 non_constant_p, overflow_p);
7249 if (*non_constant_p)
7250 break;
7251 ctx->global->put_value (t, r);
7252 if (ctx->save_exprs)
7253 ctx->save_exprs->safe_push (t);
7255 break;
7257 case TRY_CATCH_EXPR:
7258 if (TREE_OPERAND (t, 0) == NULL_TREE)
7260 r = void_node;
7261 break;
7263 /* FALLTHRU */
7264 case NON_LVALUE_EXPR:
7265 case TRY_BLOCK:
7266 case MUST_NOT_THROW_EXPR:
7267 case EXPR_STMT:
7268 case EH_SPEC_BLOCK:
7269 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
7270 lval,
7271 non_constant_p, overflow_p,
7272 jump_target);
7273 break;
7275 case CLEANUP_POINT_EXPR:
7277 auto_vec<tree, 2> cleanups;
7278 vec<tree> *prev_cleanups = ctx->global->cleanups;
7279 ctx->global->cleanups = &cleanups;
7280 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
7281 lval,
7282 non_constant_p, overflow_p,
7283 jump_target);
7284 ctx->global->cleanups = prev_cleanups;
7285 unsigned int i;
7286 tree cleanup;
7287 /* Evaluate the cleanups. */
7288 FOR_EACH_VEC_ELT_REVERSE (cleanups, i, cleanup)
7289 cxx_eval_constant_expression (ctx, cleanup, vc_discard,
7290 non_constant_p, overflow_p);
7292 break;
7294 case TRY_FINALLY_EXPR:
7295 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
7296 non_constant_p, overflow_p,
7297 jump_target);
7298 if (!*non_constant_p)
7299 /* Also evaluate the cleanup. */
7300 cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1), vc_discard,
7301 non_constant_p, overflow_p);
7302 break;
7304 case CLEANUP_STMT:
7305 r = cxx_eval_constant_expression (ctx, CLEANUP_BODY (t), lval,
7306 non_constant_p, overflow_p,
7307 jump_target);
7308 if (!CLEANUP_EH_ONLY (t) && !*non_constant_p)
7310 iloc_sentinel ils (loc);
7311 /* Also evaluate the cleanup. */
7312 cxx_eval_constant_expression (ctx, CLEANUP_EXPR (t), vc_discard,
7313 non_constant_p, overflow_p);
7315 break;
7317 /* These differ from cxx_eval_unary_expression in that this doesn't
7318 check for a constant operand or result; an address can be
7319 constant without its operand being, and vice versa. */
7320 case MEM_REF:
7321 case INDIRECT_REF:
7322 r = cxx_eval_indirect_ref (ctx, t, lval,
7323 non_constant_p, overflow_p);
7324 break;
7326 case ADDR_EXPR:
7328 tree oldop = TREE_OPERAND (t, 0);
7329 tree op = cxx_eval_constant_expression (ctx, oldop, vc_glvalue,
7330 non_constant_p, overflow_p);
7331 /* Don't VERIFY_CONSTANT here. */
7332 if (*non_constant_p)
7333 return t;
7334 gcc_checking_assert (TREE_CODE (op) != CONSTRUCTOR);
7335 /* This function does more aggressive folding than fold itself. */
7336 r = build_fold_addr_expr_with_type (op, TREE_TYPE (t));
7337 if (TREE_CODE (r) == ADDR_EXPR && TREE_OPERAND (r, 0) == oldop)
7339 ggc_free (r);
7340 return t;
7342 break;
7345 case REALPART_EXPR:
7346 case IMAGPART_EXPR:
7347 if (lval)
7349 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
7350 non_constant_p, overflow_p);
7351 if (r == error_mark_node)
7353 else if (r == TREE_OPERAND (t, 0) || lval == vc_discard)
7354 r = t;
7355 else
7356 r = fold_build1 (TREE_CODE (t), TREE_TYPE (t), r);
7357 break;
7359 /* FALLTHRU */
7360 case CONJ_EXPR:
7361 case FIX_TRUNC_EXPR:
7362 case FLOAT_EXPR:
7363 case NEGATE_EXPR:
7364 case ABS_EXPR:
7365 case ABSU_EXPR:
7366 case BIT_NOT_EXPR:
7367 case TRUTH_NOT_EXPR:
7368 case FIXED_CONVERT_EXPR:
7369 r = cxx_eval_unary_expression (ctx, t, lval,
7370 non_constant_p, overflow_p);
7371 break;
7373 case SIZEOF_EXPR:
7374 r = fold_sizeof_expr (t);
7375 /* In a template, fold_sizeof_expr may merely create a new SIZEOF_EXPR,
7376 which could lead to an infinite recursion. */
7377 if (TREE_CODE (r) != SIZEOF_EXPR)
7378 r = cxx_eval_constant_expression (ctx, r, lval,
7379 non_constant_p, overflow_p,
7380 jump_target);
7381 else
7383 *non_constant_p = true;
7384 gcc_assert (ctx->quiet);
7387 break;
7389 case COMPOUND_EXPR:
7391 /* check_return_expr sometimes wraps a TARGET_EXPR in a
7392 COMPOUND_EXPR; don't get confused. Also handle EMPTY_CLASS_EXPR
7393 introduced by build_call_a. */
7394 tree op0 = TREE_OPERAND (t, 0);
7395 tree op1 = TREE_OPERAND (t, 1);
7396 STRIP_NOPS (op1);
7397 if ((TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
7398 || TREE_CODE (op1) == EMPTY_CLASS_EXPR)
7399 r = cxx_eval_constant_expression (ctx, op0,
7400 lval, non_constant_p, overflow_p,
7401 jump_target);
7402 else
7404 /* Check that the LHS is constant and then discard it. */
7405 cxx_eval_constant_expression (ctx, op0, vc_discard,
7406 non_constant_p, overflow_p,
7407 jump_target);
7408 if (*non_constant_p)
7409 return t;
7410 op1 = TREE_OPERAND (t, 1);
7411 r = cxx_eval_constant_expression (ctx, op1,
7412 lval, non_constant_p, overflow_p,
7413 jump_target);
7416 break;
7418 case POINTER_PLUS_EXPR:
7419 case POINTER_DIFF_EXPR:
7420 case PLUS_EXPR:
7421 case MINUS_EXPR:
7422 case MULT_EXPR:
7423 case TRUNC_DIV_EXPR:
7424 case CEIL_DIV_EXPR:
7425 case FLOOR_DIV_EXPR:
7426 case ROUND_DIV_EXPR:
7427 case TRUNC_MOD_EXPR:
7428 case CEIL_MOD_EXPR:
7429 case ROUND_MOD_EXPR:
7430 case RDIV_EXPR:
7431 case EXACT_DIV_EXPR:
7432 case MIN_EXPR:
7433 case MAX_EXPR:
7434 case LSHIFT_EXPR:
7435 case RSHIFT_EXPR:
7436 case LROTATE_EXPR:
7437 case RROTATE_EXPR:
7438 case BIT_IOR_EXPR:
7439 case BIT_XOR_EXPR:
7440 case BIT_AND_EXPR:
7441 case TRUTH_XOR_EXPR:
7442 case LT_EXPR:
7443 case LE_EXPR:
7444 case GT_EXPR:
7445 case GE_EXPR:
7446 case EQ_EXPR:
7447 case NE_EXPR:
7448 case SPACESHIP_EXPR:
7449 case UNORDERED_EXPR:
7450 case ORDERED_EXPR:
7451 case UNLT_EXPR:
7452 case UNLE_EXPR:
7453 case UNGT_EXPR:
7454 case UNGE_EXPR:
7455 case UNEQ_EXPR:
7456 case LTGT_EXPR:
7457 case RANGE_EXPR:
7458 case COMPLEX_EXPR:
7459 r = cxx_eval_binary_expression (ctx, t, lval,
7460 non_constant_p, overflow_p);
7461 break;
7463 /* fold can introduce non-IF versions of these; still treat them as
7464 short-circuiting. */
7465 case TRUTH_AND_EXPR:
7466 case TRUTH_ANDIF_EXPR:
7467 r = cxx_eval_logical_expression (ctx, t, boolean_false_node,
7468 boolean_true_node,
7469 non_constant_p, overflow_p);
7470 break;
7472 case TRUTH_OR_EXPR:
7473 case TRUTH_ORIF_EXPR:
7474 r = cxx_eval_logical_expression (ctx, t, boolean_true_node,
7475 boolean_false_node,
7476 non_constant_p, overflow_p);
7477 break;
7479 case ARRAY_REF:
7480 r = cxx_eval_array_reference (ctx, t, lval,
7481 non_constant_p, overflow_p);
7482 break;
7484 case COMPONENT_REF:
7485 if (is_overloaded_fn (t))
7487 /* We can only get here in checking mode via
7488 build_non_dependent_expr, because any expression that
7489 calls or takes the address of the function will have
7490 pulled a FUNCTION_DECL out of the COMPONENT_REF. */
7491 gcc_checking_assert (ctx->quiet || errorcount);
7492 *non_constant_p = true;
7493 return t;
7495 r = cxx_eval_component_reference (ctx, t, lval,
7496 non_constant_p, overflow_p);
7497 break;
7499 case BIT_FIELD_REF:
7500 r = cxx_eval_bit_field_ref (ctx, t, lval,
7501 non_constant_p, overflow_p);
7502 break;
7504 case COND_EXPR:
7505 case IF_STMT:
7506 if (jump_target && *jump_target)
7508 tree orig_jump = *jump_target;
7509 tree arg = ((TREE_CODE (t) != IF_STMT || TREE_OPERAND (t, 1))
7510 ? TREE_OPERAND (t, 1) : void_node);
7511 /* When jumping to a label, the label might be either in the
7512 then or else blocks, so process then block first in skipping
7513 mode first, and if we are still in the skipping mode at its end,
7514 process the else block too. */
7515 r = cxx_eval_constant_expression (ctx, arg, lval, non_constant_p,
7516 overflow_p, jump_target);
7517 /* It's possible that we found the label in the then block. But
7518 it could have been followed by another jumping statement, e.g.
7519 say we're looking for case 1:
7520 if (cond)
7522 // skipped statements
7523 case 1:; // clears up *jump_target
7524 return 1; // and sets it to a RETURN_EXPR
7526 else { ... }
7527 in which case we need not go looking to the else block.
7528 (goto is not allowed in a constexpr function.) */
7529 if (*jump_target == orig_jump)
7531 arg = ((TREE_CODE (t) != IF_STMT || TREE_OPERAND (t, 2))
7532 ? TREE_OPERAND (t, 2) : void_node);
7533 r = cxx_eval_constant_expression (ctx, arg, lval, non_constant_p,
7534 overflow_p, jump_target);
7536 break;
7538 r = cxx_eval_conditional_expression (ctx, t, lval,
7539 non_constant_p, overflow_p,
7540 jump_target);
7541 break;
7542 case VEC_COND_EXPR:
7543 r = cxx_eval_vector_conditional_expression (ctx, t, non_constant_p,
7544 overflow_p);
7545 break;
7547 case CONSTRUCTOR:
7548 if (TREE_CONSTANT (t) && reduced_constant_expression_p (t))
7550 /* Don't re-process a constant CONSTRUCTOR. */
7551 verify_constructor_flags (t);
7552 if (TREE_CONSTANT (t))
7553 return t;
7555 r = cxx_eval_bare_aggregate (ctx, t, lval,
7556 non_constant_p, overflow_p);
7557 break;
7559 case VEC_INIT_EXPR:
7560 /* We can get this in a defaulted constructor for a class with a
7561 non-static data member of array type. Either the initializer will
7562 be NULL, meaning default-initialization, or it will be an lvalue
7563 or xvalue of the same type, meaning direct-initialization from the
7564 corresponding member. */
7565 r = cxx_eval_vec_init (ctx, t, lval,
7566 non_constant_p, overflow_p);
7567 break;
7569 case VEC_PERM_EXPR:
7570 r = cxx_eval_trinary_expression (ctx, t, lval,
7571 non_constant_p, overflow_p);
7572 break;
7574 case PAREN_EXPR:
7575 gcc_assert (!REF_PARENTHESIZED_P (t));
7576 /* A PAREN_EXPR resulting from __builtin_assoc_barrier has no effect in
7577 constant expressions since it's unaffected by -fassociative-math. */
7578 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
7579 non_constant_p, overflow_p);
7580 break;
7582 case NOP_EXPR:
7583 if (REINTERPRET_CAST_P (t))
7585 if (!ctx->quiet)
7586 error_at (loc,
7587 "%<reinterpret_cast%> is not a constant expression");
7588 *non_constant_p = true;
7589 return t;
7591 /* FALLTHROUGH. */
7592 case CONVERT_EXPR:
7593 case VIEW_CONVERT_EXPR:
7594 case UNARY_PLUS_EXPR:
7596 tree oldop = TREE_OPERAND (t, 0);
7598 tree op = cxx_eval_constant_expression (ctx, oldop,
7599 lval,
7600 non_constant_p, overflow_p);
7601 if (*non_constant_p)
7602 return t;
7603 tree type = TREE_TYPE (t);
7605 if (VOID_TYPE_P (type))
7606 return void_node;
7608 if (TREE_CODE (t) == CONVERT_EXPR
7609 && ARITHMETIC_TYPE_P (type)
7610 && INDIRECT_TYPE_P (TREE_TYPE (op))
7611 && ctx->manifestly_const_eval)
7613 if (!ctx->quiet)
7614 error_at (loc,
7615 "conversion from pointer type %qT to arithmetic type "
7616 "%qT in a constant expression", TREE_TYPE (op), type);
7617 *non_constant_p = true;
7618 return t;
7621 /* [expr.const]: a conversion from type cv void* to a pointer-to-object
7622 type cannot be part of a core constant expression as a resolution to
7623 DR 1312. */
7624 if (TYPE_PTROB_P (type)
7625 && TYPE_PTR_P (TREE_TYPE (op))
7626 && VOID_TYPE_P (TREE_TYPE (TREE_TYPE (op)))
7627 /* Inside a call to std::construct_at or to
7628 std::allocator<T>::{,de}allocate, we permit casting from void*
7629 because that is compiler-generated code. */
7630 && !is_std_construct_at (ctx->call)
7631 && !is_std_allocator_allocate (ctx->call))
7633 /* Likewise, don't error when casting from void* when OP is
7634 &heap uninit and similar. */
7635 tree sop = tree_strip_nop_conversions (op);
7636 if (TREE_CODE (sop) == ADDR_EXPR
7637 && VAR_P (TREE_OPERAND (sop, 0))
7638 && DECL_ARTIFICIAL (TREE_OPERAND (sop, 0)))
7639 /* OK */;
7640 else
7642 if (!ctx->quiet)
7643 error_at (loc, "cast from %qT is not allowed",
7644 TREE_TYPE (op));
7645 *non_constant_p = true;
7646 return t;
7650 if (TREE_CODE (op) == PTRMEM_CST && !TYPE_PTRMEM_P (type))
7651 op = cplus_expand_constant (op);
7653 if (TREE_CODE (op) == PTRMEM_CST && tcode == NOP_EXPR)
7655 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (op))
7656 && !can_convert_qual (type, op))
7657 op = cplus_expand_constant (op);
7658 return cp_fold_convert (type, op);
7661 if (INDIRECT_TYPE_P (type) && TREE_CODE (op) == INTEGER_CST)
7663 if (integer_zerop (op))
7665 if (TYPE_REF_P (type))
7667 if (!ctx->quiet)
7668 error_at (loc, "dereferencing a null pointer");
7669 *non_constant_p = true;
7670 return t;
7673 else
7675 /* This detects for example:
7676 reinterpret_cast<void*>(sizeof 0)
7678 if (!ctx->quiet)
7679 error_at (loc, "%<reinterpret_cast<%T>(%E)%> is not "
7680 "a constant expression",
7681 type, op);
7682 *non_constant_p = true;
7683 return t;
7687 if (INDIRECT_TYPE_P (type)
7688 && TREE_CODE (op) == NOP_EXPR
7689 && TREE_TYPE (op) == ptr_type_node
7690 && TREE_CODE (TREE_OPERAND (op, 0)) == ADDR_EXPR
7691 && VAR_P (TREE_OPERAND (TREE_OPERAND (op, 0), 0))
7692 && (DECL_NAME (TREE_OPERAND (TREE_OPERAND (op, 0),
7693 0)) == heap_uninit_identifier
7694 || DECL_NAME (TREE_OPERAND (TREE_OPERAND (op, 0),
7695 0)) == heap_vec_uninit_identifier))
7697 tree var = TREE_OPERAND (TREE_OPERAND (op, 0), 0);
7698 tree var_size = TYPE_SIZE_UNIT (TREE_TYPE (var));
7699 tree elt_type = TREE_TYPE (type);
7700 tree cookie_size = NULL_TREE;
7701 tree arg_size = NULL_TREE;
7702 if (TREE_CODE (elt_type) == RECORD_TYPE
7703 && TYPE_NAME (elt_type) == heap_identifier)
7705 tree fld1 = TYPE_FIELDS (elt_type);
7706 tree fld2 = DECL_CHAIN (fld1);
7707 elt_type = TREE_TYPE (TREE_TYPE (fld2));
7708 cookie_size = TYPE_SIZE_UNIT (TREE_TYPE (fld1));
7710 DECL_NAME (var)
7711 = (DECL_NAME (var) == heap_uninit_identifier
7712 ? heap_identifier : heap_vec_identifier);
7713 /* For zero sized elt_type, try to recover how many outer_nelts
7714 it should have. */
7715 if ((cookie_size ? tree_int_cst_equal (var_size, cookie_size)
7716 : integer_zerop (var_size))
7717 && !int_size_in_bytes (elt_type)
7718 && TREE_CODE (oldop) == CALL_EXPR
7719 && call_expr_nargs (oldop) >= 1)
7720 if (tree fun = get_function_named_in_call (oldop))
7721 if (cxx_replaceable_global_alloc_fn (fun)
7722 && IDENTIFIER_NEW_OP_P (DECL_NAME (fun)))
7723 arg_size = CALL_EXPR_ARG (oldop, 0);
7724 TREE_TYPE (var)
7725 = build_new_constexpr_heap_type (ctx, elt_type, cookie_size,
7726 var_size, arg_size,
7727 non_constant_p, overflow_p);
7728 TREE_TYPE (TREE_OPERAND (op, 0))
7729 = build_pointer_type (TREE_TYPE (var));
7732 if (op == oldop && tcode != UNARY_PLUS_EXPR)
7733 /* We didn't fold at the top so we could check for ptr-int
7734 conversion. */
7735 return fold (t);
7737 tree sop;
7739 /* Handle an array's bounds having been deduced after we built
7740 the wrapping expression. */
7741 if (same_type_ignoring_tlq_and_bounds_p (type, TREE_TYPE (op)))
7742 r = op;
7743 else if (sop = tree_strip_nop_conversions (op),
7744 sop != op && (same_type_ignoring_tlq_and_bounds_p
7745 (type, TREE_TYPE (sop))))
7746 r = sop;
7747 else if (tcode == UNARY_PLUS_EXPR)
7748 r = fold_convert (TREE_TYPE (t), op);
7749 else
7750 r = fold_build1 (tcode, type, op);
7752 /* Conversion of an out-of-range value has implementation-defined
7753 behavior; the language considers it different from arithmetic
7754 overflow, which is undefined. */
7755 if (TREE_OVERFLOW_P (r) && !TREE_OVERFLOW_P (op))
7756 TREE_OVERFLOW (r) = false;
7758 break;
7760 case EXCESS_PRECISION_EXPR:
7762 tree oldop = TREE_OPERAND (t, 0);
7764 tree op = cxx_eval_constant_expression (ctx, oldop,
7765 lval,
7766 non_constant_p, overflow_p);
7767 if (*non_constant_p)
7768 return t;
7769 r = fold_convert (TREE_TYPE (t), op);
7770 break;
7773 case EMPTY_CLASS_EXPR:
7774 /* Handle EMPTY_CLASS_EXPR produced by build_call_a by lowering
7775 it to an appropriate CONSTRUCTOR. */
7776 return build_constructor (TREE_TYPE (t), NULL);
7778 case STATEMENT_LIST:
7779 new_ctx = *ctx;
7780 new_ctx.ctor = new_ctx.object = NULL_TREE;
7781 return cxx_eval_statement_list (&new_ctx, t,
7782 non_constant_p, overflow_p, jump_target);
7784 case BIND_EXPR:
7785 return cxx_eval_constant_expression (ctx, BIND_EXPR_BODY (t),
7786 lval,
7787 non_constant_p, overflow_p,
7788 jump_target);
7790 case PREINCREMENT_EXPR:
7791 case POSTINCREMENT_EXPR:
7792 case PREDECREMENT_EXPR:
7793 case POSTDECREMENT_EXPR:
7794 return cxx_eval_increment_expression (ctx, t,
7795 lval, non_constant_p, overflow_p);
7797 case LAMBDA_EXPR:
7798 case NEW_EXPR:
7799 case VEC_NEW_EXPR:
7800 case DELETE_EXPR:
7801 case VEC_DELETE_EXPR:
7802 case THROW_EXPR:
7803 case MODOP_EXPR:
7804 /* GCC internal stuff. */
7805 case VA_ARG_EXPR:
7806 case NON_DEPENDENT_EXPR:
7807 case BASELINK:
7808 case OFFSET_REF:
7809 if (!ctx->quiet)
7810 error_at (loc, "expression %qE is not a constant expression", t);
7811 *non_constant_p = true;
7812 break;
7814 case OBJ_TYPE_REF:
7815 /* Virtual function lookup. We don't need to do anything fancy. */
7816 return cxx_eval_constant_expression (ctx, OBJ_TYPE_REF_EXPR (t),
7817 lval, non_constant_p, overflow_p);
7819 case PLACEHOLDER_EXPR:
7820 /* Use of the value or address of the current object. */
7821 if (tree ctor = lookup_placeholder (ctx, lval, TREE_TYPE (t)))
7823 if (TREE_CODE (ctor) == CONSTRUCTOR)
7824 return ctor;
7825 else
7826 return cxx_eval_constant_expression (ctx, ctor, lval,
7827 non_constant_p, overflow_p);
7829 /* A placeholder without a referent. We can get here when
7830 checking whether NSDMIs are noexcept, or in massage_init_elt;
7831 just say it's non-constant for now. */
7832 gcc_assert (ctx->quiet);
7833 *non_constant_p = true;
7834 break;
7836 case EXIT_EXPR:
7838 tree cond = TREE_OPERAND (t, 0);
7839 cond = cxx_eval_constant_expression (ctx, cond, vc_prvalue,
7840 non_constant_p, overflow_p);
7841 VERIFY_CONSTANT (cond);
7842 if (integer_nonzerop (cond))
7843 *jump_target = t;
7845 break;
7847 case GOTO_EXPR:
7848 if (breaks (&TREE_OPERAND (t, 0))
7849 || continues (&TREE_OPERAND (t, 0)))
7850 *jump_target = TREE_OPERAND (t, 0);
7851 else
7853 gcc_assert (cxx_dialect >= cxx23);
7854 if (!ctx->quiet)
7855 error_at (loc, "%<goto%> is not a constant expression");
7856 *non_constant_p = true;
7858 break;
7860 case LOOP_EXPR:
7861 case DO_STMT:
7862 case WHILE_STMT:
7863 case FOR_STMT:
7864 cxx_eval_loop_expr (ctx, t,
7865 non_constant_p, overflow_p, jump_target);
7866 break;
7868 case SWITCH_EXPR:
7869 case SWITCH_STMT:
7870 cxx_eval_switch_expr (ctx, t,
7871 non_constant_p, overflow_p, jump_target);
7872 break;
7874 case REQUIRES_EXPR:
7875 /* It's possible to get a requires-expression in a constant
7876 expression. For example:
7878 template<typename T> concept bool C() {
7879 return requires (T t) { t; };
7882 template<typename T> requires !C<T>() void f(T);
7884 Normalization leaves f with the associated constraint
7885 '!requires (T t) { ... }' which is not transformed into
7886 a constraint. */
7887 if (!processing_template_decl)
7888 return evaluate_requires_expr (t);
7889 else
7890 *non_constant_p = true;
7891 return t;
7893 case ANNOTATE_EXPR:
7894 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
7895 lval,
7896 non_constant_p, overflow_p,
7897 jump_target);
7898 break;
7900 case USING_STMT:
7901 r = void_node;
7902 break;
7904 case TEMPLATE_ID_EXPR:
7906 /* We can evaluate template-id that refers to a concept only if
7907 the template arguments are non-dependent. */
7908 tree id = unpack_concept_check (t);
7909 tree tmpl = TREE_OPERAND (id, 0);
7910 if (!concept_definition_p (tmpl))
7911 internal_error ("unexpected template-id %qE", t);
7913 if (function_concept_p (tmpl))
7915 if (!ctx->quiet)
7916 error_at (cp_expr_loc_or_input_loc (t),
7917 "function concept must be called");
7918 r = error_mark_node;
7919 break;
7922 if (!value_dependent_expression_p (t)
7923 && !uid_sensitive_constexpr_evaluation_p ())
7924 r = evaluate_concept_check (t);
7925 else
7926 *non_constant_p = true;
7928 break;
7931 case ASM_EXPR:
7932 if (!ctx->quiet)
7933 inline_asm_in_constexpr_error (loc, /*constexpr_fundef_p*/false);
7934 *non_constant_p = true;
7935 return t;
7937 case BIT_CAST_EXPR:
7938 if (lval)
7940 if (!ctx->quiet)
7941 error_at (EXPR_LOCATION (t),
7942 "address of a call to %qs is not a constant expression",
7943 "__builtin_bit_cast");
7944 *non_constant_p = true;
7945 return t;
7947 r = cxx_eval_bit_cast (ctx, t, non_constant_p, overflow_p);
7948 break;
7950 default:
7951 if (STATEMENT_CODE_P (TREE_CODE (t)))
7953 /* This function doesn't know how to deal with pre-genericize
7954 statements; this can only happen with statement-expressions,
7955 so for now just fail. */
7956 if (!ctx->quiet)
7957 error_at (EXPR_LOCATION (t),
7958 "statement is not a constant expression");
7960 else
7961 internal_error ("unexpected expression %qE of kind %s", t,
7962 get_tree_code_name (TREE_CODE (t)));
7963 *non_constant_p = true;
7964 break;
7967 if (r == error_mark_node)
7968 *non_constant_p = true;
7970 if (*non_constant_p)
7971 return t;
7972 else
7973 return r;
7976 /* P0859: A function is needed for constant evaluation if it is a constexpr
7977 function that is named by an expression ([basic.def.odr]) that is
7978 potentially constant evaluated.
7980 So we need to instantiate any constexpr functions mentioned by the
7981 expression even if the definition isn't needed for evaluating the
7982 expression. */
7984 static tree
7985 instantiate_cx_fn_r (tree *tp, int *walk_subtrees, void */*data*/)
7987 if (TREE_CODE (*tp) == FUNCTION_DECL
7988 && DECL_DECLARED_CONSTEXPR_P (*tp)
7989 && !DECL_INITIAL (*tp)
7990 && !trivial_fn_p (*tp)
7991 && DECL_TEMPLOID_INSTANTIATION (*tp)
7992 && !uid_sensitive_constexpr_evaluation_p ())
7994 ++function_depth;
7995 instantiate_decl (*tp, /*defer_ok*/false, /*expl_inst*/false);
7996 --function_depth;
7998 else if (TREE_CODE (*tp) == CALL_EXPR
7999 || TREE_CODE (*tp) == AGGR_INIT_EXPR)
8001 if (EXPR_HAS_LOCATION (*tp))
8002 input_location = EXPR_LOCATION (*tp);
8005 if (!EXPR_P (*tp))
8006 *walk_subtrees = 0;
8008 return NULL_TREE;
8011 static void
8012 instantiate_constexpr_fns (tree t)
8014 location_t loc = input_location;
8015 cp_walk_tree_without_duplicates (&t, instantiate_cx_fn_r, NULL);
8016 input_location = loc;
8019 /* Look for heap variables in the expression *TP. */
8021 static tree
8022 find_heap_var_refs (tree *tp, int *walk_subtrees, void */*data*/)
8024 if (VAR_P (*tp)
8025 && (DECL_NAME (*tp) == heap_uninit_identifier
8026 || DECL_NAME (*tp) == heap_identifier
8027 || DECL_NAME (*tp) == heap_vec_uninit_identifier
8028 || DECL_NAME (*tp) == heap_vec_identifier
8029 || DECL_NAME (*tp) == heap_deleted_identifier))
8030 return *tp;
8032 if (TYPE_P (*tp))
8033 *walk_subtrees = 0;
8034 return NULL_TREE;
8037 /* Find immediate function decls in *TP if any. */
8039 static tree
8040 find_immediate_fndecl (tree *tp, int */*walk_subtrees*/, void */*data*/)
8042 if (TREE_CODE (*tp) == FUNCTION_DECL && DECL_IMMEDIATE_FUNCTION_P (*tp))
8043 return *tp;
8044 if (TREE_CODE (*tp) == PTRMEM_CST
8045 && TREE_CODE (PTRMEM_CST_MEMBER (*tp)) == FUNCTION_DECL
8046 && DECL_IMMEDIATE_FUNCTION_P (PTRMEM_CST_MEMBER (*tp)))
8047 return PTRMEM_CST_MEMBER (*tp);
8048 return NULL_TREE;
8051 /* T has TREE_CONSTANT set but has been deemed not a valid C++ constant
8052 expression. Return a version of T that has TREE_CONSTANT cleared. */
8054 static tree
8055 mark_non_constant (tree t)
8057 gcc_checking_assert (TREE_CONSTANT (t));
8059 /* This isn't actually constant, so unset TREE_CONSTANT.
8060 Don't clear TREE_CONSTANT on ADDR_EXPR, as the middle-end requires
8061 it to be set if it is invariant address, even when it is not
8062 a valid C++ constant expression. Wrap it with a NOP_EXPR
8063 instead. */
8064 if (EXPR_P (t) && TREE_CODE (t) != ADDR_EXPR)
8065 t = copy_node (t);
8066 else if (TREE_CODE (t) == CONSTRUCTOR)
8067 t = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (t), t);
8068 else
8069 t = build_nop (TREE_TYPE (t), t);
8070 TREE_CONSTANT (t) = false;
8071 return t;
8074 /* ALLOW_NON_CONSTANT is false if T is required to be a constant expression.
8075 STRICT has the same sense as for constant_value_1: true if we only allow
8076 conforming C++ constant expressions, or false if we want a constant value
8077 even if it doesn't conform.
8078 MANIFESTLY_CONST_EVAL is true if T is manifestly const-evaluated as
8079 per P0595 even when ALLOW_NON_CONSTANT is true.
8080 CONSTEXPR_DTOR is true when evaluating the dtor of a constexpr variable.
8081 OBJECT must be non-NULL in that case. */
8083 static tree
8084 cxx_eval_outermost_constant_expr (tree t, bool allow_non_constant,
8085 bool strict = true,
8086 bool manifestly_const_eval = false,
8087 bool constexpr_dtor = false,
8088 tree object = NULL_TREE)
8090 auto_timevar time (TV_CONSTEXPR);
8092 bool non_constant_p = false;
8093 bool overflow_p = false;
8095 if (BRACE_ENCLOSED_INITIALIZER_P (t))
8097 gcc_checking_assert (allow_non_constant);
8098 return t;
8101 constexpr_global_ctx global_ctx;
8102 constexpr_ctx ctx = { &global_ctx, NULL, NULL, NULL, NULL, NULL, NULL,
8103 allow_non_constant, strict,
8104 manifestly_const_eval || !allow_non_constant };
8106 /* Turn off -frounding-math for manifestly constant evaluation. */
8107 warning_sentinel rm (flag_rounding_math, ctx.manifestly_const_eval);
8108 tree type = initialized_type (t);
8109 tree r = t;
8110 bool is_consteval = false;
8111 if (VOID_TYPE_P (type))
8113 if (constexpr_dtor)
8114 /* Used for destructors of array elements. */
8115 type = TREE_TYPE (object);
8116 else
8118 if (cxx_dialect < cxx20)
8119 return t;
8120 if (TREE_CODE (t) != CALL_EXPR && TREE_CODE (t) != AGGR_INIT_EXPR)
8121 return t;
8122 /* Calls to immediate functions returning void need to be
8123 evaluated. */
8124 tree fndecl = cp_get_callee_fndecl_nofold (t);
8125 if (fndecl == NULL_TREE || !DECL_IMMEDIATE_FUNCTION_P (fndecl))
8126 return t;
8127 else
8128 is_consteval = true;
8131 else if (cxx_dialect >= cxx20
8132 && (TREE_CODE (t) == CALL_EXPR
8133 || TREE_CODE (t) == AGGR_INIT_EXPR
8134 || TREE_CODE (t) == TARGET_EXPR))
8136 /* For non-concept checks, determine if it is consteval. */
8137 if (!concept_check_p (t))
8139 tree x = t;
8140 if (TREE_CODE (x) == TARGET_EXPR)
8141 x = TARGET_EXPR_INITIAL (x);
8142 tree fndecl = cp_get_callee_fndecl_nofold (x);
8143 if (fndecl && DECL_IMMEDIATE_FUNCTION_P (fndecl))
8144 is_consteval = true;
8147 if (AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type))
8149 /* In C++14 an NSDMI can participate in aggregate initialization,
8150 and can refer to the address of the object being initialized, so
8151 we need to pass in the relevant VAR_DECL if we want to do the
8152 evaluation in a single pass. The evaluation will dynamically
8153 update ctx.values for the VAR_DECL. We use the same strategy
8154 for C++11 constexpr constructors that refer to the object being
8155 initialized. */
8156 if (constexpr_dtor)
8158 gcc_assert (object && VAR_P (object));
8159 gcc_assert (DECL_DECLARED_CONSTEXPR_P (object));
8160 gcc_assert (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (object));
8161 if (error_operand_p (DECL_INITIAL (object)))
8162 return t;
8163 ctx.ctor = unshare_expr (DECL_INITIAL (object));
8164 TREE_READONLY (ctx.ctor) = false;
8165 /* Temporarily force decl_really_constant_value to return false
8166 for it, we want to use ctx.ctor for the current value instead. */
8167 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (object) = false;
8169 else
8171 ctx.ctor = build_constructor (type, NULL);
8172 CONSTRUCTOR_NO_CLEARING (ctx.ctor) = true;
8174 if (!object)
8176 if (TREE_CODE (t) == TARGET_EXPR)
8177 object = TARGET_EXPR_SLOT (t);
8178 else if (TREE_CODE (t) == AGGR_INIT_EXPR)
8179 object = AGGR_INIT_EXPR_SLOT (t);
8181 ctx.object = object;
8182 if (object)
8183 gcc_assert (same_type_ignoring_top_level_qualifiers_p
8184 (type, TREE_TYPE (object)));
8185 if (object && DECL_P (object))
8186 global_ctx.put_value (object, ctx.ctor);
8187 if (TREE_CODE (r) == TARGET_EXPR)
8188 /* Avoid creating another CONSTRUCTOR when we expand the
8189 TARGET_EXPR. */
8190 r = TARGET_EXPR_INITIAL (r);
8193 auto_vec<tree, 16> cleanups;
8194 global_ctx.cleanups = &cleanups;
8196 if (manifestly_const_eval)
8197 instantiate_constexpr_fns (r);
8198 r = cxx_eval_constant_expression (&ctx, r, vc_prvalue,
8199 &non_constant_p, &overflow_p);
8201 if (!constexpr_dtor)
8202 verify_constant (r, allow_non_constant, &non_constant_p, &overflow_p);
8203 else
8204 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (object) = true;
8206 unsigned int i;
8207 tree cleanup;
8208 /* Evaluate the cleanups. */
8209 FOR_EACH_VEC_ELT_REVERSE (cleanups, i, cleanup)
8210 cxx_eval_constant_expression (&ctx, cleanup, vc_discard,
8211 &non_constant_p, &overflow_p);
8213 /* Mutable logic is a bit tricky: we want to allow initialization of
8214 constexpr variables with mutable members, but we can't copy those
8215 members to another constexpr variable. */
8216 if (TREE_CODE (r) == CONSTRUCTOR && CONSTRUCTOR_MUTABLE_POISON (r))
8218 if (!allow_non_constant)
8219 error ("%qE is not a constant expression because it refers to "
8220 "mutable subobjects of %qT", t, type);
8221 non_constant_p = true;
8224 if (TREE_CODE (r) == CONSTRUCTOR && CONSTRUCTOR_NO_CLEARING (r))
8226 if (!allow_non_constant)
8227 error ("%qE is not a constant expression because it refers to "
8228 "an incompletely initialized variable", t);
8229 TREE_CONSTANT (r) = false;
8230 non_constant_p = true;
8233 if (!global_ctx.heap_vars.is_empty ())
8235 tree heap_var = cp_walk_tree_without_duplicates (&r, find_heap_var_refs,
8236 NULL);
8237 unsigned int i;
8238 if (heap_var)
8240 if (!allow_non_constant && !non_constant_p)
8241 error_at (DECL_SOURCE_LOCATION (heap_var),
8242 "%qE is not a constant expression because it refers to "
8243 "a result of %<operator new%>", t);
8244 r = t;
8245 non_constant_p = true;
8247 FOR_EACH_VEC_ELT (global_ctx.heap_vars, i, heap_var)
8249 if (DECL_NAME (heap_var) != heap_deleted_identifier)
8251 if (!allow_non_constant && !non_constant_p)
8252 error_at (DECL_SOURCE_LOCATION (heap_var),
8253 "%qE is not a constant expression because allocated "
8254 "storage has not been deallocated", t);
8255 r = t;
8256 non_constant_p = true;
8258 varpool_node::get (heap_var)->remove ();
8262 /* Check that immediate invocation does not return an expression referencing
8263 any immediate function decls. */
8264 if (is_consteval || in_immediate_context ())
8265 if (tree immediate_fndecl
8266 = cp_walk_tree_without_duplicates (&r, find_immediate_fndecl,
8267 NULL))
8269 if (!allow_non_constant && !non_constant_p)
8270 error_at (cp_expr_loc_or_input_loc (t),
8271 "immediate evaluation returns address of immediate "
8272 "function %qD", immediate_fndecl);
8273 r = t;
8274 non_constant_p = true;
8277 if (non_constant_p)
8278 /* If we saw something bad, go back to our argument. The wrapping below is
8279 only for the cases of TREE_CONSTANT argument or overflow. */
8280 r = t;
8282 if (!non_constant_p && overflow_p)
8283 non_constant_p = true;
8285 /* Unshare the result. */
8286 bool should_unshare = true;
8287 if (r == t || (TREE_CODE (t) == TARGET_EXPR
8288 && TARGET_EXPR_INITIAL (t) == r))
8289 should_unshare = false;
8291 if (non_constant_p && !allow_non_constant)
8292 return error_mark_node;
8293 else if (constexpr_dtor)
8294 return r;
8295 else if (non_constant_p && TREE_CONSTANT (r))
8296 r = mark_non_constant (r);
8297 else if (non_constant_p)
8298 return t;
8300 if (should_unshare)
8301 r = unshare_expr (r);
8303 if (TREE_CODE (r) == CONSTRUCTOR && CLASS_TYPE_P (TREE_TYPE (r)))
8305 r = adjust_temp_type (type, r);
8306 if (TREE_CODE (t) == TARGET_EXPR
8307 && TARGET_EXPR_INITIAL (t) == r)
8308 return t;
8309 else if (TREE_CODE (t) == CONSTRUCTOR || TREE_CODE (t) == CALL_EXPR)
8310 /* Don't add a TARGET_EXPR if our argument didn't have one. */;
8311 else if (TREE_CODE (t) == TARGET_EXPR && TARGET_EXPR_CLEANUP (t))
8312 r = get_target_expr (r);
8313 else
8315 r = get_target_expr (r, tf_warning_or_error | tf_no_cleanup);
8316 TREE_CONSTANT (r) = true;
8320 /* Remember the original location if that wouldn't need a wrapper. */
8321 if (location_t loc = EXPR_LOCATION (t))
8322 protected_set_expr_location (r, loc);
8324 return r;
8327 /* If T represents a constant expression returns its reduced value.
8328 Otherwise return error_mark_node. */
8330 tree
8331 cxx_constant_value (tree t, tree decl /* = NULL_TREE */,
8332 tsubst_flags_t complain /* = tf_error */)
8334 bool sfinae = !(complain & tf_error);
8335 tree r = cxx_eval_outermost_constant_expr (t, sfinae, true, true, false, decl);
8336 if (sfinae && !TREE_CONSTANT (r))
8337 r = error_mark_node;
8338 return r;
8341 /* Like cxx_constant_value, but used for evaluation of constexpr destructors
8342 of constexpr variables. The actual initializer of DECL is not modified. */
8344 void
8345 cxx_constant_dtor (tree t, tree decl)
8347 cxx_eval_outermost_constant_expr (t, false, true, true, true, decl);
8350 /* Helper routine for fold_simple function. Either return simplified
8351 expression T, otherwise NULL_TREE.
8352 In contrast to cp_fully_fold, and to maybe_constant_value, we try to fold
8353 even if we are within template-declaration. So be careful on call, as in
8354 such case types can be undefined. */
8356 static tree
8357 fold_simple_1 (tree t)
8359 tree op1;
8360 enum tree_code code = TREE_CODE (t);
8362 switch (code)
8364 case INTEGER_CST:
8365 case REAL_CST:
8366 case VECTOR_CST:
8367 case FIXED_CST:
8368 case COMPLEX_CST:
8369 return t;
8371 case SIZEOF_EXPR:
8372 return fold_sizeof_expr (t);
8374 case ABS_EXPR:
8375 case ABSU_EXPR:
8376 case CONJ_EXPR:
8377 case REALPART_EXPR:
8378 case IMAGPART_EXPR:
8379 case NEGATE_EXPR:
8380 case BIT_NOT_EXPR:
8381 case TRUTH_NOT_EXPR:
8382 case VIEW_CONVERT_EXPR:
8383 CASE_CONVERT:
8384 case FLOAT_EXPR:
8385 case FIX_TRUNC_EXPR:
8386 case FIXED_CONVERT_EXPR:
8387 case ADDR_SPACE_CONVERT_EXPR:
8389 op1 = TREE_OPERAND (t, 0);
8391 t = const_unop (code, TREE_TYPE (t), op1);
8392 if (!t)
8393 return NULL_TREE;
8395 if (CONVERT_EXPR_CODE_P (code)
8396 && TREE_OVERFLOW_P (t) && !TREE_OVERFLOW_P (op1))
8397 TREE_OVERFLOW (t) = false;
8398 return t;
8400 default:
8401 return NULL_TREE;
8405 /* If T is a simple constant expression, returns its simplified value.
8406 Otherwise returns T. In contrast to maybe_constant_value we
8407 simplify only few operations on constant-expressions, and we don't
8408 try to simplify constexpressions. */
8410 tree
8411 fold_simple (tree t)
8413 if (processing_template_decl)
8414 return t;
8416 tree r = fold_simple_1 (t);
8417 if (r)
8418 return r;
8420 return t;
8423 /* If T is a constant expression, returns its reduced value.
8424 Otherwise, if T does not have TREE_CONSTANT set, returns T.
8425 Otherwise, returns a version of T without TREE_CONSTANT.
8426 MANIFESTLY_CONST_EVAL is true if T is manifestly const-evaluated
8427 as per P0595. */
8429 static GTY((deletable)) hash_map<tree, tree> *cv_cache;
8431 tree
8432 maybe_constant_value (tree t, tree decl, bool manifestly_const_eval)
8434 tree r;
8436 if (!is_nondependent_constant_expression (t))
8438 if (TREE_OVERFLOW_P (t)
8439 || (!processing_template_decl && TREE_CONSTANT (t)))
8440 t = mark_non_constant (t);
8441 return t;
8443 else if (CONSTANT_CLASS_P (t))
8444 /* No caching or evaluation needed. */
8445 return t;
8447 if (manifestly_const_eval)
8448 return cxx_eval_outermost_constant_expr (t, true, true, true, false, decl);
8450 if (cv_cache == NULL)
8451 cv_cache = hash_map<tree, tree>::create_ggc (101);
8452 if (tree *cached = cv_cache->get (t))
8454 r = *cached;
8455 if (r != t)
8457 r = break_out_target_exprs (r, /*clear_loc*/true);
8458 protected_set_expr_location (r, EXPR_LOCATION (t));
8460 return r;
8463 /* Don't evaluate an unevaluated operand. */
8464 if (cp_unevaluated_operand)
8465 return t;
8467 uid_sensitive_constexpr_evaluation_checker c;
8468 r = cxx_eval_outermost_constant_expr (t, true, true, false, false, decl);
8469 gcc_checking_assert (r == t
8470 || CONVERT_EXPR_P (t)
8471 || TREE_CODE (t) == VIEW_CONVERT_EXPR
8472 || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
8473 || !cp_tree_equal (r, t));
8474 if (!c.evaluation_restricted_p ())
8475 cv_cache->put (t, r);
8476 return r;
8479 /* Dispose of the whole CV_CACHE. */
8481 static void
8482 clear_cv_cache (void)
8484 if (cv_cache != NULL)
8485 cv_cache->empty ();
8488 /* Dispose of the whole CV_CACHE and FOLD_CACHE. */
8490 void
8491 clear_cv_and_fold_caches ()
8493 clear_cv_cache ();
8494 clear_fold_cache ();
8497 /* Internal function handling expressions in templates for
8498 fold_non_dependent_expr and fold_non_dependent_init.
8500 If we're in a template, but T isn't value dependent, simplify
8501 it. We're supposed to treat:
8503 template <typename T> void f(T[1 + 1]);
8504 template <typename T> void f(T[2]);
8506 as two declarations of the same function, for example. */
8508 static tree
8509 fold_non_dependent_expr_template (tree t, tsubst_flags_t complain,
8510 bool manifestly_const_eval,
8511 tree object)
8513 gcc_assert (processing_template_decl);
8515 if (is_nondependent_constant_expression (t))
8517 processing_template_decl_sentinel s;
8518 t = instantiate_non_dependent_expr_internal (t, complain);
8520 if (type_unknown_p (t) || BRACE_ENCLOSED_INITIALIZER_P (t))
8522 if (TREE_OVERFLOW_P (t))
8524 t = build_nop (TREE_TYPE (t), t);
8525 TREE_CONSTANT (t) = false;
8527 return t;
8530 if (cp_unevaluated_operand && !manifestly_const_eval)
8531 return t;
8533 tree r = cxx_eval_outermost_constant_expr (t, true, true,
8534 manifestly_const_eval,
8535 false, object);
8536 /* cp_tree_equal looks through NOPs, so allow them. */
8537 gcc_checking_assert (r == t
8538 || CONVERT_EXPR_P (t)
8539 || TREE_CODE (t) == VIEW_CONVERT_EXPR
8540 || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
8541 || !cp_tree_equal (r, t));
8542 return r;
8544 else if (TREE_OVERFLOW_P (t))
8546 t = build_nop (TREE_TYPE (t), t);
8547 TREE_CONSTANT (t) = false;
8550 return t;
8553 /* Like maybe_constant_value but first fully instantiate the argument.
8555 Note: this is equivalent to instantiate_non_dependent_expr (t, complain)
8556 followed by maybe_constant_value but is more efficient,
8557 because it calls instantiation_dependent_expression_p and
8558 potential_constant_expression at most once.
8559 The manifestly_const_eval argument is passed to maybe_constant_value.
8561 Callers should generally pass their active complain, or if they are in a
8562 non-template, diagnosing context, they can use the default of
8563 tf_warning_or_error. Callers that might be within a template context, don't
8564 have a complain parameter, and aren't going to remember the result for long
8565 (e.g. null_ptr_cst_p), can pass tf_none and deal with error_mark_node
8566 appropriately. */
8568 tree
8569 fold_non_dependent_expr (tree t,
8570 tsubst_flags_t complain /* = tf_warning_or_error */,
8571 bool manifestly_const_eval /* = false */,
8572 tree object /* = NULL_TREE */)
8574 if (t == NULL_TREE)
8575 return NULL_TREE;
8577 if (processing_template_decl)
8578 return fold_non_dependent_expr_template (t, complain,
8579 manifestly_const_eval, object);
8581 return maybe_constant_value (t, object, manifestly_const_eval);
8584 /* Like fold_non_dependent_expr, but if EXPR couldn't be folded to a constant,
8585 return the original expression. */
8587 tree
8588 maybe_fold_non_dependent_expr (tree expr,
8589 tsubst_flags_t complain/*=tf_warning_or_error*/)
8591 tree t = fold_non_dependent_expr (expr, complain);
8592 if (t && TREE_CONSTANT (t))
8593 return t;
8595 return expr;
8598 /* Like maybe_constant_init but first fully instantiate the argument. */
8600 tree
8601 fold_non_dependent_init (tree t,
8602 tsubst_flags_t complain /*=tf_warning_or_error*/,
8603 bool manifestly_const_eval /*=false*/,
8604 tree object /* = NULL_TREE */)
8606 if (t == NULL_TREE)
8607 return NULL_TREE;
8609 if (processing_template_decl)
8611 t = fold_non_dependent_expr_template (t, complain,
8612 manifestly_const_eval, object);
8613 /* maybe_constant_init does this stripping, so do it here too. */
8614 if (TREE_CODE (t) == TARGET_EXPR)
8616 tree init = TARGET_EXPR_INITIAL (t);
8617 if (TREE_CODE (init) == CONSTRUCTOR)
8618 t = init;
8620 return t;
8623 return maybe_constant_init (t, object, manifestly_const_eval);
8626 /* Like maybe_constant_value, but returns a CONSTRUCTOR directly, rather
8627 than wrapped in a TARGET_EXPR.
8628 ALLOW_NON_CONSTANT is false if T is required to be a constant expression.
8629 MANIFESTLY_CONST_EVAL is true if T is manifestly const-evaluated as
8630 per P0595 even when ALLOW_NON_CONSTANT is true. */
8632 static tree
8633 maybe_constant_init_1 (tree t, tree decl, bool allow_non_constant,
8634 bool manifestly_const_eval)
8636 if (!t)
8637 return t;
8638 if (TREE_CODE (t) == EXPR_STMT)
8639 t = TREE_OPERAND (t, 0);
8640 if (TREE_CODE (t) == CONVERT_EXPR
8641 && VOID_TYPE_P (TREE_TYPE (t)))
8642 t = TREE_OPERAND (t, 0);
8643 if (TREE_CODE (t) == INIT_EXPR)
8644 t = TREE_OPERAND (t, 1);
8645 if (TREE_CODE (t) == TARGET_EXPR)
8646 t = TARGET_EXPR_INITIAL (t);
8647 if (!is_nondependent_static_init_expression (t))
8648 /* Don't try to evaluate it. */;
8649 else if (CONSTANT_CLASS_P (t) && allow_non_constant)
8650 /* No evaluation needed. */;
8651 else
8653 /* [basic.start.static] allows constant-initialization of variables with
8654 static or thread storage duration even if it isn't required, but we
8655 shouldn't bend the rules the same way for automatic variables. */
8656 bool is_static = (decl && DECL_P (decl)
8657 && (TREE_STATIC (decl) || DECL_EXTERNAL (decl)));
8658 t = cxx_eval_outermost_constant_expr (t, allow_non_constant, !is_static,
8659 manifestly_const_eval, false, decl);
8661 if (TREE_CODE (t) == TARGET_EXPR)
8663 tree init = TARGET_EXPR_INITIAL (t);
8664 if (TREE_CODE (init) == CONSTRUCTOR)
8665 t = init;
8667 return t;
8670 /* Wrapper for maybe_constant_init_1 which permits non constants. */
8672 tree
8673 maybe_constant_init (tree t, tree decl, bool manifestly_const_eval)
8675 return maybe_constant_init_1 (t, decl, true, manifestly_const_eval);
8678 /* Wrapper for maybe_constant_init_1 which does not permit non constants. */
8680 tree
8681 cxx_constant_init (tree t, tree decl)
8683 return maybe_constant_init_1 (t, decl, false, true);
8686 #if 0
8687 /* FIXME see ADDR_EXPR section in potential_constant_expression_1. */
8688 /* Return true if the object referred to by REF has automatic or thread
8689 local storage. */
8691 enum { ck_ok, ck_bad, ck_unknown };
8692 static int
8693 check_automatic_or_tls (tree ref)
8695 machine_mode mode;
8696 poly_int64 bitsize, bitpos;
8697 tree offset;
8698 int volatilep = 0, unsignedp = 0;
8699 tree decl = get_inner_reference (ref, &bitsize, &bitpos, &offset,
8700 &mode, &unsignedp, &volatilep, false);
8701 duration_kind dk;
8703 /* If there isn't a decl in the middle, we don't know the linkage here,
8704 and this isn't a constant expression anyway. */
8705 if (!DECL_P (decl))
8706 return ck_unknown;
8707 dk = decl_storage_duration (decl);
8708 return (dk == dk_auto || dk == dk_thread) ? ck_bad : ck_ok;
8710 #endif
8712 /* Data structure for passing data from potential_constant_expression_1
8713 to check_for_return_continue via cp_walk_tree. */
8714 struct check_for_return_continue_data {
8715 hash_set<tree> *pset;
8716 tree continue_stmt;
8717 tree break_stmt;
8720 /* Helper function for potential_constant_expression_1 SWITCH_STMT handling,
8721 called through cp_walk_tree. Return the first RETURN_EXPR found, or note
8722 the first CONTINUE_STMT and/or BREAK_STMT if RETURN_EXPR is not found. */
8723 static tree
8724 check_for_return_continue (tree *tp, int *walk_subtrees, void *data)
8726 tree t = *tp, s, b;
8727 check_for_return_continue_data *d = (check_for_return_continue_data *) data;
8728 switch (TREE_CODE (t))
8730 case RETURN_EXPR:
8731 return t;
8733 case CONTINUE_STMT:
8734 if (d->continue_stmt == NULL_TREE)
8735 d->continue_stmt = t;
8736 break;
8738 case BREAK_STMT:
8739 if (d->break_stmt == NULL_TREE)
8740 d->break_stmt = t;
8741 break;
8743 #define RECUR(x) \
8744 if (tree r = cp_walk_tree (&x, check_for_return_continue, data, \
8745 d->pset)) \
8746 return r
8748 /* For loops, walk subtrees manually, so that continue stmts found
8749 inside of the bodies of the loops are ignored. */
8750 case DO_STMT:
8751 *walk_subtrees = 0;
8752 RECUR (DO_COND (t));
8753 s = d->continue_stmt;
8754 b = d->break_stmt;
8755 RECUR (DO_BODY (t));
8756 d->continue_stmt = s;
8757 d->break_stmt = b;
8758 break;
8760 case WHILE_STMT:
8761 *walk_subtrees = 0;
8762 RECUR (WHILE_COND (t));
8763 s = d->continue_stmt;
8764 b = d->break_stmt;
8765 RECUR (WHILE_BODY (t));
8766 d->continue_stmt = s;
8767 d->break_stmt = b;
8768 break;
8770 case FOR_STMT:
8771 *walk_subtrees = 0;
8772 RECUR (FOR_INIT_STMT (t));
8773 RECUR (FOR_COND (t));
8774 RECUR (FOR_EXPR (t));
8775 s = d->continue_stmt;
8776 b = d->break_stmt;
8777 RECUR (FOR_BODY (t));
8778 d->continue_stmt = s;
8779 d->break_stmt = b;
8780 break;
8782 case RANGE_FOR_STMT:
8783 *walk_subtrees = 0;
8784 RECUR (RANGE_FOR_EXPR (t));
8785 s = d->continue_stmt;
8786 b = d->break_stmt;
8787 RECUR (RANGE_FOR_BODY (t));
8788 d->continue_stmt = s;
8789 d->break_stmt = b;
8790 break;
8792 case SWITCH_STMT:
8793 *walk_subtrees = 0;
8794 RECUR (SWITCH_STMT_COND (t));
8795 b = d->break_stmt;
8796 RECUR (SWITCH_STMT_BODY (t));
8797 d->break_stmt = b;
8798 break;
8799 #undef RECUR
8801 case STATEMENT_LIST:
8802 case CONSTRUCTOR:
8803 break;
8805 default:
8806 if (!EXPR_P (t))
8807 *walk_subtrees = 0;
8808 break;
8811 return NULL_TREE;
8814 /* Return true if T denotes a potentially constant expression. Issue
8815 diagnostic as appropriate under control of FLAGS. If WANT_RVAL is true,
8816 an lvalue-rvalue conversion is implied. If NOW is true, we want to
8817 consider the expression in the current context, independent of constexpr
8818 substitution. If FUNDEF_P is true, we're checking a constexpr function body
8819 and hard errors should not be reported by constexpr_error.
8821 C++0x [expr.const] used to say
8823 6 An expression is a potential constant expression if it is
8824 a constant expression where all occurrences of function
8825 parameters are replaced by arbitrary constant expressions
8826 of the appropriate type.
8828 2 A conditional expression is a constant expression unless it
8829 involves one of the following as a potentially evaluated
8830 subexpression (3.2), but subexpressions of logical AND (5.14),
8831 logical OR (5.15), and conditional (5.16) operations that are
8832 not evaluated are not considered. */
8834 static bool
8835 potential_constant_expression_1 (tree t, bool want_rval, bool strict, bool now,
8836 bool fundef_p, tsubst_flags_t flags,
8837 tree *jump_target)
8839 #define RECUR(T,RV) \
8840 potential_constant_expression_1 ((T), (RV), strict, now, fundef_p, flags, \
8841 jump_target)
8843 enum { any = false, rval = true };
8844 int i;
8845 tree tmp;
8847 if (t == error_mark_node)
8848 return false;
8849 if (t == NULL_TREE)
8850 return true;
8851 location_t loc = cp_expr_loc_or_input_loc (t);
8853 if (*jump_target)
8854 /* If we are jumping, ignore everything. This is simpler than the
8855 cxx_eval_constant_expression handling because we only need to be
8856 conservatively correct, and we don't necessarily have a constant value
8857 available, so we don't bother with switch tracking. */
8858 return true;
8860 if (TREE_THIS_VOLATILE (t) && want_rval)
8862 if (flags & tf_error)
8863 constexpr_error (loc, fundef_p, "lvalue-to-rvalue conversion of "
8864 "a volatile lvalue %qE with type %qT", t,
8865 TREE_TYPE (t));
8866 return false;
8868 if (CONSTANT_CLASS_P (t))
8869 return true;
8870 if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_TYPED)
8871 && TREE_TYPE (t) == error_mark_node)
8872 return false;
8874 switch (TREE_CODE (t))
8876 case FUNCTION_DECL:
8877 case BASELINK:
8878 case TEMPLATE_DECL:
8879 case OVERLOAD:
8880 case TEMPLATE_ID_EXPR:
8881 case LABEL_DECL:
8882 case CASE_LABEL_EXPR:
8883 case PREDICT_EXPR:
8884 case CONST_DECL:
8885 case SIZEOF_EXPR:
8886 case ALIGNOF_EXPR:
8887 case OFFSETOF_EXPR:
8888 case NOEXCEPT_EXPR:
8889 case TEMPLATE_PARM_INDEX:
8890 case TRAIT_EXPR:
8891 case IDENTIFIER_NODE:
8892 case USERDEF_LITERAL:
8893 /* We can see a FIELD_DECL in a pointer-to-member expression. */
8894 case FIELD_DECL:
8895 case RESULT_DECL:
8896 case USING_DECL:
8897 case USING_STMT:
8898 case PLACEHOLDER_EXPR:
8899 case REQUIRES_EXPR:
8900 case STATIC_ASSERT:
8901 case DEBUG_BEGIN_STMT:
8902 return true;
8904 case RETURN_EXPR:
8905 if (!RECUR (TREE_OPERAND (t, 0), any))
8906 return false;
8907 /* FALLTHROUGH */
8909 case BREAK_STMT:
8910 case CONTINUE_STMT:
8911 *jump_target = t;
8912 return true;
8914 case PARM_DECL:
8915 if (now && want_rval)
8917 tree type = TREE_TYPE (t);
8918 if ((processing_template_decl && !COMPLETE_TYPE_P (type))
8919 || dependent_type_p (type)
8920 || is_really_empty_class (type, /*ignore_vptr*/false))
8921 /* An empty class has no data to read. */
8922 return true;
8923 if (flags & tf_error)
8924 constexpr_error (input_location, fundef_p,
8925 "%qE is not a constant expression", t);
8926 return false;
8928 return true;
8930 case AGGR_INIT_EXPR:
8931 case CALL_EXPR:
8932 /* -- an invocation of a function other than a constexpr function
8933 or a constexpr constructor. */
8935 tree fun = get_function_named_in_call (t);
8936 const int nargs = call_expr_nargs (t);
8937 i = 0;
8939 if (fun == NULL_TREE)
8941 /* Reset to allow the function to continue past the end
8942 of the block below. Otherwise return early. */
8943 bool bail = true;
8945 if (TREE_CODE (t) == CALL_EXPR
8946 && CALL_EXPR_FN (t) == NULL_TREE)
8947 switch (CALL_EXPR_IFN (t))
8949 /* These should be ignored, they are optimized away from
8950 constexpr functions. */
8951 case IFN_UBSAN_NULL:
8952 case IFN_UBSAN_BOUNDS:
8953 case IFN_UBSAN_VPTR:
8954 case IFN_FALLTHROUGH:
8955 case IFN_ASSUME:
8956 return true;
8958 case IFN_ADD_OVERFLOW:
8959 case IFN_SUB_OVERFLOW:
8960 case IFN_MUL_OVERFLOW:
8961 case IFN_LAUNDER:
8962 case IFN_VEC_CONVERT:
8963 bail = false;
8964 break;
8966 default:
8967 break;
8970 if (bail)
8972 /* fold_call_expr can't do anything with IFN calls. */
8973 if (flags & tf_error)
8974 constexpr_error (loc, fundef_p,
8975 "call to internal function %qE", t);
8976 return false;
8980 if (fun && is_overloaded_fn (fun))
8982 if (TREE_CODE (fun) == FUNCTION_DECL)
8984 if (builtin_valid_in_constant_expr_p (fun))
8985 return true;
8986 if (!maybe_constexpr_fn (fun)
8987 /* Allow any built-in function; if the expansion
8988 isn't constant, we'll deal with that then. */
8989 && !fndecl_built_in_p (fun)
8990 /* In C++20, replaceable global allocation functions
8991 are constant expressions. */
8992 && (!cxx_replaceable_global_alloc_fn (fun)
8993 || TREE_CODE (t) != CALL_EXPR
8994 || (!CALL_FROM_NEW_OR_DELETE_P (t)
8995 && (current_function_decl == NULL_TREE
8996 || !is_std_allocator_allocate
8997 (current_function_decl))))
8998 /* Allow placement new in std::construct_at. */
8999 && (!cxx_placement_new_fn (fun)
9000 || TREE_CODE (t) != CALL_EXPR
9001 || current_function_decl == NULL_TREE
9002 || !is_std_construct_at (current_function_decl))
9003 && !cxx_dynamic_cast_fn_p (fun))
9005 if ((flags & tf_error)
9006 && constexpr_error (loc, fundef_p,
9007 "call to non-%<constexpr%> "
9008 "function %qD", fun))
9009 explain_invalid_constexpr_fn (fun);
9010 return false;
9012 /* A call to a non-static member function takes the address
9013 of the object as the first argument. But in a constant
9014 expression the address will be folded away, so look
9015 through it now. */
9016 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fun)
9017 && !DECL_CONSTRUCTOR_P (fun))
9019 tree x = get_nth_callarg (t, 0);
9020 if (is_this_parameter (x))
9021 return true;
9022 /* Don't require an immediately constant value, as
9023 constexpr substitution might not use the value. */
9024 bool sub_now = false;
9025 if (!potential_constant_expression_1 (x, rval, strict,
9026 sub_now, fundef_p,
9027 flags, jump_target))
9028 return false;
9029 i = 1;
9032 else
9034 if (!RECUR (fun, true))
9035 return false;
9036 fun = get_first_fn (fun);
9038 /* Skip initial arguments to base constructors. */
9039 if (DECL_BASE_CONSTRUCTOR_P (fun))
9040 i = num_artificial_parms_for (fun);
9041 fun = DECL_ORIGIN (fun);
9043 else if (fun)
9045 if (RECUR (fun, rval))
9046 /* Might end up being a constant function pointer. */;
9047 else
9048 return false;
9050 for (; i < nargs; ++i)
9052 tree x = get_nth_callarg (t, i);
9053 /* In a template, reference arguments haven't been converted to
9054 REFERENCE_TYPE and we might not even know if the parameter
9055 is a reference, so accept lvalue constants too. */
9056 bool rv = processing_template_decl ? any : rval;
9057 /* Don't require an immediately constant value, as constexpr
9058 substitution might not use the value of the argument. */
9059 bool sub_now = false;
9060 if (!potential_constant_expression_1 (x, rv, strict,
9061 sub_now, fundef_p, flags,
9062 jump_target))
9063 return false;
9065 return true;
9068 case NON_LVALUE_EXPR:
9069 /* -- an lvalue-to-rvalue conversion (4.1) unless it is applied to
9070 -- an lvalue of integral type that refers to a non-volatile
9071 const variable or static data member initialized with
9072 constant expressions, or
9074 -- an lvalue of literal type that refers to non-volatile
9075 object defined with constexpr, or that refers to a
9076 sub-object of such an object; */
9077 return RECUR (TREE_OPERAND (t, 0), rval);
9079 case EXCESS_PRECISION_EXPR:
9080 return RECUR (TREE_OPERAND (t, 0), rval);
9082 case VAR_DECL:
9083 if (DECL_HAS_VALUE_EXPR_P (t))
9085 if (now && is_normal_capture_proxy (t))
9087 /* -- in a lambda-expression, a reference to this or to a
9088 variable with automatic storage duration defined outside that
9089 lambda-expression, where the reference would be an
9090 odr-use. */
9092 if (want_rval)
9093 /* Since we're doing an lvalue-rvalue conversion, this might
9094 not be an odr-use, so evaluate the variable directly. */
9095 return RECUR (DECL_CAPTURED_VARIABLE (t), rval);
9097 if (flags & tf_error)
9099 tree cap = DECL_CAPTURED_VARIABLE (t);
9100 if (constexpr_error (input_location, fundef_p,
9101 "lambda capture of %qE is not a "
9102 "constant expression", cap)
9103 && decl_constant_var_p (cap))
9104 inform (input_location, "because it is used as a glvalue");
9106 return false;
9108 /* Treat __PRETTY_FUNCTION__ inside a template function as
9109 potentially-constant. */
9110 else if (DECL_PRETTY_FUNCTION_P (t)
9111 && DECL_VALUE_EXPR (t) == error_mark_node)
9112 return true;
9113 return RECUR (DECL_VALUE_EXPR (t), rval);
9115 if (want_rval
9116 && !var_in_maybe_constexpr_fn (t)
9117 && !type_dependent_expression_p (t)
9118 && !decl_maybe_constant_var_p (t)
9119 && (strict
9120 || !CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (t))
9121 || (DECL_INITIAL (t)
9122 && !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t)))
9123 && COMPLETE_TYPE_P (TREE_TYPE (t))
9124 && !is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
9126 if (flags & tf_error)
9127 non_const_var_error (loc, t, fundef_p);
9128 return false;
9130 return true;
9132 case NOP_EXPR:
9133 if (REINTERPRET_CAST_P (t))
9135 if (flags & tf_error)
9136 constexpr_error (loc, fundef_p, "%<reinterpret_cast%> is not a "
9137 "constant expression");
9138 return false;
9140 /* FALLTHRU */
9141 case CONVERT_EXPR:
9142 case VIEW_CONVERT_EXPR:
9143 /* -- a reinterpret_cast. FIXME not implemented, and this rule
9144 may change to something more specific to type-punning (DR 1312). */
9146 tree from = TREE_OPERAND (t, 0);
9147 if (location_wrapper_p (t))
9149 iloc_sentinel ils = loc;
9150 return (RECUR (from, want_rval));
9152 if (INDIRECT_TYPE_P (TREE_TYPE (t)))
9154 STRIP_ANY_LOCATION_WRAPPER (from);
9155 if (TREE_CODE (from) == INTEGER_CST
9156 && !integer_zerop (from))
9158 if (flags & tf_error)
9159 constexpr_error (loc, fundef_p,
9160 "%<reinterpret_cast%> from integer to "
9161 "pointer");
9162 return false;
9165 return (RECUR (from, TREE_CODE (t) != VIEW_CONVERT_EXPR));
9168 case ADDRESSOF_EXPR:
9169 /* This is like ADDR_EXPR, except it won't form pointer-to-member. */
9170 t = TREE_OPERAND (t, 0);
9171 goto handle_addr_expr;
9173 case ADDR_EXPR:
9174 /* -- a unary operator & that is applied to an lvalue that
9175 designates an object with thread or automatic storage
9176 duration; */
9177 t = TREE_OPERAND (t, 0);
9179 if (TREE_CODE (t) == OFFSET_REF && PTRMEM_OK_P (t))
9180 /* A pointer-to-member constant. */
9181 return true;
9183 handle_addr_expr:
9184 #if 0
9185 /* FIXME adjust when issue 1197 is fully resolved. For now don't do
9186 any checking here, as we might dereference the pointer later. If
9187 we remove this code, also remove check_automatic_or_tls. */
9188 i = check_automatic_or_tls (t);
9189 if (i == ck_ok)
9190 return true;
9191 if (i == ck_bad)
9193 if (flags & tf_error)
9194 error ("address-of an object %qE with thread local or "
9195 "automatic storage is not a constant expression", t);
9196 return false;
9198 #endif
9199 return RECUR (t, any);
9201 case COMPONENT_REF:
9202 case ARROW_EXPR:
9203 case OFFSET_REF:
9204 /* -- a class member access unless its postfix-expression is
9205 of literal type or of pointer to literal type. */
9206 /* This test would be redundant, as it follows from the
9207 postfix-expression being a potential constant expression. */
9208 if (type_unknown_p (t))
9209 return true;
9210 if (is_overloaded_fn (t))
9211 /* In a template, a COMPONENT_REF of a function expresses ob.fn(),
9212 which uses ob as an lvalue. */
9213 want_rval = false;
9214 gcc_fallthrough ();
9216 case REALPART_EXPR:
9217 case IMAGPART_EXPR:
9218 case BIT_FIELD_REF:
9219 return RECUR (TREE_OPERAND (t, 0), want_rval);
9221 case EXPR_PACK_EXPANSION:
9222 return RECUR (PACK_EXPANSION_PATTERN (t), want_rval);
9224 case INDIRECT_REF:
9226 tree x = TREE_OPERAND (t, 0);
9227 STRIP_NOPS (x);
9228 if (is_this_parameter (x) && !is_capture_proxy (x))
9230 if (!var_in_maybe_constexpr_fn (x))
9232 if (flags & tf_error)
9233 constexpr_error (loc, fundef_p, "use of %<this%> in a "
9234 "constant expression");
9235 return false;
9237 return true;
9239 return RECUR (x, rval);
9242 case STATEMENT_LIST:
9243 for (tree stmt : tsi_range (t))
9244 if (!RECUR (stmt, any))
9245 return false;
9246 return true;
9248 case MODIFY_EXPR:
9249 if (cxx_dialect < cxx14)
9250 goto fail;
9251 if (!RECUR (TREE_OPERAND (t, 0), any))
9252 return false;
9253 /* Just ignore clobbers. */
9254 if (TREE_CLOBBER_P (TREE_OPERAND (t, 1)))
9255 return true;
9256 if (!RECUR (TREE_OPERAND (t, 1), rval))
9257 return false;
9258 return true;
9260 case MODOP_EXPR:
9261 if (cxx_dialect < cxx14)
9262 goto fail;
9263 if (!RECUR (TREE_OPERAND (t, 0), rval))
9264 return false;
9265 if (!RECUR (TREE_OPERAND (t, 2), rval))
9266 return false;
9267 return true;
9269 case DO_STMT:
9270 if (!RECUR (DO_COND (t), rval))
9271 return false;
9272 if (!RECUR (DO_BODY (t), any))
9273 return false;
9274 if (breaks (jump_target) || continues (jump_target))
9275 *jump_target = NULL_TREE;
9276 return true;
9278 case FOR_STMT:
9279 if (!RECUR (FOR_INIT_STMT (t), any))
9280 return false;
9281 tmp = FOR_COND (t);
9282 if (!RECUR (tmp, rval))
9283 return false;
9284 if (tmp)
9286 if (!processing_template_decl)
9287 tmp = cxx_eval_outermost_constant_expr (tmp, true);
9288 /* If we couldn't evaluate the condition, it might not ever be
9289 true. */
9290 if (!integer_onep (tmp))
9292 /* Before returning true, check if the for body can contain
9293 a return. */
9294 hash_set<tree> pset;
9295 check_for_return_continue_data data = { &pset, NULL_TREE,
9296 NULL_TREE };
9297 if (tree ret_expr
9298 = cp_walk_tree (&FOR_BODY (t), check_for_return_continue,
9299 &data, &pset))
9300 *jump_target = ret_expr;
9301 return true;
9304 if (!RECUR (FOR_EXPR (t), any))
9305 return false;
9306 if (!RECUR (FOR_BODY (t), any))
9307 return false;
9308 if (breaks (jump_target) || continues (jump_target))
9309 *jump_target = NULL_TREE;
9310 return true;
9312 case RANGE_FOR_STMT:
9313 if (!RECUR (RANGE_FOR_INIT_STMT (t), any))
9314 return false;
9315 if (!RECUR (RANGE_FOR_EXPR (t), any))
9316 return false;
9317 if (!RECUR (RANGE_FOR_BODY (t), any))
9318 return false;
9319 if (breaks (jump_target) || continues (jump_target))
9320 *jump_target = NULL_TREE;
9321 return true;
9323 case WHILE_STMT:
9324 tmp = WHILE_COND (t);
9325 if (!RECUR (tmp, rval))
9326 return false;
9327 if (!processing_template_decl)
9328 tmp = cxx_eval_outermost_constant_expr (tmp, true);
9329 /* If we couldn't evaluate the condition, it might not ever be true. */
9330 if (!integer_onep (tmp))
9332 /* Before returning true, check if the while body can contain
9333 a return. */
9334 hash_set<tree> pset;
9335 check_for_return_continue_data data = { &pset, NULL_TREE,
9336 NULL_TREE };
9337 if (tree ret_expr
9338 = cp_walk_tree (&WHILE_BODY (t), check_for_return_continue,
9339 &data, &pset))
9340 *jump_target = ret_expr;
9341 return true;
9343 if (!RECUR (WHILE_BODY (t), any))
9344 return false;
9345 if (breaks (jump_target) || continues (jump_target))
9346 *jump_target = NULL_TREE;
9347 return true;
9349 case SWITCH_STMT:
9350 if (!RECUR (SWITCH_STMT_COND (t), rval))
9351 return false;
9352 /* FIXME we don't check SWITCH_STMT_BODY currently, because even
9353 unreachable labels would be checked and it is enough if there is
9354 a single switch cond value for which it is a valid constant
9355 expression. We need to check if there are any RETURN_EXPRs
9356 or CONTINUE_STMTs inside of the body though, as in that case
9357 we need to set *jump_target. */
9358 else
9360 hash_set<tree> pset;
9361 check_for_return_continue_data data = { &pset, NULL_TREE,
9362 NULL_TREE };
9363 if (tree ret_expr
9364 = cp_walk_tree (&SWITCH_STMT_BODY (t), check_for_return_continue,
9365 &data, &pset))
9366 /* The switch might return. */
9367 *jump_target = ret_expr;
9368 else if (data.continue_stmt)
9369 /* The switch can't return, but might continue. */
9370 *jump_target = data.continue_stmt;
9372 return true;
9374 case STMT_EXPR:
9375 return RECUR (STMT_EXPR_STMT (t), rval);
9377 case LAMBDA_EXPR:
9378 if (cxx_dialect >= cxx17)
9379 /* In C++17 lambdas can be constexpr, don't give up yet. */
9380 return true;
9381 else if (flags & tf_error)
9382 constexpr_error (loc, fundef_p, "lambda-expression is not a "
9383 "constant expression before C++17");
9384 return false;
9386 case NEW_EXPR:
9387 case VEC_NEW_EXPR:
9388 case DELETE_EXPR:
9389 case VEC_DELETE_EXPR:
9390 if (cxx_dialect >= cxx20)
9391 /* In C++20, new-expressions are potentially constant. */
9392 return true;
9393 else if (flags & tf_error)
9394 constexpr_error (loc, fundef_p, "new-expression is not a "
9395 "constant expression before C++20");
9396 return false;
9398 case DYNAMIC_CAST_EXPR:
9399 case PSEUDO_DTOR_EXPR:
9400 case THROW_EXPR:
9401 case OMP_PARALLEL:
9402 case OMP_TASK:
9403 case OMP_FOR:
9404 case OMP_SIMD:
9405 case OMP_DISTRIBUTE:
9406 case OMP_TASKLOOP:
9407 case OMP_LOOP:
9408 case OMP_TEAMS:
9409 case OMP_TARGET_DATA:
9410 case OMP_TARGET:
9411 case OMP_SECTIONS:
9412 case OMP_ORDERED:
9413 case OMP_CRITICAL:
9414 case OMP_SINGLE:
9415 case OMP_SECTION:
9416 case OMP_MASTER:
9417 case OMP_MASKED:
9418 case OMP_TASKGROUP:
9419 case OMP_TARGET_UPDATE:
9420 case OMP_TARGET_ENTER_DATA:
9421 case OMP_TARGET_EXIT_DATA:
9422 case OMP_ATOMIC:
9423 case OMP_ATOMIC_READ:
9424 case OMP_ATOMIC_CAPTURE_OLD:
9425 case OMP_ATOMIC_CAPTURE_NEW:
9426 case OMP_DEPOBJ:
9427 case OACC_PARALLEL:
9428 case OACC_KERNELS:
9429 case OACC_SERIAL:
9430 case OACC_DATA:
9431 case OACC_HOST_DATA:
9432 case OACC_LOOP:
9433 case OACC_CACHE:
9434 case OACC_DECLARE:
9435 case OACC_ENTER_DATA:
9436 case OACC_EXIT_DATA:
9437 case OACC_UPDATE:
9438 /* GCC internal stuff. */
9439 case VA_ARG_EXPR:
9440 case TRANSACTION_EXPR:
9441 case AT_ENCODE_EXPR:
9442 fail:
9443 if (flags & tf_error)
9444 constexpr_error (loc, fundef_p, "expression %qE is not a constant "
9445 "expression", t);
9446 return false;
9448 case ASM_EXPR:
9449 if (flags & tf_error)
9450 inline_asm_in_constexpr_error (loc, fundef_p);
9451 return false;
9453 case OBJ_TYPE_REF:
9454 if (cxx_dialect >= cxx20)
9455 /* In C++20 virtual calls can be constexpr, don't give up yet. */
9456 return true;
9457 else if (flags & tf_error)
9458 constexpr_error (loc, fundef_p, "virtual functions cannot be "
9459 "%<constexpr%> before C++20");
9460 return false;
9462 case TYPEID_EXPR:
9463 /* In C++20, a typeid expression whose operand is of polymorphic
9464 class type can be constexpr. */
9466 tree e = TREE_OPERAND (t, 0);
9467 if (cxx_dialect < cxx20
9468 && strict
9469 && !TYPE_P (e)
9470 && !type_dependent_expression_p (e)
9471 && TYPE_POLYMORPHIC_P (TREE_TYPE (e)))
9473 if (flags & tf_error)
9474 constexpr_error (loc, fundef_p, "%<typeid%> is not a "
9475 "constant expression because %qE is "
9476 "of polymorphic type", e);
9477 return false;
9479 return true;
9482 case POINTER_DIFF_EXPR:
9483 case MINUS_EXPR:
9484 want_rval = true;
9485 goto binary;
9487 case LT_EXPR:
9488 case LE_EXPR:
9489 case GT_EXPR:
9490 case GE_EXPR:
9491 case EQ_EXPR:
9492 case NE_EXPR:
9493 case SPACESHIP_EXPR:
9494 want_rval = true;
9495 goto binary;
9497 case PREINCREMENT_EXPR:
9498 case POSTINCREMENT_EXPR:
9499 case PREDECREMENT_EXPR:
9500 case POSTDECREMENT_EXPR:
9501 if (cxx_dialect < cxx14)
9502 goto fail;
9503 goto unary;
9505 case BIT_NOT_EXPR:
9506 /* A destructor. */
9507 if (TYPE_P (TREE_OPERAND (t, 0)))
9508 return true;
9509 /* fall through. */
9511 case CONJ_EXPR:
9512 case SAVE_EXPR:
9513 case FIX_TRUNC_EXPR:
9514 case FLOAT_EXPR:
9515 case NEGATE_EXPR:
9516 case ABS_EXPR:
9517 case ABSU_EXPR:
9518 case TRUTH_NOT_EXPR:
9519 case FIXED_CONVERT_EXPR:
9520 case UNARY_PLUS_EXPR:
9521 case UNARY_LEFT_FOLD_EXPR:
9522 case UNARY_RIGHT_FOLD_EXPR:
9523 unary:
9524 return RECUR (TREE_OPERAND (t, 0), rval);
9526 case CAST_EXPR:
9527 case CONST_CAST_EXPR:
9528 case STATIC_CAST_EXPR:
9529 case REINTERPRET_CAST_EXPR:
9530 case IMPLICIT_CONV_EXPR:
9531 if (!cast_valid_in_integral_constant_expression_p (TREE_TYPE (t)))
9532 /* In C++98, a conversion to non-integral type can't be part of a
9533 constant expression. */
9535 if (flags & tf_error)
9536 constexpr_error (loc, fundef_p,
9537 "cast to non-integral type %qT in a constant "
9538 "expression", TREE_TYPE (t));
9539 return false;
9541 /* This might be a conversion from a class to a (potentially) literal
9542 type. Let's consider it potentially constant since the conversion
9543 might be a constexpr user-defined conversion. */
9544 else if (cxx_dialect >= cxx11
9545 && (dependent_type_p (TREE_TYPE (t))
9546 || !COMPLETE_TYPE_P (TREE_TYPE (t))
9547 || literal_type_p (TREE_TYPE (t)))
9548 && TREE_OPERAND (t, 0))
9550 tree type = TREE_TYPE (TREE_OPERAND (t, 0));
9551 /* If this is a dependent type, it could end up being a class
9552 with conversions. */
9553 if (type == NULL_TREE || WILDCARD_TYPE_P (type))
9554 return true;
9555 /* Or a non-dependent class which has conversions. */
9556 else if (CLASS_TYPE_P (type)
9557 && (TYPE_HAS_CONVERSION (type) || dependent_scope_p (type)))
9558 return true;
9561 return (RECUR (TREE_OPERAND (t, 0),
9562 !TYPE_REF_P (TREE_TYPE (t))));
9564 case BIND_EXPR:
9565 return RECUR (BIND_EXPR_BODY (t), want_rval);
9567 case NON_DEPENDENT_EXPR:
9568 /* Treat NON_DEPENDENT_EXPR as non-constant: it's not handled by
9569 constexpr evaluation or tsubst, so fold_non_dependent_expr can't
9570 do anything useful with it. And we shouldn't see it in a context
9571 where a constant expression is strictly required, hence the assert. */
9572 gcc_checking_assert (!(flags & tf_error));
9573 return false;
9575 case CLEANUP_POINT_EXPR:
9576 case MUST_NOT_THROW_EXPR:
9577 case TRY_CATCH_EXPR:
9578 case TRY_BLOCK:
9579 case EH_SPEC_BLOCK:
9580 case EXPR_STMT:
9581 case PAREN_EXPR:
9582 /* For convenience. */
9583 case LOOP_EXPR:
9584 case EXIT_EXPR:
9585 return RECUR (TREE_OPERAND (t, 0), want_rval);
9587 case DECL_EXPR:
9588 tmp = DECL_EXPR_DECL (t);
9589 if (VAR_P (tmp) && !DECL_ARTIFICIAL (tmp))
9591 if (CP_DECL_THREAD_LOCAL_P (tmp) && !DECL_REALLY_EXTERN (tmp))
9593 if (flags & tf_error)
9594 constexpr_error (DECL_SOURCE_LOCATION (tmp), fundef_p,
9595 "%qD defined %<thread_local%> in "
9596 "%<constexpr%> context", tmp);
9597 return false;
9599 else if (TREE_STATIC (tmp))
9601 if (flags & tf_error)
9602 constexpr_error (DECL_SOURCE_LOCATION (tmp), fundef_p,
9603 "%qD defined %<static%> in %<constexpr%> "
9604 "context", tmp);
9605 return false;
9607 else if (!check_for_uninitialized_const_var
9608 (tmp, /*constexpr_context_p=*/true, flags))
9609 return false;
9611 return RECUR (DECL_INITIAL (tmp), want_rval);
9613 case TRY_FINALLY_EXPR:
9614 return (RECUR (TREE_OPERAND (t, 0), want_rval)
9615 && RECUR (TREE_OPERAND (t, 1), any));
9617 case SCOPE_REF:
9618 return RECUR (TREE_OPERAND (t, 1), want_rval);
9620 case TARGET_EXPR:
9621 if (!TARGET_EXPR_DIRECT_INIT_P (t)
9622 && !literal_type_p (TREE_TYPE (t)))
9624 if (flags & tf_error)
9626 auto_diagnostic_group d;
9627 if (constexpr_error (loc, fundef_p,
9628 "temporary of non-literal type %qT in a "
9629 "constant expression", TREE_TYPE (t)))
9630 explain_non_literal_class (TREE_TYPE (t));
9632 return false;
9634 /* FALLTHRU */
9635 case INIT_EXPR:
9636 return RECUR (TREE_OPERAND (t, 1), rval);
9638 case CONSTRUCTOR:
9640 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
9641 constructor_elt *ce;
9642 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
9643 if (!RECUR (ce->value, want_rval))
9644 return false;
9645 return true;
9648 case TREE_LIST:
9650 gcc_assert (TREE_PURPOSE (t) == NULL_TREE
9651 || DECL_P (TREE_PURPOSE (t)));
9652 if (!RECUR (TREE_VALUE (t), want_rval))
9653 return false;
9654 if (TREE_CHAIN (t) == NULL_TREE)
9655 return true;
9656 return RECUR (TREE_CHAIN (t), want_rval);
9659 case TRUNC_DIV_EXPR:
9660 case CEIL_DIV_EXPR:
9661 case FLOOR_DIV_EXPR:
9662 case ROUND_DIV_EXPR:
9663 case TRUNC_MOD_EXPR:
9664 case CEIL_MOD_EXPR:
9665 case ROUND_MOD_EXPR:
9667 tree denom = TREE_OPERAND (t, 1);
9668 if (!RECUR (denom, rval))
9669 return false;
9670 /* We can't call cxx_eval_outermost_constant_expr on an expression
9671 that hasn't been through instantiate_non_dependent_expr yet. */
9672 if (!processing_template_decl)
9673 denom = cxx_eval_outermost_constant_expr (denom, true);
9674 if (integer_zerop (denom))
9676 if (flags & tf_error)
9677 constexpr_error (input_location, fundef_p,
9678 "division by zero is not a constant expression");
9679 return false;
9681 else
9683 want_rval = true;
9684 return RECUR (TREE_OPERAND (t, 0), want_rval);
9688 case COMPOUND_EXPR:
9690 /* check_return_expr sometimes wraps a TARGET_EXPR in a
9691 COMPOUND_EXPR; don't get confused. */
9692 tree op0 = TREE_OPERAND (t, 0);
9693 tree op1 = TREE_OPERAND (t, 1);
9694 STRIP_NOPS (op1);
9695 if (TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
9696 return RECUR (op0, want_rval);
9697 else
9698 goto binary;
9701 /* If the first operand is the non-short-circuit constant, look at
9702 the second operand; otherwise we only care about the first one for
9703 potentiality. */
9704 case TRUTH_AND_EXPR:
9705 case TRUTH_ANDIF_EXPR:
9706 tmp = boolean_true_node;
9707 goto truth;
9708 case TRUTH_OR_EXPR:
9709 case TRUTH_ORIF_EXPR:
9710 tmp = boolean_false_node;
9711 truth:
9713 tree op0 = TREE_OPERAND (t, 0);
9714 tree op1 = TREE_OPERAND (t, 1);
9715 if (!RECUR (op0, rval))
9716 return false;
9717 if (!(flags & tf_error) && RECUR (op1, rval))
9718 /* When quiet, try to avoid expensive trial evaluation by first
9719 checking potentiality of the second operand. */
9720 return true;
9721 if (!processing_template_decl)
9722 op0 = cxx_eval_outermost_constant_expr (op0, true);
9723 if (tree_int_cst_equal (op0, tmp))
9724 return (flags & tf_error) ? RECUR (op1, rval) : false;
9725 else
9726 return true;
9729 case PLUS_EXPR:
9730 case MULT_EXPR:
9731 case POINTER_PLUS_EXPR:
9732 case RDIV_EXPR:
9733 case EXACT_DIV_EXPR:
9734 case MIN_EXPR:
9735 case MAX_EXPR:
9736 case LSHIFT_EXPR:
9737 case RSHIFT_EXPR:
9738 case LROTATE_EXPR:
9739 case RROTATE_EXPR:
9740 case BIT_IOR_EXPR:
9741 case BIT_XOR_EXPR:
9742 case BIT_AND_EXPR:
9743 case TRUTH_XOR_EXPR:
9744 case UNORDERED_EXPR:
9745 case ORDERED_EXPR:
9746 case UNLT_EXPR:
9747 case UNLE_EXPR:
9748 case UNGT_EXPR:
9749 case UNGE_EXPR:
9750 case UNEQ_EXPR:
9751 case LTGT_EXPR:
9752 case RANGE_EXPR:
9753 case COMPLEX_EXPR:
9754 want_rval = true;
9755 /* Fall through. */
9756 case ARRAY_REF:
9757 case ARRAY_RANGE_REF:
9758 case MEMBER_REF:
9759 case DOTSTAR_EXPR:
9760 case MEM_REF:
9761 case BINARY_LEFT_FOLD_EXPR:
9762 case BINARY_RIGHT_FOLD_EXPR:
9763 binary:
9764 for (i = 0; i < 2; ++i)
9765 if (!RECUR (TREE_OPERAND (t, i), want_rval))
9766 return false;
9767 return true;
9769 case VEC_PERM_EXPR:
9770 for (i = 0; i < 3; ++i)
9771 if (!RECUR (TREE_OPERAND (t, i), true))
9772 return false;
9773 return true;
9775 case COND_EXPR:
9776 if (COND_EXPR_IS_VEC_DELETE (t) && cxx_dialect < cxx20)
9778 if (flags & tf_error)
9779 constexpr_error (loc, fundef_p, "%<delete[]%> is not a "
9780 "constant expression");
9781 return false;
9783 /* Fall through. */
9784 case IF_STMT:
9785 case VEC_COND_EXPR:
9786 /* If the condition is a known constant, we know which of the legs we
9787 care about; otherwise we only require that the condition and
9788 either of the legs be potentially constant. */
9789 tmp = TREE_OPERAND (t, 0);
9790 if (!RECUR (tmp, rval))
9791 return false;
9792 if (!processing_template_decl)
9793 tmp = cxx_eval_outermost_constant_expr (tmp, true);
9794 /* potential_constant_expression* isn't told if it is called for
9795 manifestly_const_eval or not, so for consteval if always
9796 process both branches as if the condition is not a known
9797 constant. */
9798 if (TREE_CODE (t) != IF_STMT || !IF_STMT_CONSTEVAL_P (t))
9800 if (integer_zerop (tmp))
9801 return RECUR (TREE_OPERAND (t, 2), want_rval);
9802 else if (TREE_CODE (tmp) == INTEGER_CST)
9803 return RECUR (TREE_OPERAND (t, 1), want_rval);
9805 tmp = *jump_target;
9806 for (i = 1; i < 3; ++i)
9808 tree this_jump_target = tmp;
9809 if (potential_constant_expression_1 (TREE_OPERAND (t, i),
9810 want_rval, strict, now, fundef_p,
9811 tf_none, &this_jump_target))
9813 if (returns (&this_jump_target))
9814 *jump_target = this_jump_target;
9815 else if (!returns (jump_target))
9817 if (breaks (&this_jump_target)
9818 || continues (&this_jump_target))
9819 *jump_target = this_jump_target;
9820 if (i == 1)
9822 /* If the then branch is potentially constant, but
9823 does not return, check if the else branch
9824 couldn't return, break or continue. */
9825 hash_set<tree> pset;
9826 check_for_return_continue_data data = { &pset, NULL_TREE,
9827 NULL_TREE };
9828 if (tree ret_expr
9829 = cp_walk_tree (&TREE_OPERAND (t, 2),
9830 check_for_return_continue, &data,
9831 &pset))
9832 *jump_target = ret_expr;
9833 else if (*jump_target == NULL_TREE)
9835 if (data.continue_stmt)
9836 *jump_target = data.continue_stmt;
9837 else if (data.break_stmt)
9838 *jump_target = data.break_stmt;
9842 return true;
9845 if (flags & tf_error)
9847 if (TREE_CODE (t) == IF_STMT)
9848 constexpr_error (loc, fundef_p, "neither branch of %<if%> is a "
9849 "constant expression");
9850 else
9851 constexpr_error (loc, fundef_p, "expression %qE is not a "
9852 "constant expression", t);
9854 return false;
9856 case VEC_INIT_EXPR:
9857 if (VEC_INIT_EXPR_IS_CONSTEXPR (t))
9858 return true;
9859 if (flags & tf_error)
9861 if (constexpr_error (loc, fundef_p, "non-constant array "
9862 "initialization"))
9863 diagnose_non_constexpr_vec_init (t);
9865 return false;
9867 case TYPE_DECL:
9868 case TAG_DEFN:
9869 /* We can see these in statement-expressions. */
9870 return true;
9872 case CLEANUP_STMT:
9873 if (!RECUR (CLEANUP_BODY (t), any))
9874 return false;
9875 if (!CLEANUP_EH_ONLY (t) && !RECUR (CLEANUP_EXPR (t), any))
9876 return false;
9877 return true;
9879 case EMPTY_CLASS_EXPR:
9880 return true;
9882 case GOTO_EXPR:
9884 tree *target = &TREE_OPERAND (t, 0);
9885 /* Gotos representing break, continue and cdtor return are OK. */
9886 if (breaks (target) || continues (target) || returns (target))
9888 *jump_target = *target;
9889 return true;
9891 if (flags & tf_error)
9892 constexpr_error (loc, fundef_p, "%<goto%> is not a constant "
9893 "expression");
9894 return false;
9897 case LABEL_EXPR:
9898 t = LABEL_EXPR_LABEL (t);
9899 if (DECL_ARTIFICIAL (t) || cxx_dialect >= cxx23)
9900 return true;
9901 else if (flags & tf_error)
9902 constexpr_error (loc, fundef_p, "label definition in %<constexpr%> "
9903 "function only available with %<-std=c++2b%> or "
9904 "%<-std=gnu++2b%>");
9905 return false;
9907 case ANNOTATE_EXPR:
9908 return RECUR (TREE_OPERAND (t, 0), rval);
9910 case BIT_CAST_EXPR:
9911 return RECUR (TREE_OPERAND (t, 0), rval);
9913 /* Coroutine await, yield and return expressions are not. */
9914 case CO_AWAIT_EXPR:
9915 case CO_YIELD_EXPR:
9916 case CO_RETURN_EXPR:
9917 return false;
9919 case NONTYPE_ARGUMENT_PACK:
9921 tree args = ARGUMENT_PACK_ARGS (t);
9922 int len = TREE_VEC_LENGTH (args);
9923 for (int i = 0; i < len; ++i)
9924 if (!RECUR (TREE_VEC_ELT (args, i), any))
9925 return false;
9926 return true;
9929 default:
9930 if (objc_non_constant_expr_p (t))
9931 return false;
9933 sorry ("unexpected AST of kind %s", get_tree_code_name (TREE_CODE (t)));
9934 gcc_unreachable ();
9935 return false;
9937 #undef RECUR
9940 bool
9941 potential_constant_expression_1 (tree t, bool want_rval, bool strict, bool now,
9942 bool fundef_p, tsubst_flags_t flags)
9944 if (flags & tf_error)
9946 /* Check potentiality quietly first, as that could be performed more
9947 efficiently in some cases (currently only for TRUTH_*_EXPR). If
9948 that fails, replay the check noisily to give errors. */
9949 flags &= ~tf_error;
9950 if (potential_constant_expression_1 (t, want_rval, strict, now, fundef_p,
9951 flags))
9952 return true;
9953 flags |= tf_error;
9956 tree target = NULL_TREE;
9957 return potential_constant_expression_1 (t, want_rval, strict, now, fundef_p,
9958 flags, &target);
9961 /* The main entry point to the above. */
9963 bool
9964 potential_constant_expression (tree t)
9966 return potential_constant_expression_1 (t, /*want_rval*/false, /*strict*/true,
9967 /*now*/false, /*fundef_p*/false,
9968 tf_none);
9971 /* As above, but require a constant rvalue. */
9973 bool
9974 potential_rvalue_constant_expression (tree t)
9976 return potential_constant_expression_1 (t, /*want_rval*/true, /*strict*/true,
9977 /*now*/false, /*fundef_p*/false,
9978 tf_none);
9981 /* Like above, but complain about non-constant expressions. */
9983 bool
9984 require_potential_constant_expression (tree t)
9986 return potential_constant_expression_1 (t, /*want_rval*/false, /*strict*/true,
9987 /*now*/false, /*fundef_p*/false,
9988 tf_warning_or_error);
9991 /* Cross product of the above. */
9993 bool
9994 require_potential_rvalue_constant_expression (tree t)
9996 return potential_constant_expression_1 (t, /*want_rval*/true, /*strict*/true,
9997 /*now*/false, /*fundef_p*/false,
9998 tf_warning_or_error);
10001 /* Like require_potential_rvalue_constant_expression, but fundef_p is true. */
10003 bool
10004 require_potential_rvalue_constant_expression_fncheck (tree t)
10006 return potential_constant_expression_1 (t, /*want_rval*/true, /*strict*/true,
10007 /*now*/false, /*fundef_p*/true,
10008 tf_warning_or_error);
10011 /* Like above, but don't consider PARM_DECL a potential_constant_expression. */
10013 bool
10014 require_rvalue_constant_expression (tree t)
10016 return potential_constant_expression_1 (t, /*want_rval*/true, /*strict*/true,
10017 /*now*/true, /*fundef_p*/false,
10018 tf_warning_or_error);
10021 /* Like potential_constant_expression, but don't consider possible constexpr
10022 substitution of the current function. That is, PARM_DECL qualifies under
10023 potential_constant_expression, but not here.
10025 This is basically what you can check when any actual constant values might
10026 be value-dependent. */
10028 bool
10029 is_constant_expression (tree t)
10031 return potential_constant_expression_1 (t, /*want_rval*/false, /*strict*/true,
10032 /*now*/true, /*fundef_p*/false,
10033 tf_none);
10036 /* As above, but expect an rvalue. */
10038 bool
10039 is_rvalue_constant_expression (tree t)
10041 return potential_constant_expression_1 (t, /*want_rval*/true, /*strict*/true,
10042 /*now*/true, /*fundef_p*/false,
10043 tf_none);
10046 /* Like above, but complain about non-constant expressions. */
10048 bool
10049 require_constant_expression (tree t)
10051 return potential_constant_expression_1 (t, /*want_rval*/false, /*strict*/true,
10052 /*now*/true, /*fundef_p*/false,
10053 tf_warning_or_error);
10056 /* Like is_constant_expression, but allow const variables that are not allowed
10057 under constexpr rules. */
10059 bool
10060 is_static_init_expression (tree t)
10062 return potential_constant_expression_1 (t, /*want_rval*/false,
10063 /*strict*/false, /*now*/true,
10064 /*fundef_p*/false, tf_none);
10067 /* Returns true if T is a potential constant expression that is not
10068 instantiation-dependent, and therefore a candidate for constant folding even
10069 in a template. */
10071 bool
10072 is_nondependent_constant_expression (tree t)
10074 return (!type_unknown_p (t)
10075 && is_constant_expression (t)
10076 && !instantiation_dependent_expression_p (t));
10079 /* Returns true if T is a potential static initializer expression that is not
10080 instantiation-dependent. */
10082 bool
10083 is_nondependent_static_init_expression (tree t)
10085 return (!type_unknown_p (t)
10086 && is_static_init_expression (t)
10087 && !instantiation_dependent_expression_p (t));
10090 /* True iff FN is an implicitly constexpr function. */
10092 bool
10093 decl_implicit_constexpr_p (tree fn)
10095 if (!(flag_implicit_constexpr
10096 && TREE_CODE (fn) == FUNCTION_DECL
10097 && DECL_DECLARED_CONSTEXPR_P (fn)))
10098 return false;
10100 if (DECL_CLONED_FUNCTION_P (fn))
10101 fn = DECL_CLONED_FUNCTION (fn);
10103 return (DECL_LANG_SPECIFIC (fn)
10104 && DECL_LANG_SPECIFIC (fn)->u.fn.implicit_constexpr);
10107 /* Finalize constexpr processing after parsing. */
10109 void
10110 fini_constexpr (void)
10112 /* The contexpr call and fundef copies tables are no longer needed. */
10113 constexpr_call_table = NULL;
10114 fundef_copies_table = NULL;
10117 #include "gt-cp-constexpr.h"