libstdc++: Remove std::__is_pointer and std::__is_scalar [PR115497]
[official-gcc.git] / gcc / cp / constexpr.cc
blobbd72533491e5964b0735cdeea172ac53aef634bc
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-2024 Free Software Foundation, Inc.
7 This file is part of GCC.
9 GCC is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3, or (at your option)
12 any later version.
14 GCC is distributed in the hope that it will be useful, but
15 WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3. If not see
21 <http://www.gnu.org/licenses/>. */
23 #include "config.h"
24 #include "system.h"
25 #include "coretypes.h"
26 #include "cp-tree.h"
27 #include "varasm.h"
28 #include "c-family/c-objc.h"
29 #include "tree-iterator.h"
30 #include "gimplify.h"
31 #include "builtins.h"
32 #include "tree-inline.h"
33 #include "ubsan.h"
34 #include "timevar.h"
35 #include "fold-const-call.h"
36 #include "stor-layout.h"
37 #include "cgraph.h"
38 #include "opts.h"
39 #include "stringpool.h"
40 #include "attribs.h"
41 #include "fold-const.h"
42 #include "intl.h"
43 #include "toplev.h"
45 static bool verify_constant (tree, bool, bool *, bool *);
46 #define VERIFY_CONSTANT(X) \
47 do { \
48 if (verify_constant ((X), ctx->quiet, non_constant_p, overflow_p)) \
49 return t; \
50 } while (0)
52 static HOST_WIDE_INT find_array_ctor_elt (tree ary, tree dindex,
53 bool insert = false);
54 static int array_index_cmp (tree key, tree index);
56 /* Returns true iff FUN is an instantiation of a constexpr function
57 template or a defaulted constexpr function. */
59 bool
60 is_instantiation_of_constexpr (tree fun)
62 return ((DECL_TEMPLOID_INSTANTIATION (fun)
63 && DECL_DECLARED_CONSTEXPR_P (DECL_TI_TEMPLATE (fun)))
64 || (DECL_DEFAULTED_FN (fun)
65 && DECL_DECLARED_CONSTEXPR_P (fun)));
68 /* Return true if T is a literal type. */
70 bool
71 literal_type_p (tree t)
73 if (SCALAR_TYPE_P (t)
74 || VECTOR_TYPE_P (t)
75 || TYPE_REF_P (t)
76 || (VOID_TYPE_P (t) && cxx_dialect >= cxx14))
77 return true;
78 if (CLASS_TYPE_P (t))
80 t = complete_type (t);
81 gcc_assert (COMPLETE_TYPE_P (t) || errorcount);
82 return CLASSTYPE_LITERAL_P (t);
84 if (TREE_CODE (t) == ARRAY_TYPE)
85 return literal_type_p (strip_array_types (t));
86 return false;
89 /* If DECL is a variable declared `constexpr', require its type
90 be literal. Return error_mark_node if we give an error, the
91 DECL otherwise. */
93 tree
94 ensure_literal_type_for_constexpr_object (tree decl)
96 tree type = TREE_TYPE (decl);
97 if (VAR_P (decl)
98 && (DECL_DECLARED_CONSTEXPR_P (decl)
99 || var_in_constexpr_fn (decl))
100 && !processing_template_decl)
102 tree stype = strip_array_types (type);
103 if (CLASS_TYPE_P (stype) && !COMPLETE_TYPE_P (complete_type (stype)))
104 /* Don't complain here, we'll complain about incompleteness
105 when we try to initialize the variable. */;
106 else if (!literal_type_p (type))
108 if (DECL_DECLARED_CONSTEXPR_P (decl))
110 auto_diagnostic_group d;
111 error_at (DECL_SOURCE_LOCATION (decl),
112 "the type %qT of %<constexpr%> variable %qD "
113 "is not literal", type, decl);
114 explain_non_literal_class (type);
115 decl = error_mark_node;
117 else if (cxx_dialect < cxx23)
119 if (!is_instantiation_of_constexpr (current_function_decl))
121 auto_diagnostic_group d;
122 error_at (DECL_SOURCE_LOCATION (decl),
123 "variable %qD of non-literal type %qT in "
124 "%<constexpr%> function only available with "
125 "%<-std=c++2b%> or %<-std=gnu++2b%>", decl, type);
126 explain_non_literal_class (type);
127 decl = error_mark_node;
129 cp_function_chain->invalid_constexpr = true;
132 else if (DECL_DECLARED_CONSTEXPR_P (decl)
133 && variably_modified_type_p (type, NULL_TREE))
135 error_at (DECL_SOURCE_LOCATION (decl),
136 "%<constexpr%> variable %qD has variably-modified "
137 "type %qT", decl, type);
138 decl = error_mark_node;
141 return decl;
144 /* Issue a diagnostic with text GMSGID for constructs that are invalid in
145 constexpr functions. CONSTEXPR_FUNDEF_P is true if we're checking
146 a constexpr function body; if so, don't report hard errors and issue
147 a pedwarn pre-C++23, or a warning in C++23, if requested by
148 -Winvalid-constexpr. Otherwise, we're not in the context where we are
149 checking if a function can be marked 'constexpr', so give a hard error. */
151 ATTRIBUTE_GCC_DIAG(3,4)
152 static bool
153 constexpr_error (location_t location, bool constexpr_fundef_p,
154 const char *gmsgid, ...)
156 diagnostic_info diagnostic;
157 va_list ap;
158 rich_location richloc (line_table, location);
159 va_start (ap, gmsgid);
160 bool ret;
161 if (!constexpr_fundef_p)
163 /* Report an error that cannot be suppressed. */
164 diagnostic_set_info (&diagnostic, gmsgid, &ap, &richloc, DK_ERROR);
165 ret = diagnostic_report_diagnostic (global_dc, &diagnostic);
167 else if (warn_invalid_constexpr)
169 diagnostic_set_info (&diagnostic, gmsgid, &ap, &richloc,
170 cxx_dialect < cxx23 ? DK_PEDWARN : DK_WARNING);
171 diagnostic.option_index = OPT_Winvalid_constexpr;
172 ret = diagnostic_report_diagnostic (global_dc, &diagnostic);
174 else
175 ret = false;
176 va_end (ap);
177 return ret;
180 struct constexpr_fundef_hasher : ggc_ptr_hash<constexpr_fundef>
182 static hashval_t hash (const constexpr_fundef *);
183 static bool equal (const constexpr_fundef *, const constexpr_fundef *);
186 /* This table holds all constexpr function definitions seen in
187 the current translation unit. */
189 static GTY (()) hash_table<constexpr_fundef_hasher> *constexpr_fundef_table;
191 /* Utility function used for managing the constexpr function table.
192 Return true if the entries pointed to by P and Q are for the
193 same constexpr function. */
195 inline bool
196 constexpr_fundef_hasher::equal (const constexpr_fundef *lhs,
197 const constexpr_fundef *rhs)
199 return lhs->decl == rhs->decl;
202 /* Utility function used for managing the constexpr function table.
203 Return a hash value for the entry pointed to by Q. */
205 inline hashval_t
206 constexpr_fundef_hasher::hash (const constexpr_fundef *fundef)
208 return DECL_UID (fundef->decl);
211 /* Return a previously saved definition of function FUN. */
213 constexpr_fundef *
214 retrieve_constexpr_fundef (tree fun)
216 if (constexpr_fundef_table == NULL)
217 return NULL;
219 constexpr_fundef fundef = { fun, NULL_TREE, NULL_TREE, NULL_TREE };
220 return constexpr_fundef_table->find (&fundef);
223 /* Check whether the parameter and return types of FUN are valid for a
224 constexpr function, and complain if COMPLAIN. */
226 bool
227 is_valid_constexpr_fn (tree fun, bool complain)
229 bool ret = true;
231 if (DECL_INHERITED_CTOR (fun)
232 && TREE_CODE (fun) == TEMPLATE_DECL)
234 ret = false;
235 if (complain)
236 error ("inherited constructor %qD is not %<constexpr%>",
237 DECL_INHERITED_CTOR (fun));
239 else
241 for (tree parm = FUNCTION_FIRST_USER_PARM (fun);
242 parm != NULL_TREE; parm = TREE_CHAIN (parm))
243 if (!literal_type_p (TREE_TYPE (parm)))
245 ret = false;
246 if (complain)
248 auto_diagnostic_group d;
249 if (constexpr_error (input_location, /*constexpr_fundef_p*/true,
250 "invalid type for parameter %d of "
251 "%<constexpr%> function %q+#D",
252 DECL_PARM_INDEX (parm), fun))
253 explain_non_literal_class (TREE_TYPE (parm));
258 if (LAMBDA_TYPE_P (CP_DECL_CONTEXT (fun)) && cxx_dialect < cxx17)
260 ret = false;
261 if (complain)
262 inform (DECL_SOURCE_LOCATION (fun),
263 "lambdas are implicitly %<constexpr%> only in C++17 and later");
265 else if (DECL_DESTRUCTOR_P (fun) && cxx_dialect < cxx20)
267 ret = false;
268 if (complain)
269 error_at (DECL_SOURCE_LOCATION (fun),
270 "%<constexpr%> destructors only available with "
271 "%<-std=c++20%> or %<-std=gnu++20%>");
273 else if (!DECL_CONSTRUCTOR_P (fun) && !DECL_DESTRUCTOR_P (fun))
275 tree rettype = TREE_TYPE (TREE_TYPE (fun));
276 if (!literal_type_p (rettype))
278 ret = false;
279 if (complain)
281 auto_diagnostic_group d;
282 if (constexpr_error (input_location, /*constexpr_fundef_p*/true,
283 "invalid return type %qT of %<constexpr%> "
284 "function %q+D", rettype, fun))
285 explain_non_literal_class (rettype);
289 /* C++14 DR 1684 removed this restriction. */
290 if (cxx_dialect < cxx14
291 && DECL_IOBJ_MEMBER_FUNCTION_P (fun)
292 && !CLASSTYPE_LITERAL_P (DECL_CONTEXT (fun)))
294 ret = false;
295 if (complain)
297 auto_diagnostic_group d;
298 if (pedwarn (DECL_SOURCE_LOCATION (fun), OPT_Wpedantic,
299 "enclosing class of %<constexpr%> non-static"
300 " member function %q+#D is not a literal type",
301 fun))
302 explain_non_literal_class (DECL_CONTEXT (fun));
306 else if (CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fun)))
308 ret = false;
309 if (complain)
310 error ("%q#T has virtual base classes", DECL_CONTEXT (fun));
313 return ret;
316 /* Subroutine of build_data_member_initialization. MEMBER is a COMPONENT_REF
317 for a member of an anonymous aggregate, INIT is the initializer for that
318 member, and VEC_OUTER is the vector of constructor elements for the class
319 whose constructor we are processing. Add the initializer to the vector
320 and return true to indicate success. */
322 static bool
323 build_anon_member_initialization (tree member, tree init,
324 vec<constructor_elt, va_gc> **vec_outer)
326 /* MEMBER presents the relevant fields from the inside out, but we need
327 to build up the initializer from the outside in so that we can reuse
328 previously built CONSTRUCTORs if this is, say, the second field in an
329 anonymous struct. So we use a vec as a stack. */
330 auto_vec<tree, 2> fields;
333 fields.safe_push (TREE_OPERAND (member, 1));
334 member = TREE_OPERAND (member, 0);
336 while (ANON_AGGR_TYPE_P (TREE_TYPE (member))
337 && TREE_CODE (member) == COMPONENT_REF);
339 /* VEC has the constructor elements vector for the context of FIELD.
340 If FIELD is an anonymous aggregate, we will push inside it. */
341 vec<constructor_elt, va_gc> **vec = vec_outer;
342 tree field;
343 while (field = fields.pop(),
344 ANON_AGGR_TYPE_P (TREE_TYPE (field)))
346 tree ctor;
347 /* If there is already an outer constructor entry for the anonymous
348 aggregate FIELD, use it; otherwise, insert one. */
349 if (vec_safe_is_empty (*vec)
350 || (*vec)->last().index != field)
352 ctor = build_constructor (TREE_TYPE (field), NULL);
353 CONSTRUCTOR_APPEND_ELT (*vec, field, ctor);
355 else
356 ctor = (*vec)->last().value;
357 vec = &CONSTRUCTOR_ELTS (ctor);
360 /* Now we're at the innermost field, the one that isn't an anonymous
361 aggregate. Add its initializer to the CONSTRUCTOR and we're done. */
362 gcc_assert (fields.is_empty());
363 CONSTRUCTOR_APPEND_ELT (*vec, field, init);
365 return true;
368 /* Subroutine of build_constexpr_constructor_member_initializers.
369 The expression tree T represents a data member initialization
370 in a (constexpr) constructor definition. Build a pairing of
371 the data member with its initializer, and prepend that pair
372 to the existing initialization pair INITS. */
374 static bool
375 build_data_member_initialization (tree t, vec<constructor_elt, va_gc> **vec)
377 tree member, init;
378 if (TREE_CODE (t) == CLEANUP_POINT_EXPR)
379 t = TREE_OPERAND (t, 0);
380 if (TREE_CODE (t) == EXPR_STMT)
381 t = TREE_OPERAND (t, 0);
382 if (t == error_mark_node)
383 return false;
384 if (TREE_CODE (t) == STATEMENT_LIST)
386 for (tree stmt : tsi_range (t))
387 if (! build_data_member_initialization (stmt, vec))
388 return false;
389 return true;
391 if (TREE_CODE (t) == CLEANUP_STMT)
393 /* We can't see a CLEANUP_STMT in a constructor for a literal class,
394 but we can in a constexpr constructor for a non-literal class. Just
395 ignore it; either all the initialization will be constant, in which
396 case the cleanup can't run, or it can't be constexpr.
397 Still recurse into CLEANUP_BODY. */
398 return build_data_member_initialization (CLEANUP_BODY (t), vec);
400 if (TREE_CODE (t) == CONVERT_EXPR)
401 t = TREE_OPERAND (t, 0);
402 if (TREE_CODE (t) == INIT_EXPR
403 /* vptr initialization shows up as a MODIFY_EXPR. In C++14 we only
404 use what this function builds for cx_check_missing_mem_inits, and
405 assignment in the ctor body doesn't count. */
406 || (cxx_dialect < cxx14 && TREE_CODE (t) == MODIFY_EXPR))
408 member = TREE_OPERAND (t, 0);
409 init = break_out_target_exprs (TREE_OPERAND (t, 1));
411 else if (TREE_CODE (t) == CALL_EXPR)
413 tree fn = get_callee_fndecl (t);
414 if (!fn || !DECL_CONSTRUCTOR_P (fn))
415 /* We're only interested in calls to subobject constructors. */
416 return true;
417 member = CALL_EXPR_ARG (t, 0);
418 /* We don't use build_cplus_new here because it complains about
419 abstract bases. Leaving the call unwrapped means that it has the
420 wrong type, but cxx_eval_constant_expression doesn't care. */
421 init = break_out_target_exprs (t);
423 else if (TREE_CODE (t) == BIND_EXPR)
424 return build_data_member_initialization (BIND_EXPR_BODY (t), vec);
425 else
426 /* Don't add anything else to the CONSTRUCTOR. */
427 return true;
428 if (INDIRECT_REF_P (member))
429 member = TREE_OPERAND (member, 0);
430 if (TREE_CODE (member) == NOP_EXPR)
432 tree op = member;
433 STRIP_NOPS (op);
434 if (TREE_CODE (op) == ADDR_EXPR)
436 gcc_assert (same_type_ignoring_top_level_qualifiers_p
437 (TREE_TYPE (TREE_TYPE (op)),
438 TREE_TYPE (TREE_TYPE (member))));
439 /* Initializing a cv-qualified member; we need to look through
440 the const_cast. */
441 member = op;
443 else if (op == current_class_ptr
444 && (same_type_ignoring_top_level_qualifiers_p
445 (TREE_TYPE (TREE_TYPE (member)),
446 current_class_type)))
447 /* Delegating constructor. */
448 member = op;
449 else
451 /* This is an initializer for an empty base; keep it for now so
452 we can check it in cxx_eval_bare_aggregate. */
453 gcc_assert (is_empty_class (TREE_TYPE (TREE_TYPE (member))));
456 if (TREE_CODE (member) == ADDR_EXPR)
457 member = TREE_OPERAND (member, 0);
458 if (TREE_CODE (member) == COMPONENT_REF)
460 tree aggr = TREE_OPERAND (member, 0);
461 if (TREE_CODE (aggr) == VAR_DECL)
462 /* Initializing a local variable, don't add anything. */
463 return true;
464 if (TREE_CODE (aggr) != COMPONENT_REF)
465 /* Normal member initialization. */
466 member = TREE_OPERAND (member, 1);
467 else if (ANON_AGGR_TYPE_P (TREE_TYPE (aggr)))
468 /* Initializing a member of an anonymous union. */
469 return build_anon_member_initialization (member, init, vec);
470 else
471 /* We're initializing a vtable pointer in a base. Leave it as
472 COMPONENT_REF so we remember the path to get to the vfield. */
473 gcc_assert (TREE_TYPE (member) == vtbl_ptr_type_node);
476 /* Value-initialization can produce multiple initializers for the
477 same field; use the last one. */
478 if (!vec_safe_is_empty (*vec) && (*vec)->last().index == member)
479 (*vec)->last().value = init;
480 else
481 CONSTRUCTOR_APPEND_ELT (*vec, member, init);
482 return true;
485 /* Subroutine of check_constexpr_ctor_body_1 and constexpr_fn_retval.
486 In C++11 mode checks that the TYPE_DECLs in the BIND_EXPR_VARS of a
487 BIND_EXPR conform to 7.1.5/3/4 on typedef and alias declarations. */
489 static bool
490 check_constexpr_bind_expr_vars (tree t)
492 gcc_assert (TREE_CODE (t) == BIND_EXPR);
494 for (tree var = BIND_EXPR_VARS (t); var; var = DECL_CHAIN (var))
495 if (TREE_CODE (var) == TYPE_DECL
496 && DECL_IMPLICIT_TYPEDEF_P (var)
497 && !LAMBDA_TYPE_P (TREE_TYPE (var)))
498 return false;
499 return true;
502 /* Subroutine of check_constexpr_ctor_body. */
504 static bool
505 check_constexpr_ctor_body_1 (tree last, tree list)
507 switch (TREE_CODE (list))
509 case DECL_EXPR:
510 if (TREE_CODE (DECL_EXPR_DECL (list)) == USING_DECL
511 || TREE_CODE (DECL_EXPR_DECL (list)) == TYPE_DECL)
512 return true;
513 return false;
515 case CLEANUP_POINT_EXPR:
516 return check_constexpr_ctor_body (last, TREE_OPERAND (list, 0),
517 /*complain=*/false);
519 case BIND_EXPR:
520 if (!check_constexpr_bind_expr_vars (list)
521 || !check_constexpr_ctor_body (last, BIND_EXPR_BODY (list),
522 /*complain=*/false))
523 return false;
524 return true;
526 case USING_STMT:
527 case STATIC_ASSERT:
528 case DEBUG_BEGIN_STMT:
529 return true;
531 default:
532 return false;
536 /* Make sure that there are no statements after LAST in the constructor
537 body represented by LIST. */
539 bool
540 check_constexpr_ctor_body (tree last, tree list, bool complain)
542 /* C++14 doesn't require a constexpr ctor to have an empty body. */
543 if (cxx_dialect >= cxx14)
544 return true;
546 bool ok = true;
547 if (TREE_CODE (list) == STATEMENT_LIST)
549 tree_stmt_iterator i = tsi_last (list);
550 for (; !tsi_end_p (i); tsi_prev (&i))
552 tree t = tsi_stmt (i);
553 if (t == last)
554 break;
555 if (!check_constexpr_ctor_body_1 (last, t))
557 ok = false;
558 break;
562 else if (list != last
563 && !check_constexpr_ctor_body_1 (last, list))
564 ok = false;
565 if (!ok)
567 if (complain)
568 error ("%<constexpr%> constructor does not have empty body");
569 DECL_DECLARED_CONSTEXPR_P (current_function_decl) = false;
571 return ok;
574 /* V is a vector of constructor elements built up for the base and member
575 initializers of a constructor for TYPE. They need to be in increasing
576 offset order, which they might not be yet if TYPE has a primary base
577 which is not first in the base-clause or a vptr and at least one base
578 all of which are non-primary. */
580 static vec<constructor_elt, va_gc> *
581 sort_constexpr_mem_initializers (tree type, vec<constructor_elt, va_gc> *v)
583 tree pri = CLASSTYPE_PRIMARY_BINFO (type);
584 tree field_type;
585 unsigned i;
586 constructor_elt *ce;
588 if (pri)
589 field_type = BINFO_TYPE (pri);
590 else if (TYPE_CONTAINS_VPTR_P (type))
591 field_type = vtbl_ptr_type_node;
592 else
593 return v;
595 /* Find the element for the primary base or vptr and move it to the
596 beginning of the vec. */
597 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
598 if (TREE_TYPE (ce->index) == field_type)
599 break;
601 if (i > 0 && i < vec_safe_length (v))
603 vec<constructor_elt, va_gc> &vref = *v;
604 constructor_elt elt = vref[i];
605 for (; i > 0; --i)
606 vref[i] = vref[i-1];
607 vref[0] = elt;
610 return v;
613 /* Build compile-time evalable representations of member-initializer list
614 for a constexpr constructor. */
616 static tree
617 build_constexpr_constructor_member_initializers (tree type, tree body)
619 vec<constructor_elt, va_gc> *vec = NULL;
620 bool ok = true;
621 while (true)
622 switch (TREE_CODE (body))
624 case MUST_NOT_THROW_EXPR:
625 case EH_SPEC_BLOCK:
626 body = TREE_OPERAND (body, 0);
627 break;
629 case STATEMENT_LIST:
630 for (tree stmt : tsi_range (body))
632 body = stmt;
633 if (TREE_CODE (body) == BIND_EXPR)
634 break;
636 break;
638 case BIND_EXPR:
639 body = BIND_EXPR_BODY (body);
640 goto found;
642 default:
643 gcc_unreachable ();
645 found:
646 if (TREE_CODE (body) == TRY_BLOCK)
648 body = TREE_OPERAND (body, 0);
649 if (TREE_CODE (body) == BIND_EXPR)
650 body = BIND_EXPR_BODY (body);
652 if (TREE_CODE (body) == CLEANUP_POINT_EXPR)
654 body = TREE_OPERAND (body, 0);
655 if (TREE_CODE (body) == EXPR_STMT)
656 body = TREE_OPERAND (body, 0);
657 if (TREE_CODE (body) == INIT_EXPR
658 && (same_type_ignoring_top_level_qualifiers_p
659 (TREE_TYPE (TREE_OPERAND (body, 0)),
660 current_class_type)))
662 /* Trivial copy. */
663 return TREE_OPERAND (body, 1);
665 ok = build_data_member_initialization (body, &vec);
667 else if (TREE_CODE (body) == STATEMENT_LIST)
669 for (tree stmt : tsi_range (body))
671 ok = build_data_member_initialization (stmt, &vec);
672 if (!ok)
673 break;
676 else if (EXPR_P (body))
677 ok = build_data_member_initialization (body, &vec);
678 else
679 gcc_assert (errorcount > 0);
680 if (ok)
682 if (vec_safe_length (vec) > 0)
684 /* In a delegating constructor, return the target. */
685 constructor_elt *ce = &(*vec)[0];
686 if (ce->index == current_class_ptr)
688 body = ce->value;
689 vec_free (vec);
690 return body;
693 vec = sort_constexpr_mem_initializers (type, vec);
694 return build_constructor (type, vec);
696 else
697 return error_mark_node;
700 /* We have an expression tree T that represents a call, either CALL_EXPR
701 or AGGR_INIT_EXPR. If the call is lexically to a named function,
702 return the _DECL for that function. */
704 static tree
705 get_function_named_in_call (tree t)
707 tree callee = cp_get_callee (t);
708 tree fun = cp_get_fndecl_from_callee (callee, /*fold*/false);
709 return fun ? fun : callee;
712 /* Subroutine of check_constexpr_fundef. BODY is the body of a function
713 declared to be constexpr, or a sub-statement thereof. Returns the
714 return value if suitable, error_mark_node for a statement not allowed in
715 a constexpr function, or NULL_TREE if no return value was found. */
717 tree
718 constexpr_fn_retval (tree body)
720 switch (TREE_CODE (body))
722 case STATEMENT_LIST:
724 tree expr = NULL_TREE;
725 for (tree stmt : tsi_range (body))
727 tree s = constexpr_fn_retval (stmt);
728 if (s == error_mark_node)
729 return error_mark_node;
730 else if (s == NULL_TREE)
731 /* Keep iterating. */;
732 else if (expr)
733 /* Multiple return statements. */
734 return error_mark_node;
735 else
736 expr = s;
738 return expr;
741 case RETURN_EXPR:
742 return break_out_target_exprs (TREE_OPERAND (body, 0));
744 case DECL_EXPR:
746 tree decl = DECL_EXPR_DECL (body);
747 if (TREE_CODE (decl) == USING_DECL
748 /* Accept __func__, __FUNCTION__, and __PRETTY_FUNCTION__. */
749 || DECL_ARTIFICIAL (decl))
750 return NULL_TREE;
751 return error_mark_node;
754 case CLEANUP_POINT_EXPR:
755 return constexpr_fn_retval (TREE_OPERAND (body, 0));
757 case BIND_EXPR:
758 if (!check_constexpr_bind_expr_vars (body))
759 return error_mark_node;
760 return constexpr_fn_retval (BIND_EXPR_BODY (body));
762 case USING_STMT:
763 case DEBUG_BEGIN_STMT:
764 return NULL_TREE;
766 case CALL_EXPR:
768 tree fun = get_function_named_in_call (body);
769 if (fun != NULL_TREE
770 && fndecl_built_in_p (fun, BUILT_IN_UNREACHABLE))
771 return NULL_TREE;
773 /* Fallthru. */
775 default:
776 return error_mark_node;
780 /* Subroutine of check_constexpr_fundef. BODY is the DECL_SAVED_TREE of
781 FUN; do the necessary transformations to turn it into a single expression
782 that we can store in the hash table. */
784 static tree
785 massage_constexpr_body (tree fun, tree body)
787 if (DECL_CONSTRUCTOR_P (fun))
788 body = build_constexpr_constructor_member_initializers
789 (DECL_CONTEXT (fun), body);
790 else if (cxx_dialect < cxx14)
792 if (TREE_CODE (body) == EH_SPEC_BLOCK)
793 body = EH_SPEC_STMTS (body);
794 if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
795 body = TREE_OPERAND (body, 0);
796 body = constexpr_fn_retval (body);
798 return body;
801 /* CTYPE is a type constructed from BODY. Return true if some
802 bases/fields are uninitialized, and complain if COMPLAIN. */
804 static bool
805 cx_check_missing_mem_inits (tree ctype, tree body, bool complain)
807 /* We allow uninitialized bases/fields in C++20. */
808 if (cxx_dialect >= cxx20)
809 return false;
811 unsigned nelts = 0;
813 if (body)
815 if (TREE_CODE (body) != CONSTRUCTOR)
816 return false;
817 nelts = CONSTRUCTOR_NELTS (body);
819 tree field = TYPE_FIELDS (ctype);
821 if (TREE_CODE (ctype) == UNION_TYPE)
823 if (nelts == 0 && next_aggregate_field (field))
825 if (complain)
826 error ("%<constexpr%> constructor for union %qT must "
827 "initialize exactly one non-static data member", ctype);
828 return true;
830 return false;
833 /* Iterate over the CONSTRUCTOR, checking any missing fields don't
834 need an explicit initialization. */
835 bool bad = false;
836 for (unsigned i = 0; i <= nelts; ++i)
838 tree index = NULL_TREE;
839 if (i < nelts)
841 index = CONSTRUCTOR_ELT (body, i)->index;
842 /* Skip base and vtable inits. */
843 if (TREE_CODE (index) != FIELD_DECL
844 || DECL_ARTIFICIAL (index))
845 continue;
848 for (; field != index; field = DECL_CHAIN (field))
850 tree ftype;
851 if (TREE_CODE (field) != FIELD_DECL)
852 continue;
853 if (DECL_UNNAMED_BIT_FIELD (field))
854 continue;
855 if (DECL_ARTIFICIAL (field))
856 continue;
857 if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
859 /* Recurse to check the anonymous aggregate member. */
860 bad |= cx_check_missing_mem_inits
861 (TREE_TYPE (field), NULL_TREE, complain);
862 if (bad && !complain)
863 return true;
864 continue;
866 ftype = TREE_TYPE (field);
867 if (!ftype || !TYPE_P (ftype) || !COMPLETE_TYPE_P (ftype))
868 /* A flexible array can't be intialized here, so don't complain
869 that it isn't. */
870 continue;
871 if (is_empty_field (field))
872 /* An empty field doesn't need an initializer. */
873 continue;
874 ftype = strip_array_types (ftype);
875 if (type_has_constexpr_default_constructor (ftype))
877 /* It's OK to skip a member with a trivial constexpr ctor.
878 A constexpr ctor that isn't trivial should have been
879 added in by now. */
880 gcc_checking_assert (!TYPE_HAS_COMPLEX_DFLT (ftype)
881 || errorcount != 0);
882 continue;
884 if (!complain)
885 return true;
886 auto_diagnostic_group d;
887 error ("member %qD must be initialized by mem-initializer "
888 "in %<constexpr%> constructor", field);
889 inform (DECL_SOURCE_LOCATION (field), "declared here");
890 bad = true;
892 if (field == NULL_TREE)
893 break;
895 if (ANON_AGGR_TYPE_P (TREE_TYPE (index)))
897 /* Check the anonymous aggregate initializer is valid. */
898 bad |= cx_check_missing_mem_inits
899 (TREE_TYPE (index), CONSTRUCTOR_ELT (body, i)->value, complain);
900 if (bad && !complain)
901 return true;
903 field = DECL_CHAIN (field);
906 return bad;
909 /* We are processing the definition of the constexpr function FUN.
910 Check that its body fulfills the apropriate requirements and
911 enter it in the constexpr function definition table. */
913 void
914 maybe_save_constexpr_fundef (tree fun)
916 if (processing_template_decl
917 || cp_function_chain->invalid_constexpr
918 || (DECL_CLONED_FUNCTION_P (fun) && !DECL_DELETING_DESTRUCTOR_P (fun)))
919 return;
921 /* With -fimplicit-constexpr, try to make inlines constexpr. We'll
922 actually set DECL_DECLARED_CONSTEXPR_P below if the checks pass. */
923 bool implicit = false;
924 if (flag_implicit_constexpr)
926 if (DECL_DELETING_DESTRUCTOR_P (fun)
927 && decl_implicit_constexpr_p (DECL_CLONED_FUNCTION (fun)))
928 /* Don't inherit implicit constexpr from the non-deleting
929 destructor. */
930 DECL_DECLARED_CONSTEXPR_P (fun) = false;
932 if (!DECL_DECLARED_CONSTEXPR_P (fun)
933 && DECL_DECLARED_INLINE_P (fun)
934 && !lookup_attribute ("noinline", DECL_ATTRIBUTES (fun)))
935 implicit = true;
938 if (!DECL_DECLARED_CONSTEXPR_P (fun) && !implicit)
939 return;
941 bool complain = !DECL_GENERATED_P (fun) && !implicit;
943 if (!is_valid_constexpr_fn (fun, complain))
944 return;
946 tree massaged = massage_constexpr_body (fun, DECL_SAVED_TREE (fun));
947 if (massaged == NULL_TREE || massaged == error_mark_node)
949 if (!DECL_CONSTRUCTOR_P (fun) && complain)
950 error ("body of %<constexpr%> function %qD not a return-statement",
951 fun);
952 return;
955 bool potential = potential_rvalue_constant_expression (massaged);
956 if (!potential && complain)
957 require_potential_rvalue_constant_expression_fncheck (massaged);
959 if (DECL_CONSTRUCTOR_P (fun) && potential
960 && !DECL_DEFAULTED_FN (fun))
962 if (cx_check_missing_mem_inits (DECL_CONTEXT (fun),
963 massaged, complain))
964 potential = false;
965 else if (cxx_dialect > cxx11)
967 /* What we got from massage_constexpr_body is pretty much just the
968 ctor-initializer, also check the body. */
969 massaged = DECL_SAVED_TREE (fun);
970 potential = potential_rvalue_constant_expression (massaged);
971 if (!potential && complain)
972 require_potential_rvalue_constant_expression_fncheck (massaged);
976 if (!potential && complain
977 /* If -Wno-invalid-constexpr was specified, we haven't complained
978 about non-constant expressions yet. Register the function and
979 complain in explain_invalid_constexpr_fn if the function is
980 called. */
981 && warn_invalid_constexpr != 0)
982 return;
984 if (implicit)
986 if (potential)
988 DECL_DECLARED_CONSTEXPR_P (fun) = true;
989 DECL_LANG_SPECIFIC (fun)->u.fn.implicit_constexpr = true;
990 if (DECL_CONSTRUCTOR_P (fun))
991 TYPE_HAS_CONSTEXPR_CTOR (DECL_CONTEXT (fun)) = true;
993 else
994 /* Don't bother keeping the pre-generic body of unsuitable functions
995 not explicitly declared constexpr. */
996 return;
999 constexpr_fundef entry = {fun, NULL_TREE, NULL_TREE, NULL_TREE};
1000 bool clear_ctx = false;
1001 if (DECL_RESULT (fun) && DECL_CONTEXT (DECL_RESULT (fun)) == NULL_TREE)
1003 clear_ctx = true;
1004 DECL_CONTEXT (DECL_RESULT (fun)) = fun;
1006 tree saved_fn = current_function_decl;
1007 current_function_decl = fun;
1008 entry.body = copy_fn (entry.decl, entry.parms, entry.result);
1009 current_function_decl = saved_fn;
1010 if (clear_ctx)
1011 DECL_CONTEXT (DECL_RESULT (entry.decl)) = NULL_TREE;
1012 if (!potential)
1013 /* For a template instantiation, we want to remember the pre-generic body
1014 for explain_invalid_constexpr_fn, but do tell cxx_eval_call_expression
1015 that it doesn't need to bother trying to expand the function. */
1016 entry.result = error_mark_node;
1018 register_constexpr_fundef (entry);
1021 /* BODY is a validated and massaged definition of a constexpr
1022 function. Register it in the hash table. */
1024 void
1025 register_constexpr_fundef (const constexpr_fundef &value)
1027 /* Create the constexpr function table if necessary. */
1028 if (constexpr_fundef_table == NULL)
1029 constexpr_fundef_table
1030 = hash_table<constexpr_fundef_hasher>::create_ggc (101);
1032 constexpr_fundef **slot = constexpr_fundef_table->find_slot
1033 (const_cast<constexpr_fundef *> (&value), INSERT);
1035 gcc_assert (*slot == NULL);
1036 *slot = ggc_alloc<constexpr_fundef> ();
1037 **slot = value;
1040 /* FUN is a non-constexpr (or, with -Wno-invalid-constexpr, a constexpr
1041 function called in a context that requires a constant expression).
1042 If it comes from a constexpr template, explain why the instantiation
1043 isn't constexpr. Otherwise, explain why the function cannot be used
1044 in a constexpr context. */
1046 void
1047 explain_invalid_constexpr_fn (tree fun)
1049 static hash_set<tree> *diagnosed;
1050 tree body;
1051 /* In C++23, a function marked 'constexpr' may not actually be a constant
1052 expression. We haven't diagnosed the problem yet: -Winvalid-constexpr
1053 wasn't enabled. The function was called, so diagnose why it cannot be
1054 used in a constant expression. */
1055 if (warn_invalid_constexpr == 0 && DECL_DECLARED_CONSTEXPR_P (fun))
1056 /* Go on. */;
1057 /* Only diagnose defaulted functions, lambdas, or instantiations. */
1058 else if (!DECL_DEFAULTED_FN (fun)
1059 && !LAMBDA_TYPE_P (CP_DECL_CONTEXT (fun))
1060 && !is_instantiation_of_constexpr (fun))
1062 inform (DECL_SOURCE_LOCATION (fun), "%qD declared here", fun);
1063 return;
1065 if (diagnosed == NULL)
1066 diagnosed = new hash_set<tree>;
1067 if (diagnosed->add (fun))
1068 /* Already explained. */
1069 return;
1071 iloc_sentinel ils = input_location;
1072 if (!lambda_static_thunk_p (fun))
1074 /* Diagnostics should completely ignore the static thunk, so leave
1075 input_location set to our caller's location. */
1076 input_location = DECL_SOURCE_LOCATION (fun);
1077 inform (input_location,
1078 "%qD is not usable as a %<constexpr%> function because:", fun);
1080 /* First check the declaration. */
1081 if (is_valid_constexpr_fn (fun, true))
1083 /* Then if it's OK, the body. */
1084 if (!DECL_DECLARED_CONSTEXPR_P (fun)
1085 && DECL_DEFAULTED_FN (fun))
1086 explain_implicit_non_constexpr (fun);
1087 else
1089 if (constexpr_fundef *fd = retrieve_constexpr_fundef (fun))
1090 body = fd->body;
1091 else
1092 body = DECL_SAVED_TREE (fun);
1093 body = massage_constexpr_body (fun, body);
1094 require_potential_rvalue_constant_expression (body);
1095 if (DECL_CONSTRUCTOR_P (fun))
1097 cx_check_missing_mem_inits (DECL_CONTEXT (fun), body, true);
1098 if (cxx_dialect > cxx11)
1100 /* Also check the body, not just the ctor-initializer. */
1101 body = DECL_SAVED_TREE (fun);
1102 require_potential_rvalue_constant_expression (body);
1109 /* Objects of this type represent calls to constexpr functions
1110 along with the bindings of parameters to their arguments, for
1111 the purpose of compile time evaluation. */
1113 struct GTY((for_user)) constexpr_call {
1114 /* Description of the constexpr function definition. */
1115 constexpr_fundef *fundef;
1116 /* Parameter bindings environment. A TREE_VEC of arguments. */
1117 tree bindings;
1118 /* Result of the call.
1119 NULL means the call is being evaluated.
1120 error_mark_node means that the evaluation was erroneous;
1121 otherwise, the actuall value of the call. */
1122 tree result;
1123 /* The hash of this call; we remember it here to avoid having to
1124 recalculate it when expanding the hash table. */
1125 hashval_t hash;
1126 /* The value of constexpr_ctx::manifestly_const_eval. */
1127 enum mce_value manifestly_const_eval;
1130 struct constexpr_call_hasher : ggc_ptr_hash<constexpr_call>
1132 static hashval_t hash (constexpr_call *);
1133 static bool equal (constexpr_call *, constexpr_call *);
1136 enum constexpr_switch_state {
1137 /* Used when processing a switch for the first time by cxx_eval_switch_expr
1138 and default: label for that switch has not been seen yet. */
1139 css_default_not_seen,
1140 /* Used when processing a switch for the first time by cxx_eval_switch_expr
1141 and default: label for that switch has been seen already. */
1142 css_default_seen,
1143 /* Used when processing a switch for the second time by
1144 cxx_eval_switch_expr, where default: label should match. */
1145 css_default_processing
1148 /* The constexpr expansion context part which needs one instance per
1149 cxx_eval_outermost_constant_expr invocation. VALUES is a map of values of
1150 variables initialized within the expression. */
1152 class constexpr_global_ctx {
1153 /* Values for any temporaries or local variables within the
1154 constant-expression. Objects outside their lifetime have
1155 value 'void_node'. */
1156 hash_map<tree,tree> values;
1157 public:
1158 /* Number of cxx_eval_constant_expression calls (except skipped ones,
1159 on simple constants or location wrappers) encountered during current
1160 cxx_eval_outermost_constant_expr call. */
1161 HOST_WIDE_INT constexpr_ops_count;
1162 /* Heap VAR_DECLs created during the evaluation of the outermost constant
1163 expression. */
1164 auto_vec<tree, 16> heap_vars;
1165 /* Cleanups that need to be evaluated at the end of CLEANUP_POINT_EXPR. */
1166 vec<tree> *cleanups;
1167 /* If non-null, only allow modification of existing values of the variables
1168 in this set. Set by modifiable_tracker, below. */
1169 hash_set<tree> *modifiable;
1170 /* Number of heap VAR_DECL deallocations. */
1171 unsigned heap_dealloc_count;
1172 /* Constructor. */
1173 constexpr_global_ctx ()
1174 : constexpr_ops_count (0), cleanups (NULL), modifiable (nullptr),
1175 heap_dealloc_count (0) {}
1177 bool is_outside_lifetime (tree t)
1179 if (tree *p = values.get (t))
1180 if (*p == void_node)
1181 return true;
1182 return false;
1184 tree get_value (tree t)
1186 if (tree *p = values.get (t))
1187 if (*p != void_node)
1188 return *p;
1189 return NULL_TREE;
1191 tree *get_value_ptr (tree t, bool initializing)
1193 if (modifiable && !modifiable->contains (t))
1194 return nullptr;
1195 if (tree *p = values.get (t))
1197 if (*p != void_node)
1198 return p;
1199 else if (initializing)
1201 *p = NULL_TREE;
1202 return p;
1205 return nullptr;
1207 void put_value (tree t, tree v)
1209 bool already_in_map = values.put (t, v);
1210 if (!already_in_map && modifiable)
1211 modifiable->add (t);
1213 void destroy_value (tree t)
1215 if (TREE_CODE (t) == VAR_DECL
1216 || TREE_CODE (t) == PARM_DECL
1217 || TREE_CODE (t) == RESULT_DECL)
1218 values.put (t, void_node);
1219 else
1220 values.remove (t);
1222 void clear_value (tree t)
1224 values.remove (t);
1228 /* Helper class for constexpr_global_ctx. In some cases we want to avoid
1229 side-effects from evaluation of a particular subexpression of a
1230 constant-expression. In such cases we use modifiable_tracker to prevent
1231 modification of variables created outside of that subexpression.
1233 ??? We could change the hash_set to a hash_map, allow and track external
1234 modifications, and roll them back in the destructor. It's not clear to me
1235 that this would be worthwhile. */
1237 class modifiable_tracker
1239 hash_set<tree> set;
1240 constexpr_global_ctx *global;
1241 public:
1242 modifiable_tracker (constexpr_global_ctx *g): global(g)
1244 global->modifiable = &set;
1246 ~modifiable_tracker ()
1248 for (tree t: set)
1249 global->clear_value (t);
1250 global->modifiable = nullptr;
1254 /* The constexpr expansion context. CALL is the current function
1255 expansion, CTOR is the current aggregate initializer, OBJECT is the
1256 object being initialized by CTOR, either a VAR_DECL or a _REF. */
1258 struct constexpr_ctx {
1259 /* The part of the context that needs to be unique to the whole
1260 cxx_eval_outermost_constant_expr invocation. */
1261 constexpr_global_ctx *global;
1262 /* The innermost call we're evaluating. */
1263 constexpr_call *call;
1264 /* SAVE_EXPRs and TARGET_EXPR_SLOT vars of TARGET_EXPRs that we've seen
1265 within the current LOOP_EXPR. NULL if we aren't inside a loop. */
1266 vec<tree> *save_exprs;
1267 /* The CONSTRUCTOR we're currently building up for an aggregate
1268 initializer. */
1269 tree ctor;
1270 /* The object we're building the CONSTRUCTOR for. */
1271 tree object;
1272 /* If inside SWITCH_EXPR. */
1273 constexpr_switch_state *css_state;
1274 /* The aggregate initialization context inside which this one is nested. This
1275 is used by lookup_placeholder to resolve PLACEHOLDER_EXPRs. */
1276 const constexpr_ctx *parent;
1278 /* Whether we should error on a non-constant expression or fail quietly.
1279 This flag needs to be here, but some of the others could move to global
1280 if they get larger than a word. */
1281 bool quiet;
1282 /* Whether we are strictly conforming to constant expression rules or
1283 trying harder to get a constant value. */
1284 bool strict;
1285 /* Whether __builtin_is_constant_evaluated () should be true. */
1286 mce_value manifestly_const_eval;
1289 /* Remove T from the global values map, checking for attempts to destroy
1290 a value that has already finished its lifetime. */
1292 static void
1293 destroy_value_checked (const constexpr_ctx* ctx, tree t, bool *non_constant_p)
1295 if (t == error_mark_node || TREE_TYPE (t) == error_mark_node)
1296 return;
1298 /* Don't error again here if we've already reported a problem. */
1299 if (!*non_constant_p
1300 && DECL_P (t)
1301 /* Non-trivial destructors have their lifetimes ended explicitly
1302 with a clobber, so don't worry about it here. */
1303 && (!TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (t))
1304 /* ...except parameters are remapped in cxx_eval_call_expression,
1305 and the destructor call during cleanup won't be able to tell that
1306 this value has already been destroyed, so complain now. This is
1307 not quite unobservable, but is extremely unlikely to crop up in
1308 practice; see g++.dg/cpp2a/constexpr-lifetime2.C. */
1309 || TREE_CODE (t) == PARM_DECL)
1310 && ctx->global->is_outside_lifetime (t))
1312 if (!ctx->quiet)
1314 auto_diagnostic_group d;
1315 error ("destroying %qE outside its lifetime", t);
1316 inform (DECL_SOURCE_LOCATION (t), "declared here");
1318 *non_constant_p = true;
1320 ctx->global->destroy_value (t);
1323 /* This internal flag controls whether we should avoid doing anything during
1324 constexpr evaluation that would cause extra DECL_UID generation, such as
1325 template instantiation and function body copying. */
1327 static bool uid_sensitive_constexpr_evaluation_value;
1329 /* An internal counter that keeps track of the number of times
1330 uid_sensitive_constexpr_evaluation_p returned true. */
1332 static unsigned uid_sensitive_constexpr_evaluation_true_counter;
1334 /* The accessor for uid_sensitive_constexpr_evaluation_value which also
1335 increments the corresponding counter. */
1337 static bool
1338 uid_sensitive_constexpr_evaluation_p ()
1340 if (uid_sensitive_constexpr_evaluation_value)
1342 ++uid_sensitive_constexpr_evaluation_true_counter;
1343 return true;
1345 else
1346 return false;
1349 /* The default constructor for uid_sensitive_constexpr_evaluation_sentinel
1350 enables the internal flag for uid_sensitive_constexpr_evaluation_p
1351 during the lifetime of the sentinel object. Upon its destruction, the
1352 previous value of uid_sensitive_constexpr_evaluation_p is restored. */
1354 uid_sensitive_constexpr_evaluation_sentinel
1355 ::uid_sensitive_constexpr_evaluation_sentinel ()
1356 : ovr (uid_sensitive_constexpr_evaluation_value, true)
1360 /* The default constructor for uid_sensitive_constexpr_evaluation_checker
1361 records the current number of times that uid_sensitive_constexpr_evaluation_p
1362 has been called and returned true. */
1364 uid_sensitive_constexpr_evaluation_checker
1365 ::uid_sensitive_constexpr_evaluation_checker ()
1366 : saved_counter (uid_sensitive_constexpr_evaluation_true_counter)
1370 /* Returns true iff uid_sensitive_constexpr_evaluation_p is true, and
1371 some constexpr evaluation was restricted due to u_s_c_e_p being called
1372 and returning true during the lifetime of this checker object. */
1374 bool
1375 uid_sensitive_constexpr_evaluation_checker::evaluation_restricted_p () const
1377 return (uid_sensitive_constexpr_evaluation_value
1378 && saved_counter != uid_sensitive_constexpr_evaluation_true_counter);
1382 /* A table of all constexpr calls that have been evaluated by the
1383 compiler in this translation unit. */
1385 static GTY (()) hash_table<constexpr_call_hasher> *constexpr_call_table;
1387 /* Compute a hash value for a constexpr call representation. */
1389 inline hashval_t
1390 constexpr_call_hasher::hash (constexpr_call *info)
1392 return info->hash;
1395 /* Return true if the objects pointed to by P and Q represent calls
1396 to the same constexpr function with the same arguments.
1397 Otherwise, return false. */
1399 bool
1400 constexpr_call_hasher::equal (constexpr_call *lhs, constexpr_call *rhs)
1402 if (lhs == rhs)
1403 return true;
1404 if (lhs->hash != rhs->hash)
1405 return false;
1406 if (lhs->manifestly_const_eval != rhs->manifestly_const_eval)
1407 return false;
1408 if (!constexpr_fundef_hasher::equal (lhs->fundef, rhs->fundef))
1409 return false;
1410 return cp_tree_equal (lhs->bindings, rhs->bindings);
1413 /* Initialize the constexpr call table, if needed. */
1415 static void
1416 maybe_initialize_constexpr_call_table (void)
1418 if (constexpr_call_table == NULL)
1419 constexpr_call_table = hash_table<constexpr_call_hasher>::create_ggc (101);
1422 /* During constexpr CALL_EXPR evaluation, to avoid issues with sharing when
1423 a function happens to get called recursively, we unshare the callee
1424 function's body and evaluate this unshared copy instead of evaluating the
1425 original body.
1427 FUNDEF_COPIES_TABLE is a per-function freelist of these unshared function
1428 copies. The underlying data structure of FUNDEF_COPIES_TABLE is a hash_map
1429 that's keyed off of the original FUNCTION_DECL and whose value is a
1430 TREE_LIST of this function's unused copies awaiting reuse.
1432 This is not GC-deletable to avoid GC affecting UID generation. */
1434 static GTY(()) decl_tree_map *fundef_copies_table;
1436 /* Reuse a copy or create a new unshared copy of the function FUN.
1437 Return this copy. We use a TREE_LIST whose PURPOSE is body, VALUE
1438 is parms, TYPE is result. */
1440 static tree
1441 get_fundef_copy (constexpr_fundef *fundef)
1443 tree copy;
1444 bool existed;
1445 tree *slot = &(hash_map_safe_get_or_insert<hm_ggc>
1446 (fundef_copies_table, fundef->decl, &existed, 127));
1448 if (!existed)
1450 /* There is no cached function available, or in use. We can use
1451 the function directly. That the slot is now created records
1452 that this function is now in use. */
1453 copy = build_tree_list (fundef->body, fundef->parms);
1454 TREE_TYPE (copy) = fundef->result;
1456 else if (*slot == NULL_TREE)
1458 if (uid_sensitive_constexpr_evaluation_p ())
1459 return NULL_TREE;
1461 /* We've already used the function itself, so make a copy. */
1462 copy = build_tree_list (NULL, NULL);
1463 tree saved_body = DECL_SAVED_TREE (fundef->decl);
1464 tree saved_parms = DECL_ARGUMENTS (fundef->decl);
1465 tree saved_result = DECL_RESULT (fundef->decl);
1466 tree saved_fn = current_function_decl;
1467 DECL_SAVED_TREE (fundef->decl) = fundef->body;
1468 DECL_ARGUMENTS (fundef->decl) = fundef->parms;
1469 DECL_RESULT (fundef->decl) = fundef->result;
1470 current_function_decl = fundef->decl;
1471 TREE_PURPOSE (copy) = copy_fn (fundef->decl, TREE_VALUE (copy),
1472 TREE_TYPE (copy));
1473 current_function_decl = saved_fn;
1474 DECL_RESULT (fundef->decl) = saved_result;
1475 DECL_ARGUMENTS (fundef->decl) = saved_parms;
1476 DECL_SAVED_TREE (fundef->decl) = saved_body;
1478 else
1480 /* We have a cached function available. */
1481 copy = *slot;
1482 *slot = TREE_CHAIN (copy);
1485 return copy;
1488 /* Save the copy COPY of function FUN for later reuse by
1489 get_fundef_copy(). By construction, there will always be an entry
1490 to find. */
1492 static void
1493 save_fundef_copy (tree fun, tree copy)
1495 tree *slot = fundef_copies_table->get (fun);
1496 TREE_CHAIN (copy) = *slot;
1497 *slot = copy;
1500 /* Whether our evaluation wants a prvalue (e.g. CONSTRUCTOR or _CST),
1501 a glvalue (e.g. VAR_DECL or _REF), or nothing. */
1503 enum value_cat {
1504 vc_prvalue = 0,
1505 vc_glvalue = 1,
1506 vc_discard = 2
1509 static tree cxx_eval_constant_expression (const constexpr_ctx *, tree,
1510 value_cat, bool *, bool *, tree * = NULL);
1511 static tree cxx_eval_bare_aggregate (const constexpr_ctx *, tree,
1512 value_cat, bool *, bool *);
1513 static tree cxx_fold_indirect_ref (const constexpr_ctx *, location_t, tree, tree,
1514 bool * = NULL);
1515 static tree find_heap_var_refs (tree *, int *, void *);
1517 /* Attempt to evaluate T which represents a call to a builtin function.
1518 We assume here that all builtin functions evaluate to scalar types
1519 represented by _CST nodes. */
1521 static tree
1522 cxx_eval_builtin_function_call (const constexpr_ctx *ctx, tree t, tree fun,
1523 value_cat lval,
1524 bool *non_constant_p, bool *overflow_p)
1526 const int nargs = call_expr_nargs (t);
1527 tree *args = (tree *) alloca (nargs * sizeof (tree));
1528 tree new_call;
1529 int i;
1531 /* Don't fold __builtin_constant_p within a constexpr function. */
1532 bool bi_const_p = DECL_IS_BUILTIN_CONSTANT_P (fun);
1534 /* If we aren't requiring a constant expression, defer __builtin_constant_p
1535 in a constexpr function until we have values for the parameters. */
1536 if (bi_const_p
1537 && ctx->manifestly_const_eval != mce_true
1538 && current_function_decl
1539 && DECL_DECLARED_CONSTEXPR_P (current_function_decl))
1541 *non_constant_p = true;
1542 return t;
1545 /* For __builtin_is_constant_evaluated, defer it if not
1546 ctx->manifestly_const_eval (as sometimes we try to constant evaluate
1547 without manifestly_const_eval even expressions or parts thereof which
1548 will later be manifestly const_eval evaluated), otherwise fold it to
1549 true. */
1550 if (fndecl_built_in_p (fun, CP_BUILT_IN_IS_CONSTANT_EVALUATED,
1551 BUILT_IN_FRONTEND))
1553 if (ctx->manifestly_const_eval == mce_unknown)
1555 *non_constant_p = true;
1556 return t;
1558 return constant_boolean_node (ctx->manifestly_const_eval == mce_true,
1559 boolean_type_node);
1562 if (fndecl_built_in_p (fun, CP_BUILT_IN_SOURCE_LOCATION, BUILT_IN_FRONTEND))
1564 temp_override<tree> ovr (current_function_decl);
1565 if (ctx->call && ctx->call->fundef)
1566 current_function_decl = ctx->call->fundef->decl;
1567 return fold_builtin_source_location (t);
1570 int strops = 0;
1571 int strret = 0;
1572 if (fndecl_built_in_p (fun, BUILT_IN_NORMAL))
1573 switch (DECL_FUNCTION_CODE (fun))
1575 case BUILT_IN_STRLEN:
1576 case BUILT_IN_STRNLEN:
1577 strops = 1;
1578 break;
1579 case BUILT_IN_MEMCHR:
1580 case BUILT_IN_STRCHR:
1581 case BUILT_IN_STRRCHR:
1582 strops = 1;
1583 strret = 1;
1584 break;
1585 case BUILT_IN_MEMCMP:
1586 case BUILT_IN_STRCMP:
1587 strops = 2;
1588 break;
1589 case BUILT_IN_STRSTR:
1590 strops = 2;
1591 strret = 1;
1592 break;
1593 case BUILT_IN_ASAN_POINTER_COMPARE:
1594 case BUILT_IN_ASAN_POINTER_SUBTRACT:
1595 /* These builtins shall be ignored during constant expression
1596 evaluation. */
1597 return void_node;
1598 case BUILT_IN_UNREACHABLE:
1599 case BUILT_IN_TRAP:
1600 if (!*non_constant_p && !ctx->quiet)
1602 /* Do not allow__builtin_unreachable in constexpr function.
1603 The __builtin_unreachable call with BUILTINS_LOCATION
1604 comes from cp_maybe_instrument_return. */
1605 if (EXPR_LOCATION (t) == BUILTINS_LOCATION)
1606 error ("%<constexpr%> call flows off the end of the function");
1607 else
1608 error ("%q+E is not a constant expression", t);
1610 *non_constant_p = true;
1611 return t;
1612 default:
1613 break;
1616 /* Be permissive for arguments to built-ins; __builtin_constant_p should
1617 return constant false for a non-constant argument. */
1618 constexpr_ctx new_ctx = *ctx;
1619 new_ctx.quiet = true;
1620 for (i = 0; i < nargs; ++i)
1622 tree arg = CALL_EXPR_ARG (t, i);
1623 tree oarg = arg;
1625 /* To handle string built-ins we need to pass ADDR_EXPR<STRING_CST> since
1626 expand_builtin doesn't know how to look in the values table. */
1627 bool strop = i < strops;
1628 if (strop)
1630 STRIP_NOPS (arg);
1631 if (TREE_CODE (arg) == ADDR_EXPR)
1632 arg = TREE_OPERAND (arg, 0);
1633 else
1634 strop = false;
1637 /* If builtin_valid_in_constant_expr_p is true,
1638 potential_constant_expression_1 has not recursed into the arguments
1639 of the builtin, verify it here. */
1640 if (!builtin_valid_in_constant_expr_p (fun)
1641 || potential_constant_expression (arg))
1643 bool dummy1 = false, dummy2 = false;
1644 arg = cxx_eval_constant_expression (&new_ctx, arg, vc_prvalue,
1645 &dummy1, &dummy2);
1648 if (bi_const_p)
1649 /* For __builtin_constant_p, fold all expressions with constant values
1650 even if they aren't C++ constant-expressions. */
1651 arg = cp_fold_rvalue (arg);
1652 else if (strop)
1654 if (TREE_CODE (arg) == CONSTRUCTOR)
1655 arg = braced_lists_to_strings (TREE_TYPE (arg), arg);
1656 if (TREE_CODE (arg) == STRING_CST)
1657 arg = build_address (arg);
1658 else
1659 arg = oarg;
1662 args[i] = arg;
1665 bool save_ffbcp = force_folding_builtin_constant_p;
1666 force_folding_builtin_constant_p |= ctx->manifestly_const_eval == mce_true;
1667 tree save_cur_fn = current_function_decl;
1668 /* Return name of ctx->call->fundef->decl for __builtin_FUNCTION (). */
1669 if (fndecl_built_in_p (fun, BUILT_IN_FUNCTION)
1670 && ctx->call
1671 && ctx->call->fundef)
1672 current_function_decl = ctx->call->fundef->decl;
1673 if (fndecl_built_in_p (fun,
1674 CP_BUILT_IN_IS_POINTER_INTERCONVERTIBLE_WITH_CLASS,
1675 BUILT_IN_FRONTEND))
1677 location_t loc = EXPR_LOCATION (t);
1678 if (nargs >= 1)
1679 VERIFY_CONSTANT (args[0]);
1680 new_call
1681 = fold_builtin_is_pointer_inverconvertible_with_class (loc, nargs,
1682 args);
1684 else if (fndecl_built_in_p (fun,
1685 CP_BUILT_IN_IS_CORRESPONDING_MEMBER,
1686 BUILT_IN_FRONTEND))
1688 location_t loc = EXPR_LOCATION (t);
1689 if (nargs >= 2)
1691 VERIFY_CONSTANT (args[0]);
1692 VERIFY_CONSTANT (args[1]);
1694 new_call = fold_builtin_is_corresponding_member (loc, nargs, args);
1696 else
1697 new_call = fold_builtin_call_array (EXPR_LOCATION (t), TREE_TYPE (t),
1698 CALL_EXPR_FN (t), nargs, args);
1699 current_function_decl = save_cur_fn;
1700 force_folding_builtin_constant_p = save_ffbcp;
1701 if (new_call == NULL)
1703 if (!*non_constant_p && !ctx->quiet)
1705 new_call = build_call_array_loc (EXPR_LOCATION (t), TREE_TYPE (t),
1706 CALL_EXPR_FN (t), nargs, args);
1707 error ("%q+E is not a constant expression", new_call);
1709 *non_constant_p = true;
1710 return t;
1713 if (!potential_constant_expression (new_call))
1715 if (!*non_constant_p && !ctx->quiet)
1716 error ("%q+E is not a constant expression", new_call);
1717 *non_constant_p = true;
1718 return t;
1721 if (strret)
1723 /* memchr returns a pointer into the first argument, but we replaced the
1724 argument above with a STRING_CST; put it back it now. */
1725 tree op = CALL_EXPR_ARG (t, strret-1);
1726 STRIP_NOPS (new_call);
1727 if (TREE_CODE (new_call) == POINTER_PLUS_EXPR)
1728 TREE_OPERAND (new_call, 0) = op;
1729 else if (TREE_CODE (new_call) == ADDR_EXPR)
1730 new_call = op;
1733 return cxx_eval_constant_expression (&new_ctx, new_call, lval,
1734 non_constant_p, overflow_p);
1737 /* TEMP is the constant value of a temporary object of type TYPE. Adjust
1738 the type of the value to match. */
1740 static tree
1741 adjust_temp_type (tree type, tree temp)
1743 if (same_type_p (TREE_TYPE (temp), type))
1744 return temp;
1745 /* Avoid wrapping an aggregate value in a NOP_EXPR. */
1746 if (TREE_CODE (temp) == CONSTRUCTOR)
1748 /* build_constructor wouldn't retain various CONSTRUCTOR flags. */
1749 tree t = copy_node (temp);
1750 TREE_TYPE (t) = type;
1751 return t;
1753 if (TREE_CODE (temp) == EMPTY_CLASS_EXPR)
1754 return build0 (EMPTY_CLASS_EXPR, type);
1755 gcc_assert (scalarish_type_p (type));
1756 /* Now we know we're dealing with a scalar, and a prvalue of non-class
1757 type is cv-unqualified. */
1758 return cp_fold_convert (cv_unqualified (type), temp);
1761 /* If T is a CONSTRUCTOR, return an unshared copy of T and any
1762 sub-CONSTRUCTORs. Otherwise return T.
1764 We use this whenever we initialize an object as a whole, whether it's a
1765 parameter, a local variable, or a subobject, so that subsequent
1766 modifications don't affect other places where it was used. */
1768 tree
1769 unshare_constructor (tree t MEM_STAT_DECL)
1771 if (!t || TREE_CODE (t) != CONSTRUCTOR)
1772 return t;
1773 auto_vec <tree*, 4> ptrs;
1774 ptrs.safe_push (&t);
1775 while (!ptrs.is_empty ())
1777 tree *p = ptrs.pop ();
1778 tree n = copy_node (*p PASS_MEM_STAT);
1779 CONSTRUCTOR_ELTS (n) = vec_safe_copy (CONSTRUCTOR_ELTS (*p) PASS_MEM_STAT);
1780 *p = n;
1781 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (n);
1782 constructor_elt *ce;
1783 for (HOST_WIDE_INT i = 0; vec_safe_iterate (v, i, &ce); ++i)
1784 if (ce->value && TREE_CODE (ce->value) == CONSTRUCTOR)
1785 ptrs.safe_push (&ce->value);
1787 return t;
1790 /* If T is a CONSTRUCTOR, ggc_free T and any sub-CONSTRUCTORs. */
1792 static void
1793 free_constructor (tree t)
1795 if (!t || TREE_CODE (t) != CONSTRUCTOR)
1796 return;
1797 releasing_vec ctors;
1798 vec_safe_push (ctors, t);
1799 while (!ctors->is_empty ())
1801 tree c = ctors->pop ();
1802 if (vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (c))
1804 constructor_elt *ce;
1805 for (HOST_WIDE_INT i = 0; vec_safe_iterate (elts, i, &ce); ++i)
1806 if (ce->value && TREE_CODE (ce->value) == CONSTRUCTOR)
1807 vec_safe_push (ctors, ce->value);
1808 ggc_free (elts);
1810 ggc_free (c);
1814 /* Helper function of cxx_bind_parameters_in_call. Return non-NULL
1815 if *TP is address of a static variable (or part of it) currently being
1816 constructed or of a heap artificial variable. */
1818 static tree
1819 addr_of_non_const_var (tree *tp, int *walk_subtrees, void *data)
1821 if (TREE_CODE (*tp) == ADDR_EXPR)
1822 if (tree var = get_base_address (TREE_OPERAND (*tp, 0)))
1823 if (VAR_P (var) && TREE_STATIC (var))
1825 if (DECL_NAME (var) == heap_uninit_identifier
1826 || DECL_NAME (var) == heap_identifier
1827 || DECL_NAME (var) == heap_vec_uninit_identifier
1828 || DECL_NAME (var) == heap_vec_identifier)
1829 return var;
1831 constexpr_global_ctx *global = (constexpr_global_ctx *) data;
1832 if (global->get_value (var))
1833 return var;
1835 if (TYPE_P (*tp))
1836 *walk_subtrees = false;
1837 return NULL_TREE;
1840 /* Subroutine of cxx_eval_call_expression.
1841 We are processing a call expression (either CALL_EXPR or
1842 AGGR_INIT_EXPR) in the context of CTX. Evaluate
1843 all arguments and bind their values to correspondings
1844 parameters, making up the NEW_CALL context. */
1846 static tree
1847 cxx_bind_parameters_in_call (const constexpr_ctx *ctx, tree t, tree fun,
1848 bool *non_constant_p, bool *overflow_p,
1849 bool *non_constant_args)
1851 const int nargs = call_expr_nargs (t);
1852 tree parms = DECL_ARGUMENTS (fun);
1853 int i;
1854 /* We don't record ellipsis args below. */
1855 int nparms = list_length (parms);
1856 int nbinds = nargs < nparms ? nargs : nparms;
1857 tree binds = make_tree_vec (nbinds);
1858 for (i = 0; i < nargs; ++i)
1860 tree x, arg;
1861 tree type = parms ? TREE_TYPE (parms) : void_type_node;
1862 if (parms && DECL_BY_REFERENCE (parms))
1863 type = TREE_TYPE (type);
1864 x = get_nth_callarg (t, i);
1865 /* For member function, the first argument is a pointer to the implied
1866 object. For a constructor, it might still be a dummy object, in
1867 which case we get the real argument from ctx. */
1868 if (i == 0 && DECL_CONSTRUCTOR_P (fun)
1869 && is_dummy_object (x))
1871 x = ctx->object;
1872 x = build_address (x);
1874 if (TREE_ADDRESSABLE (type))
1876 /* Undo convert_for_arg_passing work here. */
1877 x = convert_from_reference (x);
1878 arg = cxx_eval_constant_expression (ctx, x, vc_glvalue,
1879 non_constant_p, overflow_p);
1881 else
1882 /* Normally we would strip a TARGET_EXPR in an initialization context
1883 such as this, but here we do the elision differently: we keep the
1884 TARGET_EXPR, and use its CONSTRUCTOR as the value of the parm. */
1885 arg = cxx_eval_constant_expression (ctx, x, vc_prvalue,
1886 non_constant_p, overflow_p);
1887 /* Check we aren't dereferencing a null pointer when calling a non-static
1888 member function, which is undefined behaviour. */
1889 if (i == 0 && DECL_OBJECT_MEMBER_FUNCTION_P (fun)
1890 && integer_zerop (arg)
1891 /* But ignore calls from within compiler-generated code, to handle
1892 cases like lambda function pointer conversion operator thunks
1893 which pass NULL as the 'this' pointer. */
1894 && !(TREE_CODE (t) == CALL_EXPR && CALL_FROM_THUNK_P (t)))
1896 if (!ctx->quiet)
1897 error_at (cp_expr_loc_or_input_loc (x),
1898 "dereferencing a null pointer");
1899 *non_constant_p = true;
1901 /* Don't VERIFY_CONSTANT here. */
1902 if (*non_constant_p && ctx->quiet)
1903 break;
1904 /* Just discard ellipsis args after checking their constantitude. */
1905 if (!parms)
1906 continue;
1908 if (!*non_constant_p)
1910 /* Make sure the binding has the same type as the parm. But
1911 only for constant args. */
1912 if (TREE_ADDRESSABLE (type))
1914 if (!same_type_p (type, TREE_TYPE (arg)))
1916 arg = build_fold_addr_expr (arg);
1917 arg = cp_fold_convert (build_reference_type (type), arg);
1918 arg = convert_from_reference (arg);
1921 else if (!TYPE_REF_P (type))
1922 arg = adjust_temp_type (type, arg);
1923 if (!TREE_CONSTANT (arg))
1924 *non_constant_args = true;
1925 else if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
1926 /* The destructor needs to see any modifications the callee makes
1927 to the argument. */
1928 *non_constant_args = true;
1929 /* If arg is or contains address of a heap artificial variable or
1930 of a static variable being constructed, avoid caching the
1931 function call, as those variables might be modified by the
1932 function, or might be modified by the callers in between
1933 the cached function and just read by the function. */
1934 else if (!*non_constant_args
1935 && cp_walk_tree (&arg, addr_of_non_const_var, ctx->global,
1936 NULL))
1937 *non_constant_args = true;
1939 /* For virtual calls, adjust the this argument, so that it is
1940 the object on which the method is called, rather than
1941 one of its bases. */
1942 if (i == 0 && DECL_VIRTUAL_P (fun))
1944 tree addr = arg;
1945 STRIP_NOPS (addr);
1946 if (TREE_CODE (addr) == ADDR_EXPR)
1948 tree obj = TREE_OPERAND (addr, 0);
1949 while (TREE_CODE (obj) == COMPONENT_REF
1950 && DECL_FIELD_IS_BASE (TREE_OPERAND (obj, 1))
1951 && !same_type_ignoring_top_level_qualifiers_p
1952 (TREE_TYPE (obj), DECL_CONTEXT (fun)))
1953 obj = TREE_OPERAND (obj, 0);
1954 if (obj != TREE_OPERAND (addr, 0))
1955 arg = build_fold_addr_expr_with_type (obj,
1956 TREE_TYPE (arg));
1959 TREE_VEC_ELT (binds, i) = arg;
1961 parms = TREE_CHAIN (parms);
1964 return binds;
1967 /* Variables and functions to manage constexpr call expansion context.
1968 These do not need to be marked for PCH or GC. */
1970 /* FIXME remember and print actual constant arguments. */
1971 static vec<tree> call_stack;
1972 static int call_stack_tick;
1973 static int last_cx_error_tick;
1975 static int
1976 push_cx_call_context (tree call)
1978 ++call_stack_tick;
1979 if (!EXPR_HAS_LOCATION (call))
1980 SET_EXPR_LOCATION (call, input_location);
1981 call_stack.safe_push (call);
1982 int len = call_stack.length ();
1983 if (len > max_constexpr_depth)
1984 return false;
1985 return len;
1988 static void
1989 pop_cx_call_context (void)
1991 ++call_stack_tick;
1992 call_stack.pop ();
1995 vec<tree>
1996 cx_error_context (void)
1998 vec<tree> r = vNULL;
1999 if (call_stack_tick != last_cx_error_tick
2000 && !call_stack.is_empty ())
2001 r = call_stack;
2002 last_cx_error_tick = call_stack_tick;
2003 return r;
2006 /* E is an operand of a failed assertion, fold it either with or without
2007 constexpr context. */
2009 static tree
2010 fold_operand (tree e, const constexpr_ctx *ctx)
2012 if (ctx)
2014 bool new_non_constant_p = false, new_overflow_p = false;
2015 e = cxx_eval_constant_expression (ctx, e, vc_prvalue,
2016 &new_non_constant_p,
2017 &new_overflow_p);
2019 else
2020 e = fold_non_dependent_expr (e, tf_none, /*manifestly_const_eval=*/true);
2021 return e;
2024 /* If we have a condition in conjunctive normal form (CNF), find the first
2025 failing clause. In other words, given an expression like
2027 true && true && false && true && false
2029 return the first 'false'. EXPR is the expression. */
2031 static tree
2032 find_failing_clause_r (const constexpr_ctx *ctx, tree expr)
2034 if (TREE_CODE (expr) == TRUTH_ANDIF_EXPR)
2036 /* First check the left side... */
2037 tree e = find_failing_clause_r (ctx, TREE_OPERAND (expr, 0));
2038 if (e == NULL_TREE)
2039 /* ...if we didn't find a false clause, check the right side. */
2040 e = find_failing_clause_r (ctx, TREE_OPERAND (expr, 1));
2041 return e;
2043 tree e = contextual_conv_bool (expr, tf_none);
2044 e = fold_operand (e, ctx);
2045 if (integer_zerop (e))
2046 /* This is the failing clause. */
2047 return expr;
2048 return NULL_TREE;
2051 /* Wrapper for find_failing_clause_r. */
2053 tree
2054 find_failing_clause (const constexpr_ctx *ctx, tree expr)
2056 if (TREE_CODE (expr) == TRUTH_ANDIF_EXPR)
2057 if (tree e = find_failing_clause_r (ctx, expr))
2058 expr = e;
2059 return expr;
2062 /* Emit additional diagnostics for failing condition BAD.
2063 Used by finish_static_assert and IFN_ASSUME constexpr diagnostics.
2064 If SHOW_EXPR_P is true, print the condition (because it was
2065 instantiation-dependent). */
2067 void
2068 diagnose_failing_condition (tree bad, location_t cloc, bool show_expr_p,
2069 const constexpr_ctx *ctx /* = nullptr */)
2071 /* Nobody wants to see the artificial (bool) cast. */
2072 bad = tree_strip_nop_conversions (bad);
2073 if (TREE_CODE (bad) == CLEANUP_POINT_EXPR)
2074 bad = TREE_OPERAND (bad, 0);
2076 /* Actually explain the failure if this is a concept check or a
2077 requires-expression. */
2078 if (concept_check_p (bad) || TREE_CODE (bad) == REQUIRES_EXPR)
2079 diagnose_constraints (cloc, bad, NULL_TREE);
2080 else if (COMPARISON_CLASS_P (bad)
2081 && ARITHMETIC_TYPE_P (TREE_TYPE (TREE_OPERAND (bad, 0))))
2083 tree op0 = fold_operand (TREE_OPERAND (bad, 0), ctx);
2084 tree op1 = fold_operand (TREE_OPERAND (bad, 1), ctx);
2085 tree cond = build2 (TREE_CODE (bad), boolean_type_node, op0, op1);
2086 inform (cloc, "the comparison reduces to %qE", cond);
2088 else if (show_expr_p)
2089 inform (cloc, "%qE evaluates to false", bad);
2092 /* Process an assert/assume of ORIG_ARG. If it's not supposed to be evaluated,
2093 do it without changing the current evaluation state. If it evaluates to
2094 false, complain and return false; otherwise, return true. */
2096 static bool
2097 cxx_eval_assert (const constexpr_ctx *ctx, tree arg, const char *msg,
2098 location_t loc, bool evaluated,
2099 bool *non_constant_p, bool *overflow_p)
2101 if (*non_constant_p)
2102 return true;
2104 tree eval;
2105 if (!evaluated)
2107 if (!potential_rvalue_constant_expression (arg))
2108 return true;
2110 constexpr_ctx new_ctx = *ctx;
2111 new_ctx.quiet = true;
2112 bool new_non_constant_p = false, new_overflow_p = false;
2113 /* Avoid modification of existing values. */
2114 modifiable_tracker ms (new_ctx.global);
2115 eval = cxx_eval_constant_expression (&new_ctx, arg, vc_prvalue,
2116 &new_non_constant_p,
2117 &new_overflow_p);
2119 else
2120 eval = cxx_eval_constant_expression (ctx, arg, vc_prvalue,
2121 non_constant_p,
2122 overflow_p);
2123 if (!*non_constant_p && integer_zerop (eval))
2125 if (!ctx->quiet)
2127 /* See if we can find which clause was failing
2128 (for logical AND). */
2129 tree bad = find_failing_clause (ctx, arg);
2130 /* If not, or its location is unusable, fall back to the
2131 previous location. */
2132 location_t cloc = cp_expr_loc_or_loc (bad, loc);
2134 /* Report the error. */
2135 auto_diagnostic_group d;
2136 error_at (cloc, msg);
2137 diagnose_failing_condition (bad, cloc, true, ctx);
2138 return bad;
2140 *non_constant_p = true;
2141 return false;
2144 return true;
2147 /* Evaluate a call T to a GCC internal function when possible and return
2148 the evaluated result or, under the control of CTX, give an error, set
2149 NON_CONSTANT_P, and return the unevaluated call T otherwise. */
2151 static tree
2152 cxx_eval_internal_function (const constexpr_ctx *ctx, tree t,
2153 value_cat lval,
2154 bool *non_constant_p, bool *overflow_p)
2156 enum tree_code opcode = ERROR_MARK;
2158 switch (CALL_EXPR_IFN (t))
2160 case IFN_UBSAN_NULL:
2161 case IFN_UBSAN_BOUNDS:
2162 case IFN_UBSAN_VPTR:
2163 case IFN_FALLTHROUGH:
2164 return void_node;
2166 case IFN_ASSUME:
2167 if (!cxx_eval_assert (ctx, CALL_EXPR_ARG (t, 0),
2168 G_("failed %<assume%> attribute assumption"),
2169 EXPR_LOCATION (t), /*eval*/false,
2170 non_constant_p, overflow_p))
2171 return t;
2172 return void_node;
2174 case IFN_ADD_OVERFLOW:
2175 opcode = PLUS_EXPR;
2176 break;
2177 case IFN_SUB_OVERFLOW:
2178 opcode = MINUS_EXPR;
2179 break;
2180 case IFN_MUL_OVERFLOW:
2181 opcode = MULT_EXPR;
2182 break;
2184 case IFN_LAUNDER:
2185 return cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0),
2186 vc_prvalue, non_constant_p,
2187 overflow_p);
2189 case IFN_VEC_CONVERT:
2191 tree arg = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0),
2192 vc_prvalue, non_constant_p,
2193 overflow_p);
2194 if (TREE_CODE (arg) == VECTOR_CST)
2195 if (tree r = fold_const_call (CFN_VEC_CONVERT, TREE_TYPE (t), arg))
2196 return r;
2198 /* FALLTHRU */
2200 default:
2201 if (!ctx->quiet)
2202 error_at (cp_expr_loc_or_input_loc (t),
2203 "call to internal function %qE", t);
2204 *non_constant_p = true;
2205 return t;
2208 /* Evaluate constant arguments using OPCODE and return a complex
2209 number containing the result and the overflow bit. */
2210 tree arg0 = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0), lval,
2211 non_constant_p, overflow_p);
2212 tree arg1 = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 1), lval,
2213 non_constant_p, overflow_p);
2215 if (TREE_CODE (arg0) == INTEGER_CST && TREE_CODE (arg1) == INTEGER_CST)
2217 location_t loc = cp_expr_loc_or_input_loc (t);
2218 tree type = TREE_TYPE (TREE_TYPE (t));
2219 tree result = fold_binary_loc (loc, opcode, type,
2220 fold_convert_loc (loc, type, arg0),
2221 fold_convert_loc (loc, type, arg1));
2222 tree ovf
2223 = build_int_cst (type, arith_overflowed_p (opcode, type, arg0, arg1));
2224 /* Reset TREE_OVERFLOW to avoid warnings for the overflow. */
2225 if (TREE_OVERFLOW (result))
2226 TREE_OVERFLOW (result) = 0;
2228 return build_complex (TREE_TYPE (t), result, ovf);
2231 *non_constant_p = true;
2232 return t;
2235 /* Clean CONSTRUCTOR_NO_CLEARING from CTOR and its sub-aggregates. */
2237 static void
2238 clear_no_implicit_zero (tree ctor)
2240 if (CONSTRUCTOR_NO_CLEARING (ctor))
2242 CONSTRUCTOR_NO_CLEARING (ctor) = false;
2243 for (auto &e: CONSTRUCTOR_ELTS (ctor))
2244 if (TREE_CODE (e.value) == CONSTRUCTOR)
2245 clear_no_implicit_zero (e.value);
2249 /* Complain about a const object OBJ being modified in a constant expression.
2250 EXPR is the MODIFY_EXPR expression performing the modification. */
2252 static void
2253 modifying_const_object_error (tree expr, tree obj)
2255 location_t loc = cp_expr_loc_or_input_loc (expr);
2256 auto_diagnostic_group d;
2257 error_at (loc, "modifying a const object %qE is not allowed in "
2258 "a constant expression", TREE_OPERAND (expr, 0));
2260 /* Find the underlying object that was declared as const. */
2261 location_t decl_loc = UNKNOWN_LOCATION;
2262 for (tree probe = obj; decl_loc == UNKNOWN_LOCATION; )
2263 switch (TREE_CODE (probe))
2265 case BIT_FIELD_REF:
2266 case COMPONENT_REF:
2268 tree elt = TREE_OPERAND (probe, 1);
2269 if (CP_TYPE_CONST_P (TREE_TYPE (elt)))
2270 decl_loc = DECL_SOURCE_LOCATION (elt);
2271 probe = TREE_OPERAND (probe, 0);
2273 break;
2275 case ARRAY_REF:
2276 case REALPART_EXPR:
2277 case IMAGPART_EXPR:
2278 probe = TREE_OPERAND (probe, 0);
2279 break;
2281 default:
2282 decl_loc = location_of (probe);
2283 break;
2285 inform (decl_loc, "originally declared %<const%> here");
2288 /* Return true if FNDECL is a replaceable global allocation function that
2289 should be useable during constant expression evaluation. */
2291 static inline bool
2292 cxx_replaceable_global_alloc_fn (tree fndecl)
2294 return (cxx_dialect >= cxx20
2295 && IDENTIFIER_NEWDEL_OP_P (DECL_NAME (fndecl))
2296 && CP_DECL_CONTEXT (fndecl) == global_namespace
2297 && (DECL_IS_REPLACEABLE_OPERATOR_NEW_P (fndecl)
2298 || DECL_IS_OPERATOR_DELETE_P (fndecl)));
2301 /* Return true if FNDECL is a placement new function that should be
2302 useable during constant expression evaluation of std::construct_at. */
2304 static inline bool
2305 cxx_placement_new_fn (tree fndecl)
2307 if (cxx_dialect >= cxx20
2308 && IDENTIFIER_NEW_OP_P (DECL_NAME (fndecl))
2309 && CP_DECL_CONTEXT (fndecl) == global_namespace
2310 && !DECL_IS_REPLACEABLE_OPERATOR_NEW_P (fndecl)
2311 && TREE_CODE (TREE_TYPE (fndecl)) == FUNCTION_TYPE)
2313 tree first_arg = TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (fndecl)));
2314 if (TREE_VALUE (first_arg) == ptr_type_node
2315 && TREE_CHAIN (first_arg) == void_list_node)
2316 return true;
2318 return false;
2321 /* Return true if FNDECL is std::construct_at. */
2323 static inline bool
2324 is_std_construct_at (tree fndecl)
2326 if (!decl_in_std_namespace_p (fndecl))
2327 return false;
2329 tree name = DECL_NAME (fndecl);
2330 return name && id_equal (name, "construct_at");
2333 /* Overload for the above taking constexpr_call*. */
2335 static inline bool
2336 is_std_construct_at (const constexpr_call *call)
2338 return (call
2339 && call->fundef
2340 && is_std_construct_at (call->fundef->decl));
2343 /* True if CTX is an instance of std::allocator. */
2345 bool
2346 is_std_allocator (tree ctx)
2348 if (ctx == NULL_TREE || !CLASS_TYPE_P (ctx) || !TYPE_MAIN_DECL (ctx))
2349 return false;
2351 tree decl = TYPE_MAIN_DECL (ctx);
2352 tree name = DECL_NAME (decl);
2353 if (name == NULL_TREE || !id_equal (name, "allocator"))
2354 return false;
2356 return decl_in_std_namespace_p (decl);
2359 /* Return true if FNDECL is std::allocator<T>::{,de}allocate. */
2361 static inline bool
2362 is_std_allocator_allocate (tree fndecl)
2364 tree name = DECL_NAME (fndecl);
2365 if (name == NULL_TREE
2366 || !(id_equal (name, "allocate") || id_equal (name, "deallocate")))
2367 return false;
2369 return is_std_allocator (DECL_CONTEXT (fndecl));
2372 /* Overload for the above taking constexpr_call*. */
2374 static inline bool
2375 is_std_allocator_allocate (const constexpr_call *call)
2377 return (call
2378 && call->fundef
2379 && is_std_allocator_allocate (call->fundef->decl));
2382 /* Return true if FNDECL is std::source_location::current. */
2384 static inline bool
2385 is_std_source_location_current (tree fndecl)
2387 if (!decl_in_std_namespace_p (fndecl))
2388 return false;
2390 tree name = DECL_NAME (fndecl);
2391 if (name == NULL_TREE || !id_equal (name, "current"))
2392 return false;
2394 tree ctx = DECL_CONTEXT (fndecl);
2395 if (ctx == NULL_TREE || !CLASS_TYPE_P (ctx) || !TYPE_MAIN_DECL (ctx))
2396 return false;
2398 name = DECL_NAME (TYPE_MAIN_DECL (ctx));
2399 return name && id_equal (name, "source_location");
2402 /* Overload for the above taking constexpr_call*. */
2404 static inline bool
2405 is_std_source_location_current (const constexpr_call *call)
2407 return (call
2408 && call->fundef
2409 && is_std_source_location_current (call->fundef->decl));
2412 /* Return true if FNDECL is __dynamic_cast. */
2414 static inline bool
2415 cxx_dynamic_cast_fn_p (tree fndecl)
2417 return (cxx_dialect >= cxx20
2418 && id_equal (DECL_NAME (fndecl), "__dynamic_cast")
2419 && CP_DECL_CONTEXT (fndecl) == abi_node);
2422 /* Often, we have an expression in the form of address + offset, e.g.
2423 "&_ZTV1A + 16". Extract the object from it, i.e. "_ZTV1A". */
2425 static tree
2426 extract_obj_from_addr_offset (tree expr)
2428 if (TREE_CODE (expr) == POINTER_PLUS_EXPR)
2429 expr = TREE_OPERAND (expr, 0);
2430 STRIP_NOPS (expr);
2431 if (TREE_CODE (expr) == ADDR_EXPR)
2432 expr = TREE_OPERAND (expr, 0);
2433 return expr;
2436 /* Given a PATH like
2438 g.D.2181.D.2154.D.2102.D.2093
2440 find a component with type TYPE. Return NULL_TREE if not found, and
2441 error_mark_node if the component is not accessible. If STOP is non-null,
2442 this function will return NULL_TREE if STOP is found before TYPE. */
2444 static tree
2445 get_component_with_type (tree path, tree type, tree stop)
2447 while (true)
2449 if (same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (path), type))
2450 /* Found it. */
2451 return path;
2452 else if (stop
2453 && (same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (path),
2454 stop)))
2455 return NULL_TREE;
2456 else if (TREE_CODE (path) == COMPONENT_REF
2457 && DECL_FIELD_IS_BASE (TREE_OPERAND (path, 1)))
2459 /* We need to check that the component we're accessing is in fact
2460 accessible. */
2461 if (TREE_PRIVATE (TREE_OPERAND (path, 1))
2462 || TREE_PROTECTED (TREE_OPERAND (path, 1)))
2463 return error_mark_node;
2464 path = TREE_OPERAND (path, 0);
2466 else
2467 return NULL_TREE;
2471 /* Evaluate a call to __dynamic_cast (permitted by P1327R1).
2473 The declaration of __dynamic_cast is:
2475 void* __dynamic_cast (const void* __src_ptr,
2476 const __class_type_info* __src_type,
2477 const __class_type_info* __dst_type,
2478 ptrdiff_t __src2dst);
2480 where src2dst has the following possible values
2482 >-1: src_type is a unique public non-virtual base of dst_type
2483 dst_ptr + src2dst == src_ptr
2484 -1: unspecified relationship
2485 -2: src_type is not a public base of dst_type
2486 -3: src_type is a multiple public non-virtual base of dst_type
2488 Since literal types can't have virtual bases, we only expect hint >=0,
2489 -2, or -3. */
2491 static tree
2492 cxx_eval_dynamic_cast_fn (const constexpr_ctx *ctx, tree call,
2493 bool *non_constant_p, bool *overflow_p)
2495 /* T will be something like
2496 __dynamic_cast ((B*) b, &_ZTI1B, &_ZTI1D, 8)
2497 dismantle it. */
2498 gcc_assert (call_expr_nargs (call) == 4);
2499 tsubst_flags_t complain = ctx->quiet ? tf_none : tf_warning_or_error;
2500 tree obj = CALL_EXPR_ARG (call, 0);
2501 tree type = CALL_EXPR_ARG (call, 2);
2502 HOST_WIDE_INT hint = int_cst_value (CALL_EXPR_ARG (call, 3));
2503 location_t loc = cp_expr_loc_or_input_loc (call);
2505 /* Get the target type of the dynamic_cast. */
2506 gcc_assert (TREE_CODE (type) == ADDR_EXPR);
2507 type = TREE_OPERAND (type, 0);
2508 type = TREE_TYPE (DECL_NAME (type));
2510 /* TYPE can only be either T* or T&. We can't know which of these it
2511 is by looking at TYPE, but OBJ will be "(T*) x" in the first case,
2512 and something like "(T*)(T&)(T*) x" in the second case. */
2513 bool reference_p = false;
2514 while (CONVERT_EXPR_P (obj) || TREE_CODE (obj) == SAVE_EXPR)
2516 reference_p |= TYPE_REF_P (TREE_TYPE (obj));
2517 obj = TREE_OPERAND (obj, 0);
2520 /* Evaluate the object so that we know its dynamic type. */
2521 obj = cxx_eval_constant_expression (ctx, obj, vc_prvalue, non_constant_p,
2522 overflow_p);
2523 if (*non_constant_p)
2524 return call;
2526 /* We expect OBJ to be in form of &d.D.2102 when HINT == 0,
2527 but when HINT is > 0, it can also be something like
2528 &d.D.2102 + 18446744073709551608, which includes the BINFO_OFFSET. */
2529 obj = extract_obj_from_addr_offset (obj);
2530 const tree objtype = TREE_TYPE (obj);
2531 /* If OBJ doesn't refer to a base field, we're done. */
2532 if (tree t = (TREE_CODE (obj) == COMPONENT_REF
2533 ? TREE_OPERAND (obj, 1) : obj))
2534 if (TREE_CODE (t) != FIELD_DECL || !DECL_FIELD_IS_BASE (t))
2536 if (reference_p)
2538 if (!ctx->quiet)
2540 auto_diagnostic_group d;
2541 error_at (loc, "reference %<dynamic_cast%> failed");
2542 inform (loc, "dynamic type %qT of its operand does "
2543 "not have a base class of type %qT",
2544 objtype, type);
2546 *non_constant_p = true;
2548 return integer_zero_node;
2551 /* [class.cdtor] When a dynamic_cast is used in a constructor ...
2552 or in a destructor ... if the operand of the dynamic_cast refers
2553 to the object under construction or destruction, this object is
2554 considered to be a most derived object that has the type of the
2555 constructor or destructor's class. */
2556 tree vtable = build_vfield_ref (obj, objtype);
2557 vtable = cxx_eval_constant_expression (ctx, vtable, vc_prvalue,
2558 non_constant_p, overflow_p);
2559 if (*non_constant_p)
2560 return call;
2561 /* With -fsanitize=vptr, we initialize all vtable pointers to null,
2562 so it's possible that we got a null pointer now. */
2563 if (integer_zerop (vtable))
2565 if (!ctx->quiet)
2566 error_at (loc, "virtual table pointer is used uninitialized");
2567 *non_constant_p = true;
2568 return integer_zero_node;
2570 /* VTABLE will be &_ZTV1A + 16 or similar, get _ZTV1A. */
2571 vtable = extract_obj_from_addr_offset (vtable);
2572 const tree mdtype = DECL_CONTEXT (vtable);
2574 /* Given dynamic_cast<T>(v),
2576 [expr.dynamic.cast] If C is the class type to which T points or refers,
2577 the runtime check logically executes as follows:
2579 If, in the most derived object pointed (referred) to by v, v points
2580 (refers) to a public base class subobject of a C object, and if only
2581 one object of type C is derived from the subobject pointed (referred)
2582 to by v the result points (refers) to that C object.
2584 In this case, HINT >= 0 or -3. */
2585 if (hint >= 0 || hint == -3)
2587 /* Look for a component with type TYPE. */
2588 tree t = get_component_with_type (obj, type, mdtype);
2589 /* If not accessible, give an error. */
2590 if (t == error_mark_node)
2592 if (reference_p)
2594 if (!ctx->quiet)
2596 auto_diagnostic_group d;
2597 error_at (loc, "reference %<dynamic_cast%> failed");
2598 inform (loc, "static type %qT of its operand is a "
2599 "non-public base class of dynamic type %qT",
2600 objtype, type);
2603 *non_constant_p = true;
2605 return integer_zero_node;
2607 else if (t)
2608 /* The result points to the TYPE object. */
2609 return cp_build_addr_expr (t, complain);
2610 /* Else, TYPE was not found, because the HINT turned out to be wrong.
2611 Fall through to the normal processing. */
2614 /* Otherwise, if v points (refers) to a public base class subobject of the
2615 most derived object, and the type of the most derived object has a base
2616 class, of type C, that is unambiguous and public, the result points
2617 (refers) to the C subobject of the most derived object.
2619 But it can also be an invalid case. */
2621 /* Get the most derived object. */
2622 obj = get_component_with_type (obj, mdtype, NULL_TREE);
2623 if (obj == error_mark_node)
2625 if (reference_p)
2627 if (!ctx->quiet)
2629 auto_diagnostic_group d;
2630 error_at (loc, "reference %<dynamic_cast%> failed");
2631 inform (loc, "static type %qT of its operand is a non-public"
2632 " base class of dynamic type %qT", objtype, mdtype);
2634 *non_constant_p = true;
2636 return integer_zero_node;
2638 else
2639 gcc_assert (obj);
2641 /* Check that the type of the most derived object has a base class
2642 of type TYPE that is unambiguous and public. */
2643 base_kind b_kind;
2644 tree binfo = lookup_base (mdtype, type, ba_check, &b_kind, tf_none);
2645 if (!binfo || binfo == error_mark_node)
2647 if (reference_p)
2649 if (!ctx->quiet)
2651 auto_diagnostic_group d;
2652 error_at (loc, "reference %<dynamic_cast%> failed");
2653 if (b_kind == bk_ambig)
2654 inform (loc, "%qT is an ambiguous base class of dynamic "
2655 "type %qT of its operand", type, mdtype);
2656 else
2657 inform (loc, "dynamic type %qT of its operand does not "
2658 "have an unambiguous public base class %qT",
2659 mdtype, type);
2661 *non_constant_p = true;
2663 return integer_zero_node;
2665 /* If so, return the TYPE subobject of the most derived object. */
2666 obj = convert_to_base_statically (obj, binfo);
2667 return cp_build_addr_expr (obj, complain);
2670 /* Data structure used by replace_decl and replace_decl_r. */
2672 struct replace_decl_data
2674 /* The _DECL we want to replace. */
2675 tree decl;
2676 /* The replacement for DECL. */
2677 tree replacement;
2678 /* Trees we've visited. */
2679 hash_set<tree> *pset;
2680 /* Whether we've performed any replacements. */
2681 bool changed;
2684 /* Helper function for replace_decl, called through cp_walk_tree. */
2686 static tree
2687 replace_decl_r (tree *tp, int *walk_subtrees, void *data)
2689 replace_decl_data *d = (replace_decl_data *) data;
2691 if (*tp == d->decl)
2693 *tp = unshare_expr (d->replacement);
2694 d->changed = true;
2695 *walk_subtrees = 0;
2697 else if (TYPE_P (*tp)
2698 || d->pset->add (*tp))
2699 *walk_subtrees = 0;
2701 return NULL_TREE;
2704 /* Replace every occurrence of DECL with (an unshared copy of)
2705 REPLACEMENT within the expression *TP. Returns true iff a
2706 replacement was performed. */
2708 bool
2709 replace_decl (tree *tp, tree decl, tree replacement)
2711 gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
2712 (TREE_TYPE (decl), TREE_TYPE (replacement)));
2713 hash_set<tree> pset;
2714 replace_decl_data data = { decl, replacement, &pset, false };
2715 cp_walk_tree (tp, replace_decl_r, &data, NULL);
2716 return data.changed;
2719 /* Evaluate the call T to virtual function thunk THUNK_FNDECL. */
2721 static tree
2722 cxx_eval_thunk_call (const constexpr_ctx *ctx, tree t, tree thunk_fndecl,
2723 value_cat lval,
2724 bool *non_constant_p, bool *overflow_p)
2726 tree function = THUNK_TARGET (thunk_fndecl);
2728 if (THUNK_VIRTUAL_OFFSET (thunk_fndecl))
2730 if (!ctx->quiet)
2732 if (!DECL_DECLARED_CONSTEXPR_P (function))
2734 error ("call to non-%<constexpr%> function %qD", function);
2735 explain_invalid_constexpr_fn (function);
2737 else
2738 /* virtual_offset is only set for virtual bases, which make the
2739 class non-literal, so we don't need to handle it here. */
2740 error ("calling constexpr member function %qD through virtual "
2741 "base subobject", function);
2743 *non_constant_p = true;
2744 return t;
2747 tree new_call = copy_node (t);
2748 CALL_EXPR_FN (new_call) = function;
2749 TREE_TYPE (new_call) = TREE_TYPE (TREE_TYPE (function));
2751 tree offset = size_int (THUNK_FIXED_OFFSET (thunk_fndecl));
2753 if (DECL_THIS_THUNK_P (thunk_fndecl))
2755 /* 'this'-adjusting thunk. */
2756 tree this_arg = CALL_EXPR_ARG (t, 0);
2757 this_arg = build2 (POINTER_PLUS_EXPR, TREE_TYPE (this_arg),
2758 this_arg, offset);
2759 CALL_EXPR_ARG (new_call, 0) = this_arg;
2761 else
2762 /* Return-adjusting thunk. */
2763 new_call = build2 (POINTER_PLUS_EXPR, TREE_TYPE (new_call),
2764 new_call, offset);
2766 return cxx_eval_constant_expression (ctx, new_call, lval,
2767 non_constant_p, overflow_p);
2770 /* If OBJECT is of const class type, evaluate it to a CONSTRUCTOR and set
2771 its TREE_READONLY flag according to READONLY_P. Used for constexpr
2772 'tors to detect modifying const objects in a constexpr context. */
2774 static void
2775 cxx_set_object_constness (const constexpr_ctx *ctx, tree object,
2776 bool readonly_p, bool *non_constant_p,
2777 bool *overflow_p)
2779 if (CLASS_TYPE_P (TREE_TYPE (object))
2780 && CP_TYPE_CONST_P (TREE_TYPE (object)))
2782 /* Subobjects might not be stored in ctx->global->values but we
2783 can get its CONSTRUCTOR by evaluating *this. */
2784 tree e = cxx_eval_constant_expression (ctx, object, vc_prvalue,
2785 non_constant_p, overflow_p);
2786 if (TREE_CODE (e) == CONSTRUCTOR && !*non_constant_p)
2787 TREE_READONLY (e) = readonly_p;
2791 /* Subroutine of cxx_eval_constant_expression.
2792 Evaluate the call expression tree T in the context of OLD_CALL expression
2793 evaluation. */
2795 static tree
2796 cxx_eval_call_expression (const constexpr_ctx *ctx, tree t,
2797 value_cat lval,
2798 bool *non_constant_p, bool *overflow_p)
2800 /* Handle concept checks separately. */
2801 if (concept_check_p (t))
2802 return evaluate_concept_check (t);
2804 location_t loc = cp_expr_loc_or_input_loc (t);
2805 tree fun = get_function_named_in_call (t);
2806 constexpr_call new_call
2807 = { NULL, NULL, NULL, 0, ctx->manifestly_const_eval };
2808 int depth_ok;
2810 if (fun == NULL_TREE)
2811 return cxx_eval_internal_function (ctx, t, lval,
2812 non_constant_p, overflow_p);
2814 if (TREE_CODE (fun) != FUNCTION_DECL)
2816 /* Might be a constexpr function pointer. */
2817 fun = cxx_eval_constant_expression (ctx, fun, vc_prvalue,
2818 non_constant_p, overflow_p);
2819 STRIP_NOPS (fun);
2820 if (TREE_CODE (fun) == ADDR_EXPR)
2821 fun = TREE_OPERAND (fun, 0);
2822 /* For TARGET_VTABLE_USES_DESCRIPTORS targets, there is no
2823 indirection, the called expression is a pointer into the
2824 virtual table which should contain FDESC_EXPR. Extract the
2825 FUNCTION_DECL from there. */
2826 else if (TARGET_VTABLE_USES_DESCRIPTORS
2827 && TREE_CODE (fun) == POINTER_PLUS_EXPR
2828 && TREE_CODE (TREE_OPERAND (fun, 0)) == ADDR_EXPR
2829 && TREE_CODE (TREE_OPERAND (fun, 1)) == INTEGER_CST)
2831 tree d = TREE_OPERAND (TREE_OPERAND (fun, 0), 0);
2832 if (VAR_P (d)
2833 && DECL_VTABLE_OR_VTT_P (d)
2834 && TREE_CODE (TREE_TYPE (d)) == ARRAY_TYPE
2835 && TREE_TYPE (TREE_TYPE (d)) == vtable_entry_type
2836 && DECL_INITIAL (d)
2837 && TREE_CODE (DECL_INITIAL (d)) == CONSTRUCTOR)
2839 tree i = int_const_binop (TRUNC_DIV_EXPR, TREE_OPERAND (fun, 1),
2840 TYPE_SIZE_UNIT (vtable_entry_type));
2841 HOST_WIDE_INT idx = find_array_ctor_elt (DECL_INITIAL (d), i);
2842 if (idx >= 0)
2844 tree fdesc
2845 = (*CONSTRUCTOR_ELTS (DECL_INITIAL (d)))[idx].value;
2846 if (TREE_CODE (fdesc) == FDESC_EXPR
2847 && integer_zerop (TREE_OPERAND (fdesc, 1)))
2848 fun = TREE_OPERAND (fdesc, 0);
2853 if (TREE_CODE (fun) != FUNCTION_DECL)
2855 if (!ctx->quiet && !*non_constant_p)
2856 error_at (loc, "expression %qE does not designate a %<constexpr%> "
2857 "function", fun);
2858 *non_constant_p = true;
2859 return t;
2861 if (DECL_CLONED_FUNCTION_P (fun) && !DECL_DELETING_DESTRUCTOR_P (fun))
2862 fun = DECL_CLONED_FUNCTION (fun);
2864 if (is_ubsan_builtin_p (fun))
2865 return void_node;
2867 if (fndecl_built_in_p (fun))
2868 return cxx_eval_builtin_function_call (ctx, t, fun,
2869 lval, non_constant_p, overflow_p);
2870 if (DECL_THUNK_P (fun))
2871 return cxx_eval_thunk_call (ctx, t, fun, lval, non_constant_p, overflow_p);
2872 if (!maybe_constexpr_fn (fun))
2874 if (TREE_CODE (t) == CALL_EXPR
2875 && cxx_replaceable_global_alloc_fn (fun)
2876 && (CALL_FROM_NEW_OR_DELETE_P (t)
2877 || is_std_allocator_allocate (ctx->call)))
2879 const bool new_op_p = IDENTIFIER_NEW_OP_P (DECL_NAME (fun));
2880 const int nargs = call_expr_nargs (t);
2881 tree arg0 = NULL_TREE;
2882 for (int i = 0; i < nargs; ++i)
2884 tree arg = CALL_EXPR_ARG (t, i);
2885 arg = cxx_eval_constant_expression (ctx, arg, vc_prvalue,
2886 non_constant_p, overflow_p);
2887 /* Deleting a non-constant pointer has a better error message
2888 below. */
2889 if (new_op_p || i != 0)
2890 VERIFY_CONSTANT (arg);
2891 if (i == 0)
2892 arg0 = arg;
2894 gcc_assert (arg0);
2895 if (new_op_p)
2897 tree type = build_array_type_nelts (char_type_node,
2898 tree_to_uhwi (arg0));
2899 tree var = build_decl (loc, VAR_DECL,
2900 (IDENTIFIER_OVL_OP_FLAGS (DECL_NAME (fun))
2901 & OVL_OP_FLAG_VEC)
2902 ? heap_vec_uninit_identifier
2903 : heap_uninit_identifier,
2904 type);
2905 DECL_ARTIFICIAL (var) = 1;
2906 TREE_STATIC (var) = 1;
2907 // Temporarily register the artificial var in varpool,
2908 // so that comparisons of its address against NULL are folded
2909 // through nonzero_address even with
2910 // -fno-delete-null-pointer-checks or that comparison of
2911 // addresses of different heap artificial vars is folded too.
2912 // See PR98988 and PR99031.
2913 varpool_node::finalize_decl (var);
2914 ctx->global->heap_vars.safe_push (var);
2915 ctx->global->put_value (var, NULL_TREE);
2916 return fold_convert (ptr_type_node, build_address (var));
2918 else
2920 STRIP_NOPS (arg0);
2921 if (TREE_CODE (arg0) == ADDR_EXPR
2922 && VAR_P (TREE_OPERAND (arg0, 0)))
2924 tree var = TREE_OPERAND (arg0, 0);
2925 if (DECL_NAME (var) == heap_uninit_identifier
2926 || DECL_NAME (var) == heap_identifier)
2928 if (IDENTIFIER_OVL_OP_FLAGS (DECL_NAME (fun))
2929 & OVL_OP_FLAG_VEC)
2931 if (!ctx->quiet)
2933 auto_diagnostic_group d;
2934 error_at (loc, "array deallocation of object "
2935 "allocated with non-array "
2936 "allocation");
2937 inform (DECL_SOURCE_LOCATION (var),
2938 "allocation performed here");
2940 *non_constant_p = true;
2941 return t;
2943 DECL_NAME (var) = heap_deleted_identifier;
2944 ctx->global->destroy_value (var);
2945 ctx->global->heap_dealloc_count++;
2946 return void_node;
2948 else if (DECL_NAME (var) == heap_vec_uninit_identifier
2949 || DECL_NAME (var) == heap_vec_identifier)
2951 if ((IDENTIFIER_OVL_OP_FLAGS (DECL_NAME (fun))
2952 & OVL_OP_FLAG_VEC) == 0)
2954 if (!ctx->quiet)
2956 auto_diagnostic_group d;
2957 error_at (loc, "non-array deallocation of "
2958 "object allocated with array "
2959 "allocation");
2960 inform (DECL_SOURCE_LOCATION (var),
2961 "allocation performed here");
2963 *non_constant_p = true;
2964 return t;
2966 DECL_NAME (var) = heap_deleted_identifier;
2967 ctx->global->destroy_value (var);
2968 ctx->global->heap_dealloc_count++;
2969 return void_node;
2971 else if (DECL_NAME (var) == heap_deleted_identifier)
2973 if (!ctx->quiet)
2974 error_at (loc, "deallocation of already deallocated "
2975 "storage");
2976 *non_constant_p = true;
2977 return t;
2980 if (!ctx->quiet)
2981 error_at (loc, "deallocation of storage that was "
2982 "not previously allocated");
2983 *non_constant_p = true;
2984 return t;
2987 /* Allow placement new in std::construct_at, just return the second
2988 argument. */
2989 if (TREE_CODE (t) == CALL_EXPR
2990 && cxx_placement_new_fn (fun)
2991 && is_std_construct_at (ctx->call))
2993 const int nargs = call_expr_nargs (t);
2994 tree arg1 = NULL_TREE;
2995 for (int i = 0; i < nargs; ++i)
2997 tree arg = CALL_EXPR_ARG (t, i);
2998 arg = cxx_eval_constant_expression (ctx, arg, vc_prvalue,
2999 non_constant_p, overflow_p);
3000 if (i == 1)
3001 arg1 = arg;
3002 else
3003 VERIFY_CONSTANT (arg);
3005 gcc_assert (arg1);
3006 return arg1;
3008 else if (cxx_dynamic_cast_fn_p (fun))
3009 return cxx_eval_dynamic_cast_fn (ctx, t, non_constant_p, overflow_p);
3011 if (!ctx->quiet)
3013 if (!lambda_static_thunk_p (fun))
3014 error_at (loc, "call to non-%<constexpr%> function %qD", fun);
3015 explain_invalid_constexpr_fn (fun);
3017 *non_constant_p = true;
3018 return t;
3021 constexpr_ctx new_ctx = *ctx;
3022 if (DECL_CONSTRUCTOR_P (fun) && !ctx->object
3023 && TREE_CODE (t) == AGGR_INIT_EXPR)
3025 /* We want to have an initialization target for an AGGR_INIT_EXPR.
3026 If we don't already have one in CTX, use the AGGR_INIT_EXPR_SLOT. */
3027 new_ctx.object = AGGR_INIT_EXPR_SLOT (t);
3028 tree ctor = new_ctx.ctor = build_constructor (DECL_CONTEXT (fun), NULL);
3029 CONSTRUCTOR_NO_CLEARING (ctor) = true;
3030 ctx->global->put_value (new_ctx.object, ctor);
3031 ctx = &new_ctx;
3034 /* We used to shortcut trivial constructor/op= here, but nowadays
3035 we can only get a trivial function here with -fno-elide-constructors. */
3036 gcc_checking_assert (!trivial_fn_p (fun)
3037 || !flag_elide_constructors
3038 /* We don't elide constructors when processing
3039 a noexcept-expression. */
3040 || cp_noexcept_operand);
3042 bool non_constant_args = false;
3043 new_call.bindings
3044 = cxx_bind_parameters_in_call (ctx, t, fun, non_constant_p,
3045 overflow_p, &non_constant_args);
3047 /* We build up the bindings list before we know whether we already have this
3048 call cached. If we don't end up saving these bindings, ggc_free them when
3049 this function exits. */
3050 class free_bindings
3052 tree *bindings;
3053 public:
3054 free_bindings (tree &b): bindings (&b) { }
3055 ~free_bindings () { if (bindings) ggc_free (*bindings); }
3056 void preserve () { bindings = NULL; }
3057 } fb (new_call.bindings);
3059 if (*non_constant_p)
3060 return t;
3062 /* We can't defer instantiating the function any longer. */
3063 if (!DECL_INITIAL (fun)
3064 && (DECL_TEMPLOID_INSTANTIATION (fun) || DECL_DEFAULTED_FN (fun))
3065 && !uid_sensitive_constexpr_evaluation_p ())
3067 location_t save_loc = input_location;
3068 input_location = loc;
3069 ++function_depth;
3070 if (ctx->manifestly_const_eval == mce_true)
3071 FNDECL_MANIFESTLY_CONST_EVALUATED (fun) = true;
3072 if (DECL_TEMPLOID_INSTANTIATION (fun))
3073 instantiate_decl (fun, /*defer_ok*/false, /*expl_inst*/false);
3074 else
3075 synthesize_method (fun);
3076 --function_depth;
3077 input_location = save_loc;
3080 /* If in direct recursive call, optimize definition search. */
3081 if (ctx && ctx->call && ctx->call->fundef && ctx->call->fundef->decl == fun)
3082 new_call.fundef = ctx->call->fundef;
3083 else
3085 new_call.fundef = retrieve_constexpr_fundef (fun);
3086 if (new_call.fundef == NULL || new_call.fundef->body == NULL
3087 || new_call.fundef->result == error_mark_node
3088 || fun == current_function_decl)
3090 if (!ctx->quiet)
3092 /* We need to check for current_function_decl here in case we're
3093 being called during cp_fold_function, because at that point
3094 DECL_INITIAL is set properly and we have a fundef but we
3095 haven't lowered invisirefs yet (c++/70344). */
3096 if (DECL_INITIAL (fun) == error_mark_node
3097 || fun == current_function_decl)
3098 error_at (loc, "%qD called in a constant expression before its "
3099 "definition is complete", fun);
3100 else if (DECL_INITIAL (fun))
3102 /* The definition of fun was somehow unsuitable. But pretend
3103 that lambda static thunks don't exist. */
3104 if (!lambda_static_thunk_p (fun))
3105 error_at (loc, "%qD called in a constant expression", fun);
3106 explain_invalid_constexpr_fn (fun);
3108 else
3109 error_at (loc, "%qD used before its definition", fun);
3111 *non_constant_p = true;
3112 return t;
3116 depth_ok = push_cx_call_context (t);
3118 /* Remember the object we are constructing or destructing. */
3119 tree new_obj = NULL_TREE;
3120 if (DECL_CONSTRUCTOR_P (fun) || DECL_DESTRUCTOR_P (fun))
3122 /* In a cdtor, it should be the first `this' argument.
3123 At this point it has already been evaluated in the call
3124 to cxx_bind_parameters_in_call. */
3125 new_obj = TREE_VEC_ELT (new_call.bindings, 0);
3126 new_obj = cxx_fold_indirect_ref (ctx, loc, DECL_CONTEXT (fun), new_obj);
3128 if (ctx->call && ctx->call->fundef
3129 && DECL_CONSTRUCTOR_P (ctx->call->fundef->decl))
3131 tree cur_obj = TREE_VEC_ELT (ctx->call->bindings, 0);
3132 STRIP_NOPS (cur_obj);
3133 if (TREE_CODE (cur_obj) == ADDR_EXPR)
3134 cur_obj = TREE_OPERAND (cur_obj, 0);
3135 if (new_obj == cur_obj)
3136 /* We're calling the target constructor of a delegating
3137 constructor, or accessing a base subobject through a
3138 NOP_EXPR as part of a call to a base constructor, so
3139 there is no new (sub)object. */
3140 new_obj = NULL_TREE;
3144 tree result = NULL_TREE;
3146 constexpr_call *entry = NULL;
3147 if (depth_ok && !non_constant_args && ctx->strict)
3149 new_call.hash = constexpr_fundef_hasher::hash (new_call.fundef);
3150 new_call.hash
3151 = iterative_hash_template_arg (new_call.bindings, new_call.hash);
3152 new_call.hash
3153 = iterative_hash_object (ctx->manifestly_const_eval, new_call.hash);
3155 /* If we have seen this call before, we are done. */
3156 maybe_initialize_constexpr_call_table ();
3157 bool insert = depth_ok < constexpr_cache_depth;
3158 constexpr_call **slot
3159 = constexpr_call_table->find_slot (&new_call,
3160 insert ? INSERT : NO_INSERT);
3161 entry = slot ? *slot : NULL;
3162 if (entry == NULL)
3164 /* Only cache up to constexpr_cache_depth to limit memory use. */
3165 if (insert)
3167 /* We need to keep a pointer to the entry, not just the slot, as
3168 the slot can move during evaluation of the body. */
3169 *slot = entry = ggc_alloc<constexpr_call> ();
3170 *entry = new_call;
3171 fb.preserve ();
3174 /* Calls that are in progress have their result set to NULL, so that we
3175 can detect circular dependencies. Now that we only cache up to
3176 constexpr_cache_depth this won't catch circular dependencies that
3177 start deeper, but they'll hit the recursion or ops limit. */
3178 else if (entry->result == NULL)
3180 if (!ctx->quiet)
3181 error ("call has circular dependency");
3182 *non_constant_p = true;
3183 entry->result = result = error_mark_node;
3185 else
3186 result = entry->result;
3189 if (!depth_ok)
3191 if (!ctx->quiet)
3192 error ("%<constexpr%> evaluation depth exceeds maximum of %d (use "
3193 "%<-fconstexpr-depth=%> to increase the maximum)",
3194 max_constexpr_depth);
3195 *non_constant_p = true;
3196 result = error_mark_node;
3198 else
3200 bool cacheable = !!entry;
3201 if (result && result != error_mark_node)
3202 /* OK */;
3203 else if (!DECL_SAVED_TREE (fun))
3205 /* When at_eof >= 3, cgraph has started throwing away
3206 DECL_SAVED_TREE, so fail quietly. FIXME we get here because of
3207 late code generation for VEC_INIT_EXPR, which needs to be
3208 completely reconsidered. */
3209 gcc_assert (at_eof >= 3 && ctx->quiet);
3210 *non_constant_p = true;
3212 else if (tree copy = get_fundef_copy (new_call.fundef))
3214 tree body, parms, res;
3215 releasing_vec ctors;
3217 /* Reuse or create a new unshared copy of this function's body. */
3218 body = TREE_PURPOSE (copy);
3219 parms = TREE_VALUE (copy);
3220 res = TREE_TYPE (copy);
3222 /* Associate the bindings with the remapped parms. */
3223 tree bound = new_call.bindings;
3224 tree remapped = parms;
3225 for (int i = 0; i < TREE_VEC_LENGTH (bound); ++i)
3227 tree arg = TREE_VEC_ELT (bound, i);
3228 if (entry)
3230 /* Unshare args going into the hash table to separate them
3231 from the caller's context, for better GC and to avoid
3232 problems with verify_gimple. */
3233 arg = unshare_expr_without_location (arg);
3234 TREE_VEC_ELT (bound, i) = arg;
3236 /* And then unshare again so the callee doesn't change the
3237 argument values in the hash table. XXX Could we unshare
3238 lazily in cxx_eval_store_expression? */
3239 arg = unshare_constructor (arg);
3240 if (TREE_CODE (arg) == CONSTRUCTOR)
3241 vec_safe_push (ctors, arg);
3243 ctx->global->put_value (remapped, arg);
3244 remapped = DECL_CHAIN (remapped);
3246 if (remapped)
3248 /* We shouldn't have any parms without args, but fail gracefully
3249 in error recovery. */
3250 gcc_checking_assert (seen_error ());
3251 *non_constant_p = true;
3253 /* Add the RESULT_DECL to the values map, too. */
3254 gcc_assert (!DECL_BY_REFERENCE (res));
3255 ctx->global->put_value (res, NULL_TREE);
3257 /* Remember the current call we're evaluating. */
3258 constexpr_ctx call_ctx = *ctx;
3259 call_ctx.call = &new_call;
3260 unsigned save_heap_alloc_count = ctx->global->heap_vars.length ();
3261 unsigned save_heap_dealloc_count = ctx->global->heap_dealloc_count;
3263 /* Make sure we fold std::is_constant_evaluated to true in an
3264 immediate function. */
3265 if (DECL_IMMEDIATE_FUNCTION_P (fun))
3266 call_ctx.manifestly_const_eval = mce_true;
3268 /* If this is a constexpr destructor, the object's const and volatile
3269 semantics are no longer in effect; see [class.dtor]p5. */
3270 if (new_obj && DECL_DESTRUCTOR_P (fun))
3271 cxx_set_object_constness (ctx, new_obj, /*readonly_p=*/false,
3272 non_constant_p, overflow_p);
3274 /* If this is a constructor, we are beginning the lifetime of the
3275 object we are initializing. */
3276 if (new_obj
3277 && DECL_CONSTRUCTOR_P (fun)
3278 && TREE_CODE (new_obj) == COMPONENT_REF
3279 && TREE_CODE (TREE_TYPE (TREE_OPERAND (new_obj, 0))) == UNION_TYPE)
3281 tree activate = build2 (INIT_EXPR, TREE_TYPE (new_obj),
3282 new_obj,
3283 build_constructor (TREE_TYPE (new_obj),
3284 NULL));
3285 cxx_eval_constant_expression (ctx, activate,
3286 lval, non_constant_p, overflow_p);
3287 ggc_free (activate);
3290 tree jump_target = NULL_TREE;
3291 cxx_eval_constant_expression (&call_ctx, body,
3292 vc_discard, non_constant_p, overflow_p,
3293 &jump_target);
3295 if (DECL_CONSTRUCTOR_P (fun))
3296 /* This can be null for a subobject constructor call, in
3297 which case what we care about is the initialization
3298 side-effects rather than the value. We could get at the
3299 value by evaluating *this, but we don't bother; there's
3300 no need to put such a call in the hash table. */
3301 result = lval ? ctx->object : ctx->ctor;
3302 else if (VOID_TYPE_P (TREE_TYPE (res)))
3303 result = void_node;
3304 else
3306 result = ctx->global->get_value (res);
3307 if (result == NULL_TREE && !*non_constant_p
3308 && !DECL_DESTRUCTOR_P (fun))
3310 if (!ctx->quiet)
3311 error ("%<constexpr%> call flows off the end "
3312 "of the function");
3313 *non_constant_p = true;
3317 /* At this point, the object's constructor will have run, so
3318 the object is no longer under construction, and its possible
3319 'const' semantics now apply. Make a note of this fact by
3320 marking the CONSTRUCTOR TREE_READONLY. */
3321 if (new_obj && DECL_CONSTRUCTOR_P (fun))
3322 cxx_set_object_constness (ctx, new_obj, /*readonly_p=*/true,
3323 non_constant_p, overflow_p);
3325 /* Remove the parms/result from the values map. */
3326 destroy_value_checked (ctx, res, non_constant_p);
3327 for (tree parm = parms; parm; parm = TREE_CHAIN (parm))
3328 destroy_value_checked (ctx, parm, non_constant_p);
3330 /* Free any parameter CONSTRUCTORs we aren't returning directly. */
3331 while (!ctors->is_empty ())
3333 tree c = ctors->pop ();
3334 if (c != result)
3335 free_constructor (c);
3338 /* Make the unshared function copy we used available for re-use. */
3339 save_fundef_copy (fun, copy);
3341 /* If the call allocated some heap object that hasn't been
3342 deallocated during the call, or if it deallocated some heap
3343 object it has not allocated, the call isn't really stateless
3344 for the constexpr evaluation and should not be cached.
3345 It is fine if the call allocates something and deallocates it
3346 too. */
3347 if (cacheable
3348 && (save_heap_alloc_count != ctx->global->heap_vars.length ()
3349 || (save_heap_dealloc_count
3350 != ctx->global->heap_dealloc_count)))
3352 tree heap_var;
3353 unsigned int i;
3354 if ((ctx->global->heap_vars.length ()
3355 - ctx->global->heap_dealloc_count)
3356 != save_heap_alloc_count - save_heap_dealloc_count)
3357 cacheable = false;
3358 else
3359 FOR_EACH_VEC_ELT_FROM (ctx->global->heap_vars, i, heap_var,
3360 save_heap_alloc_count)
3361 if (DECL_NAME (heap_var) != heap_deleted_identifier)
3363 cacheable = false;
3364 break;
3368 /* Rewrite all occurrences of the function's RESULT_DECL with the
3369 current object under construction. */
3370 if (!*non_constant_p && ctx->object
3371 && CLASS_TYPE_P (TREE_TYPE (res))
3372 && !is_empty_class (TREE_TYPE (res)))
3373 if (replace_decl (&result, res, ctx->object))
3374 cacheable = false;
3376 /* Only cache a permitted result of a constant expression. */
3377 if (cacheable && !reduced_constant_expression_p (result))
3378 cacheable = false;
3380 else
3381 /* Couldn't get a function copy to evaluate. */
3382 *non_constant_p = true;
3384 if (result == error_mark_node)
3385 *non_constant_p = true;
3386 if (*non_constant_p || *overflow_p)
3387 result = error_mark_node;
3388 else if (!result)
3389 result = void_node;
3390 if (entry)
3391 entry->result = cacheable ? result : error_mark_node;
3394 /* The result of a constexpr function must be completely initialized.
3396 However, in C++20, a constexpr constructor doesn't necessarily have
3397 to initialize all the fields, so we don't clear CONSTRUCTOR_NO_CLEARING
3398 in order to detect reading an unitialized object in constexpr instead
3399 of value-initializing it. (reduced_constant_expression_p is expected to
3400 take care of clearing the flag.) */
3401 if (TREE_CODE (result) == CONSTRUCTOR
3402 && (cxx_dialect < cxx20
3403 || !DECL_CONSTRUCTOR_P (fun)))
3404 clear_no_implicit_zero (result);
3406 pop_cx_call_context ();
3407 return result;
3410 /* Return true if T is a valid constant initializer. If a CONSTRUCTOR
3411 initializes all the members, the CONSTRUCTOR_NO_CLEARING flag will be
3412 cleared.
3413 FIXME speed this up, it's taking 16% of compile time on sieve testcase. */
3415 bool
3416 reduced_constant_expression_p (tree t)
3418 if (t == NULL_TREE)
3419 return false;
3421 switch (TREE_CODE (t))
3423 case PTRMEM_CST:
3424 /* Even if we can't lower this yet, it's constant. */
3425 return true;
3427 case CONSTRUCTOR:
3428 /* And we need to handle PTRMEM_CST wrapped in a CONSTRUCTOR. */
3429 tree field;
3430 if (!AGGREGATE_TYPE_P (TREE_TYPE (t)))
3431 /* A constant vector would be folded to VECTOR_CST.
3432 A CONSTRUCTOR of scalar type means uninitialized. */
3433 return false;
3434 if (CONSTRUCTOR_NO_CLEARING (t))
3436 if (TREE_CODE (TREE_TYPE (t)) == ARRAY_TYPE)
3438 /* There must be a valid constant initializer at every array
3439 index. */
3440 tree min = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (t)));
3441 tree max = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (t)));
3442 tree cursor = min;
3443 for (auto &e: CONSTRUCTOR_ELTS (t))
3445 if (!reduced_constant_expression_p (e.value))
3446 return false;
3447 if (array_index_cmp (cursor, e.index) != 0)
3448 return false;
3449 if (TREE_CODE (e.index) == RANGE_EXPR)
3450 cursor = TREE_OPERAND (e.index, 1);
3451 cursor = int_const_binop (PLUS_EXPR, cursor, size_one_node);
3453 if (find_array_ctor_elt (t, max) == -1)
3454 return false;
3455 goto ok;
3457 else if (cxx_dialect >= cxx20
3458 && TREE_CODE (TREE_TYPE (t)) == UNION_TYPE)
3460 if (CONSTRUCTOR_NELTS (t) == 0)
3461 /* An initialized union has a constructor element. */
3462 return false;
3463 /* And it only initializes one member. */
3464 field = NULL_TREE;
3466 else
3467 field = next_subobject_field (TYPE_FIELDS (TREE_TYPE (t)));
3469 else
3470 field = NULL_TREE;
3471 for (auto &e: CONSTRUCTOR_ELTS (t))
3473 /* If VAL is null, we're in the middle of initializing this
3474 element. */
3475 if (!reduced_constant_expression_p (e.value))
3476 return false;
3477 /* We want to remove initializers for empty fields in a struct to
3478 avoid confusing output_constructor. */
3479 if (is_empty_field (e.index)
3480 && TREE_CODE (TREE_TYPE (t)) == RECORD_TYPE)
3481 return false;
3482 /* Check for non-empty fields between initialized fields when
3483 CONSTRUCTOR_NO_CLEARING. */
3484 for (; field && e.index != field;
3485 field = next_subobject_field (DECL_CHAIN (field)))
3486 if (!is_really_empty_class (TREE_TYPE (field),
3487 /*ignore_vptr*/false))
3488 return false;
3489 if (field)
3490 field = next_subobject_field (DECL_CHAIN (field));
3492 /* There could be a non-empty field at the end. */
3493 for (; field; field = next_subobject_field (DECL_CHAIN (field)))
3494 if (!is_really_empty_class (TREE_TYPE (field), /*ignore_vptr*/false))
3495 return false;
3497 if (CONSTRUCTOR_NO_CLEARING (t))
3498 /* All the fields are initialized. */
3499 CONSTRUCTOR_NO_CLEARING (t) = false;
3500 return true;
3502 default:
3503 /* FIXME are we calling this too much? */
3504 return initializer_constant_valid_p (t, TREE_TYPE (t)) != NULL_TREE;
3508 /* *TP was not deemed constant by reduced_constant_expression_p. Explain
3509 why and suggest what could be done about it. */
3511 static tree
3512 verify_constant_explain_r (tree *tp, int *walk_subtrees, void *)
3514 bool ref_p = false;
3516 /* No need to look into types or unevaluated operands. */
3517 if (TYPE_P (*tp) || unevaluated_p (TREE_CODE (*tp)))
3519 *walk_subtrees = false;
3520 return NULL_TREE;
3523 switch (TREE_CODE (*tp))
3525 CASE_CONVERT:
3526 if (TREE_CODE (TREE_OPERAND (*tp, 0)) != ADDR_EXPR)
3527 break;
3528 ref_p = TYPE_REF_P (TREE_TYPE (*tp));
3529 *tp = TREE_OPERAND (*tp, 0);
3530 gcc_fallthrough ();
3531 case ADDR_EXPR:
3533 tree op = TREE_OPERAND (*tp, 0);
3534 if (VAR_P (op)
3535 && DECL_DECLARED_CONSTEXPR_P (op)
3536 && !TREE_STATIC (op)
3537 /* ??? We should also say something about temporaries. */
3538 && !DECL_ARTIFICIAL (op))
3540 if (ref_p)
3541 inform (location_of (*tp), "reference to %qD is not a constant "
3542 "expression", op);
3543 else
3544 inform (location_of (*tp), "pointer to %qD is not a constant "
3545 "expression", op);
3546 const location_t op_loc = DECL_SOURCE_LOCATION (op);
3547 rich_location richloc (line_table, op_loc);
3548 richloc.add_fixit_insert_before (op_loc, "static ");
3549 inform (&richloc,
3550 "address of non-static constexpr variable %qD may differ on "
3551 "each invocation of the enclosing function; add %<static%> "
3552 "to give it a constant address", op);
3554 break;
3556 default:
3557 break;
3560 return NULL_TREE;
3563 /* Some expressions may have constant operands but are not constant
3564 themselves, such as 1/0. Call this function to check for that
3565 condition.
3567 We only call this in places that require an arithmetic constant, not in
3568 places where we might have a non-constant expression that can be a
3569 component of a constant expression, such as the address of a constexpr
3570 variable that might be dereferenced later. */
3572 static bool
3573 verify_constant (tree t, bool allow_non_constant, bool *non_constant_p,
3574 bool *overflow_p)
3576 if (!*non_constant_p && !reduced_constant_expression_p (t)
3577 && t != void_node)
3579 if (!allow_non_constant)
3581 auto_diagnostic_group d;
3582 error_at (cp_expr_loc_or_input_loc (t),
3583 "%q+E is not a constant expression", t);
3584 cp_walk_tree_without_duplicates (&t, verify_constant_explain_r,
3585 nullptr);
3587 *non_constant_p = true;
3589 if (TREE_OVERFLOW_P (t))
3591 if (!allow_non_constant)
3593 permerror (input_location, "overflow in constant expression");
3594 /* If we're being permissive (and are in an enforcing
3595 context), ignore the overflow. */
3596 if (flag_permissive)
3597 return *non_constant_p;
3599 *overflow_p = true;
3601 return *non_constant_p;
3604 /* Check whether the shift operation with code CODE and type TYPE on LHS
3605 and RHS is undefined. If it is, give an error with an explanation,
3606 and return true; return false otherwise. */
3608 static bool
3609 cxx_eval_check_shift_p (location_t loc, const constexpr_ctx *ctx,
3610 enum tree_code code, tree type, tree lhs, tree rhs)
3612 if ((code != LSHIFT_EXPR && code != RSHIFT_EXPR)
3613 || TREE_CODE (lhs) != INTEGER_CST
3614 || TREE_CODE (rhs) != INTEGER_CST)
3615 return false;
3617 tree lhstype = TREE_TYPE (lhs);
3618 unsigned HOST_WIDE_INT uprec = TYPE_PRECISION (TREE_TYPE (lhs));
3620 /* [expr.shift] The behavior is undefined if the right operand
3621 is negative, or greater than or equal to the length in bits
3622 of the promoted left operand. */
3623 if (tree_int_cst_sgn (rhs) == -1)
3625 if (!ctx->quiet)
3626 permerror (loc, "right operand of shift expression %q+E is negative",
3627 build2_loc (loc, code, type, lhs, rhs));
3628 return (!flag_permissive || ctx->quiet);
3630 if (compare_tree_int (rhs, uprec) >= 0)
3632 if (!ctx->quiet)
3633 permerror (loc, "right operand of shift expression %q+E is greater "
3634 "than or equal to the precision %wu of the left operand",
3635 build2_loc (loc, code, type, lhs, rhs), uprec);
3636 return (!flag_permissive || ctx->quiet);
3639 /* The value of E1 << E2 is E1 left-shifted E2 bit positions; [...]
3640 if E1 has a signed type and non-negative value, and E1x2^E2 is
3641 representable in the corresponding unsigned type of the result type,
3642 then that value, converted to the result type, is the resulting value;
3643 otherwise, the behavior is undefined.
3644 For C++20:
3645 The value of E1 << E2 is the unique value congruent to E1 x 2^E2 modulo
3646 2^N, where N is the range exponent of the type of the result. */
3647 if (code == LSHIFT_EXPR
3648 && !TYPE_OVERFLOW_WRAPS (lhstype)
3649 && cxx_dialect >= cxx11
3650 && cxx_dialect < cxx20)
3652 if (tree_int_cst_sgn (lhs) == -1)
3654 if (!ctx->quiet)
3655 permerror (loc,
3656 "left operand of shift expression %q+E is negative",
3657 build2_loc (loc, code, type, lhs, rhs));
3658 return (!flag_permissive || ctx->quiet);
3660 /* For signed x << y the following:
3661 (unsigned) x >> ((prec (lhs) - 1) - y)
3662 if > 1, is undefined. The right-hand side of this formula
3663 is the highest bit of the LHS that can be set (starting from 0),
3664 so that the shift doesn't overflow. We then right-shift the LHS
3665 to see whether any other bit is set making the original shift
3666 undefined -- the result is not representable in the corresponding
3667 unsigned type. */
3668 tree t = build_int_cst (unsigned_type_node, uprec - 1);
3669 t = fold_build2 (MINUS_EXPR, unsigned_type_node, t, rhs);
3670 tree ulhs = fold_convert (unsigned_type_for (lhstype), lhs);
3671 t = fold_build2 (RSHIFT_EXPR, TREE_TYPE (ulhs), ulhs, t);
3672 if (tree_int_cst_lt (integer_one_node, t))
3674 if (!ctx->quiet)
3675 permerror (loc, "shift expression %q+E overflows",
3676 build2_loc (loc, code, type, lhs, rhs));
3677 return (!flag_permissive || ctx->quiet);
3680 return false;
3683 /* Subroutine of cxx_eval_constant_expression.
3684 Attempt to reduce the unary expression tree T to a compile time value.
3685 If successful, return the value. Otherwise issue a diagnostic
3686 and return error_mark_node. */
3688 static tree
3689 cxx_eval_unary_expression (const constexpr_ctx *ctx, tree t,
3690 bool /*lval*/,
3691 bool *non_constant_p, bool *overflow_p)
3693 tree r;
3694 tree orig_arg = TREE_OPERAND (t, 0);
3695 tree arg = cxx_eval_constant_expression (ctx, orig_arg, vc_prvalue,
3696 non_constant_p, overflow_p);
3697 VERIFY_CONSTANT (arg);
3698 location_t loc = EXPR_LOCATION (t);
3699 enum tree_code code = TREE_CODE (t);
3700 tree type = TREE_TYPE (t);
3701 r = fold_unary_loc (loc, code, type, arg);
3702 if (r == NULL_TREE)
3704 if (arg == orig_arg)
3705 r = t;
3706 else
3707 r = build1_loc (loc, code, type, arg);
3709 VERIFY_CONSTANT (r);
3710 return r;
3713 /* Helper function for cxx_eval_binary_expression. Try to optimize
3714 original POINTER_PLUS_EXPR T, LHS p+ RHS, return NULL_TREE if the
3715 generic folding should be used. */
3717 static tree
3718 cxx_fold_pointer_plus_expression (const constexpr_ctx *ctx, tree t,
3719 tree lhs, tree rhs, bool *non_constant_p,
3720 bool *overflow_p)
3722 STRIP_NOPS (lhs);
3723 if (TREE_CODE (lhs) != ADDR_EXPR)
3724 return NULL_TREE;
3726 lhs = TREE_OPERAND (lhs, 0);
3728 /* &A[i] p+ j => &A[i + j] */
3729 if (TREE_CODE (lhs) == ARRAY_REF
3730 && TREE_CODE (TREE_OPERAND (lhs, 1)) == INTEGER_CST
3731 && TREE_CODE (rhs) == INTEGER_CST
3732 && TYPE_SIZE_UNIT (TREE_TYPE (lhs))
3733 && TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (lhs))) == INTEGER_CST)
3735 tree orig_type = TREE_TYPE (t);
3736 location_t loc = EXPR_LOCATION (t);
3737 tree type = TREE_TYPE (lhs);
3739 t = fold_convert_loc (loc, ssizetype, TREE_OPERAND (lhs, 1));
3740 tree nelts = array_type_nelts_top (TREE_TYPE (TREE_OPERAND (lhs, 0)));
3741 nelts = cxx_eval_constant_expression (ctx, nelts, vc_prvalue,
3742 non_constant_p, overflow_p);
3743 if (*non_constant_p)
3744 return NULL_TREE;
3745 /* Don't fold an out-of-bound access. */
3746 if (!tree_int_cst_le (t, nelts))
3747 return NULL_TREE;
3748 rhs = cp_fold_convert (ssizetype, rhs);
3749 /* Don't fold if rhs can't be divided exactly by TYPE_SIZE_UNIT.
3750 constexpr int A[1]; ... (char *)&A[0] + 1 */
3751 if (!integer_zerop (fold_build2_loc (loc, TRUNC_MOD_EXPR, sizetype,
3752 rhs, TYPE_SIZE_UNIT (type))))
3753 return NULL_TREE;
3754 /* Make sure to treat the second operand of POINTER_PLUS_EXPR
3755 as signed. */
3756 rhs = fold_build2_loc (loc, EXACT_DIV_EXPR, ssizetype, rhs,
3757 TYPE_SIZE_UNIT (type));
3758 t = size_binop_loc (loc, PLUS_EXPR, rhs, t);
3759 t = build4_loc (loc, ARRAY_REF, type, TREE_OPERAND (lhs, 0),
3760 t, NULL_TREE, NULL_TREE);
3761 t = cp_build_addr_expr (t, tf_warning_or_error);
3762 t = cp_fold_convert (orig_type, t);
3763 return cxx_eval_constant_expression (ctx, t, vc_prvalue,
3764 non_constant_p, overflow_p);
3767 return NULL_TREE;
3770 /* Try to fold expressions like
3771 (struct S *) (&a[0].D.2378 + 12)
3772 into
3773 &MEM <struct T> [(void *)&a + 12B]
3774 This is something normally done by gimple_fold_stmt_to_constant_1
3775 on GIMPLE, but is undesirable on GENERIC if we are e.g. going to
3776 dereference the address because some details are lost.
3777 For pointer comparisons we want such folding though so that
3778 match.pd address_compare optimization works. */
3780 static tree
3781 cxx_maybe_fold_addr_pointer_plus (tree t)
3783 while (CONVERT_EXPR_P (t)
3784 && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (t, 0))))
3785 t = TREE_OPERAND (t, 0);
3786 if (TREE_CODE (t) != POINTER_PLUS_EXPR)
3787 return NULL_TREE;
3788 tree op0 = TREE_OPERAND (t, 0);
3789 tree op1 = TREE_OPERAND (t, 1);
3790 if (TREE_CODE (op1) != INTEGER_CST)
3791 return NULL_TREE;
3792 while (CONVERT_EXPR_P (op0)
3793 && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (op0, 0))))
3794 op0 = TREE_OPERAND (op0, 0);
3795 if (TREE_CODE (op0) != ADDR_EXPR)
3796 return NULL_TREE;
3797 op1 = fold_convert (ptr_type_node, op1);
3798 tree r = fold_build2 (MEM_REF, TREE_TYPE (TREE_TYPE (op0)), op0, op1);
3799 return build1_loc (EXPR_LOCATION (t), ADDR_EXPR, TREE_TYPE (op0), r);
3802 /* Subroutine of cxx_eval_constant_expression.
3803 Like cxx_eval_unary_expression, except for binary expressions. */
3805 static tree
3806 cxx_eval_binary_expression (const constexpr_ctx *ctx, tree t,
3807 value_cat lval,
3808 bool *non_constant_p, bool *overflow_p)
3810 tree r = NULL_TREE;
3811 tree orig_lhs = TREE_OPERAND (t, 0);
3812 tree orig_rhs = TREE_OPERAND (t, 1);
3813 tree lhs, rhs;
3814 lhs = cxx_eval_constant_expression (ctx, orig_lhs, vc_prvalue,
3815 non_constant_p, overflow_p);
3816 /* Don't VERIFY_CONSTANT here, it's unnecessary and will break pointer
3817 subtraction. */
3818 if (*non_constant_p)
3819 return t;
3820 rhs = cxx_eval_constant_expression (ctx, orig_rhs, vc_prvalue,
3821 non_constant_p, overflow_p);
3822 if (*non_constant_p)
3823 return t;
3825 location_t loc = EXPR_LOCATION (t);
3826 enum tree_code code = TREE_CODE (t);
3827 tree type = TREE_TYPE (t);
3829 if (code == EQ_EXPR || code == NE_EXPR)
3831 bool is_code_eq = (code == EQ_EXPR);
3833 if (TREE_CODE (lhs) == PTRMEM_CST
3834 && TREE_CODE (rhs) == PTRMEM_CST)
3836 tree lmem = PTRMEM_CST_MEMBER (lhs);
3837 tree rmem = PTRMEM_CST_MEMBER (rhs);
3838 bool eq;
3839 if (TREE_CODE (lmem) == TREE_CODE (rmem)
3840 && TREE_CODE (lmem) == FIELD_DECL
3841 && TREE_CODE (DECL_CONTEXT (lmem)) == UNION_TYPE
3842 && same_type_p (DECL_CONTEXT (lmem),
3843 DECL_CONTEXT (rmem)))
3844 /* If both refer to (possibly different) members of the same union
3845 (12.3), they compare equal. */
3846 eq = true;
3847 else
3848 eq = cp_tree_equal (lhs, rhs);
3849 r = constant_boolean_node (eq == is_code_eq, type);
3851 else if ((TREE_CODE (lhs) == PTRMEM_CST
3852 || TREE_CODE (rhs) == PTRMEM_CST)
3853 && (null_member_pointer_value_p (lhs)
3854 || null_member_pointer_value_p (rhs)))
3855 r = constant_boolean_node (!is_code_eq, type);
3856 else if (TREE_CODE (lhs) == PTRMEM_CST)
3857 lhs = cplus_expand_constant (lhs);
3858 else if (TREE_CODE (rhs) == PTRMEM_CST)
3859 rhs = cplus_expand_constant (rhs);
3861 if (r == NULL_TREE
3862 && TREE_CODE_CLASS (code) == tcc_comparison
3863 && POINTER_TYPE_P (TREE_TYPE (lhs)))
3865 if (tree lhso = cxx_maybe_fold_addr_pointer_plus (lhs))
3866 lhs = fold_convert (TREE_TYPE (lhs), lhso);
3867 if (tree rhso = cxx_maybe_fold_addr_pointer_plus (rhs))
3868 rhs = fold_convert (TREE_TYPE (rhs), rhso);
3870 if (code == POINTER_PLUS_EXPR && !*non_constant_p
3871 && integer_zerop (lhs) && !integer_zerop (rhs))
3873 if (!ctx->quiet)
3874 error ("arithmetic involving a null pointer in %qE", lhs);
3875 *non_constant_p = true;
3876 return t;
3878 else if (code == POINTER_PLUS_EXPR)
3879 r = cxx_fold_pointer_plus_expression (ctx, t, lhs, rhs, non_constant_p,
3880 overflow_p);
3881 else if (code == SPACESHIP_EXPR)
3883 r = genericize_spaceship (loc, type, lhs, rhs);
3884 return cxx_eval_constant_expression (ctx, r, lval, non_constant_p,
3885 overflow_p);
3888 if (r == NULL_TREE)
3890 if (ctx->manifestly_const_eval == mce_true
3891 && (flag_constexpr_fp_except
3892 || TREE_CODE (type) != REAL_TYPE))
3894 auto ofcc = make_temp_override (folding_cxx_constexpr, true);
3895 r = fold_binary_initializer_loc (loc, code, type, lhs, rhs);
3897 else
3898 r = fold_binary_loc (loc, code, type, lhs, rhs);
3901 if (r == NULL_TREE
3902 && (code == LSHIFT_EXPR || code == RSHIFT_EXPR)
3903 && TREE_CODE (lhs) == INTEGER_CST
3904 && TREE_CODE (rhs) == INTEGER_CST
3905 && wi::neg_p (wi::to_wide (rhs)))
3907 /* For diagnostics and -fpermissive emulate previous behavior of
3908 handling shifts by negative amount. */
3909 tree nrhs = const_unop (NEGATE_EXPR, TREE_TYPE (rhs), rhs);
3910 if (nrhs)
3911 r = fold_binary_loc (loc,
3912 code == LSHIFT_EXPR ? RSHIFT_EXPR : LSHIFT_EXPR,
3913 type, lhs, nrhs);
3916 if (r == NULL_TREE)
3918 if (lhs == orig_lhs && rhs == orig_rhs)
3919 r = t;
3920 else
3921 r = build2_loc (loc, code, type, lhs, rhs);
3923 else if (cxx_eval_check_shift_p (loc, ctx, code, type, lhs, rhs))
3924 *non_constant_p = true;
3925 /* Don't VERIFY_CONSTANT if this might be dealing with a pointer to
3926 a local array in a constexpr function. */
3927 bool ptr = INDIRECT_TYPE_P (TREE_TYPE (lhs));
3928 if (!ptr)
3929 VERIFY_CONSTANT (r);
3930 return r;
3933 /* Subroutine of cxx_eval_constant_expression.
3934 Attempt to evaluate condition expressions. */
3936 static tree
3937 cxx_eval_conditional_expression (const constexpr_ctx *ctx, tree t,
3938 value_cat lval,
3939 bool *non_constant_p, bool *overflow_p,
3940 tree *jump_target)
3942 tree val = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
3943 vc_prvalue,
3944 non_constant_p, overflow_p);
3945 VERIFY_CONSTANT (val);
3946 if (TREE_CODE (t) == IF_STMT && IF_STMT_CONSTEVAL_P (t))
3948 /* Evaluate the condition as if it was
3949 if (__builtin_is_constant_evaluated ()), i.e. defer it if not
3950 ctx->manifestly_const_eval (as sometimes we try to constant evaluate
3951 without manifestly_const_eval even expressions or parts thereof which
3952 will later be manifestly const_eval evaluated), otherwise fold it to
3953 true. */
3954 if (ctx->manifestly_const_eval == mce_unknown)
3956 *non_constant_p = true;
3957 return t;
3959 val = constant_boolean_node (ctx->manifestly_const_eval == mce_true,
3960 boolean_type_node);
3962 /* Don't VERIFY_CONSTANT the other operands. */
3963 const bool zero_p = integer_zerop (val);
3964 if (zero_p)
3965 val = TREE_OPERAND (t, 2);
3966 else
3967 val = TREE_OPERAND (t, 1);
3968 if (TREE_CODE (t) == IF_STMT && !val)
3969 val = void_node;
3971 /* P2564: a subexpression of a manifestly constant-evaluated expression
3972 or conversion is an immediate function context. */
3973 if (ctx->manifestly_const_eval != mce_true
3974 && !in_immediate_context ()
3975 && cp_fold_immediate (&TREE_OPERAND (t, zero_p ? 1 : 2),
3976 ctx->manifestly_const_eval))
3978 *non_constant_p = true;
3979 return t;
3982 /* A TARGET_EXPR may be nested inside another TARGET_EXPR, but still
3983 serve as the initializer for the same object as the outer TARGET_EXPR,
3984 as in
3985 A a = true ? A{} : A{};
3986 so strip the inner TARGET_EXPR so we don't materialize a temporary. */
3987 if (TREE_CODE (val) == TARGET_EXPR)
3988 val = TARGET_EXPR_INITIAL (val);
3989 return cxx_eval_constant_expression (ctx, val, lval, non_constant_p,
3990 overflow_p, jump_target);
3993 /* Subroutine of cxx_eval_constant_expression.
3994 Attempt to evaluate vector condition expressions. Unlike
3995 cxx_eval_conditional_expression, VEC_COND_EXPR acts like a normal
3996 ternary arithmetics operation, where all 3 arguments have to be
3997 evaluated as constants and then folding computes the result from
3998 them. */
4000 static tree
4001 cxx_eval_vector_conditional_expression (const constexpr_ctx *ctx, tree t,
4002 bool *non_constant_p, bool *overflow_p)
4004 tree arg1 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
4005 vc_prvalue,
4006 non_constant_p, overflow_p);
4007 VERIFY_CONSTANT (arg1);
4008 tree arg2 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
4009 vc_prvalue,
4010 non_constant_p, overflow_p);
4011 VERIFY_CONSTANT (arg2);
4012 tree arg3 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 2),
4013 vc_prvalue,
4014 non_constant_p, overflow_p);
4015 VERIFY_CONSTANT (arg3);
4016 location_t loc = EXPR_LOCATION (t);
4017 tree type = TREE_TYPE (t);
4018 tree r = fold_ternary_loc (loc, VEC_COND_EXPR, type, arg1, arg2, arg3);
4019 if (r == NULL_TREE)
4021 if (arg1 == TREE_OPERAND (t, 0)
4022 && arg2 == TREE_OPERAND (t, 1)
4023 && arg3 == TREE_OPERAND (t, 2))
4024 r = t;
4025 else
4026 r = build3_loc (loc, VEC_COND_EXPR, type, arg1, arg2, arg3);
4028 VERIFY_CONSTANT (r);
4029 return r;
4032 /* Returns less than, equal to, or greater than zero if KEY is found to be
4033 less than, to match, or to be greater than the constructor_elt's INDEX. */
4035 static int
4036 array_index_cmp (tree key, tree index)
4038 gcc_assert (TREE_CODE (key) == INTEGER_CST);
4040 switch (TREE_CODE (index))
4042 case INTEGER_CST:
4043 return tree_int_cst_compare (key, index);
4044 case RANGE_EXPR:
4046 tree lo = TREE_OPERAND (index, 0);
4047 tree hi = TREE_OPERAND (index, 1);
4048 if (tree_int_cst_lt (key, lo))
4049 return -1;
4050 else if (tree_int_cst_lt (hi, key))
4051 return 1;
4052 else
4053 return 0;
4055 default:
4056 gcc_unreachable ();
4060 /* Returns the index of the constructor_elt of ARY which matches DINDEX, or -1
4061 if none. If INSERT is true, insert a matching element rather than fail. */
4063 static HOST_WIDE_INT
4064 find_array_ctor_elt (tree ary, tree dindex, bool insert)
4066 if (tree_int_cst_sgn (dindex) < 0)
4067 return -1;
4069 unsigned HOST_WIDE_INT i = tree_to_uhwi (dindex);
4070 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ary);
4071 unsigned HOST_WIDE_INT len = vec_safe_length (elts);
4073 unsigned HOST_WIDE_INT end = len;
4074 unsigned HOST_WIDE_INT begin = 0;
4076 /* If the last element of the CONSTRUCTOR has its own index, we can assume
4077 that the same is true of the other elements and index directly. */
4078 if (end > 0)
4080 tree cindex = (*elts)[end - 1].index;
4081 if (cindex == NULL_TREE)
4083 /* Verify that if the last index is missing, all indexes
4084 are missing. */
4085 if (flag_checking)
4086 for (unsigned int j = 0; j < len - 1; ++j)
4087 gcc_assert ((*elts)[j].index == NULL_TREE);
4088 if (i < end)
4089 return i;
4090 else
4092 begin = end;
4093 if (i == end)
4094 /* If the element is to be added right at the end,
4095 make sure it is added with cleared index too. */
4096 dindex = NULL_TREE;
4097 else if (insert)
4098 /* Otherwise, in order not to break the assumption
4099 that CONSTRUCTOR either has all indexes or none,
4100 we need to add indexes to all elements. */
4101 for (unsigned int j = 0; j < len; ++j)
4102 (*elts)[j].index = build_int_cst (TREE_TYPE (dindex), j);
4105 else if (TREE_CODE (cindex) == INTEGER_CST
4106 && compare_tree_int (cindex, end - 1) == 0)
4108 if (i < end)
4109 return i;
4110 else
4111 begin = end;
4115 /* Otherwise, find a matching index by means of a binary search. */
4116 while (begin != end)
4118 unsigned HOST_WIDE_INT middle = (begin + end) / 2;
4119 constructor_elt &elt = (*elts)[middle];
4120 tree idx = elt.index;
4122 int cmp = array_index_cmp (dindex, idx);
4123 if (cmp < 0)
4124 end = middle;
4125 else if (cmp > 0)
4126 begin = middle + 1;
4127 else
4129 if (insert && TREE_CODE (idx) == RANGE_EXPR)
4131 /* We need to split the range. */
4132 constructor_elt e;
4133 tree lo = TREE_OPERAND (idx, 0);
4134 tree hi = TREE_OPERAND (idx, 1);
4135 tree value = elt.value;
4136 dindex = fold_convert (sizetype, dindex);
4137 if (tree_int_cst_lt (lo, dindex))
4139 /* There are still some lower elts; shorten the range. */
4140 tree new_hi = int_const_binop (MINUS_EXPR, dindex,
4141 size_one_node);
4142 if (tree_int_cst_equal (lo, new_hi))
4143 /* Only one element left, no longer a range. */
4144 elt.index = lo;
4145 else
4146 TREE_OPERAND (idx, 1) = new_hi;
4147 /* Append the element we want to insert. */
4148 ++middle;
4149 e.index = dindex;
4150 e.value = unshare_constructor (value);
4151 vec_safe_insert (CONSTRUCTOR_ELTS (ary), middle, e);
4153 else
4154 /* No lower elts, the range elt is now ours. */
4155 elt.index = dindex;
4157 if (tree_int_cst_lt (dindex, hi))
4159 /* There are still some higher elts; append a range. */
4160 tree new_lo = int_const_binop (PLUS_EXPR, dindex,
4161 size_one_node);
4162 if (tree_int_cst_equal (new_lo, hi))
4163 e.index = hi;
4164 else
4165 e.index = build2 (RANGE_EXPR, sizetype, new_lo, hi);
4166 e.value = unshare_constructor (value);
4167 vec_safe_insert (CONSTRUCTOR_ELTS (ary), middle + 1, e);
4170 return middle;
4174 if (insert)
4176 constructor_elt e = { dindex, NULL_TREE };
4177 vec_safe_insert (CONSTRUCTOR_ELTS (ary), end, e);
4178 return end;
4181 return -1;
4184 /* Return a pointer to the constructor_elt of CTOR which matches INDEX. If no
4185 matching constructor_elt exists, then add one to CTOR.
4187 As an optimization, if POS_HINT is non-negative then it is used as a guess
4188 for the (integer) index of the matching constructor_elt within CTOR. */
4190 static constructor_elt *
4191 get_or_insert_ctor_field (tree ctor, tree index, int pos_hint = -1)
4193 /* Check the hint first. */
4194 if (pos_hint >= 0 && (unsigned)pos_hint < CONSTRUCTOR_NELTS (ctor)
4195 && CONSTRUCTOR_ELT (ctor, pos_hint)->index == index)
4196 return CONSTRUCTOR_ELT (ctor, pos_hint);
4198 tree type = TREE_TYPE (ctor);
4199 if (TREE_CODE (type) == VECTOR_TYPE && index == NULL_TREE)
4201 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (ctor), index, NULL_TREE);
4202 return &CONSTRUCTOR_ELTS (ctor)->last();
4204 else if (TREE_CODE (type) == ARRAY_TYPE || TREE_CODE (type) == VECTOR_TYPE)
4206 if (TREE_CODE (index) == RANGE_EXPR)
4208 /* Support for RANGE_EXPR index lookups is currently limited to
4209 accessing an existing element via POS_HINT, or appending a new
4210 element to the end of CTOR. ??? Support for other access
4211 patterns may also be needed. */
4212 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ctor);
4213 if (vec_safe_length (elts))
4215 tree lo = TREE_OPERAND (index, 0);
4216 gcc_assert (array_index_cmp (elts->last().index, lo) < 0);
4218 CONSTRUCTOR_APPEND_ELT (elts, index, NULL_TREE);
4219 return &elts->last();
4222 HOST_WIDE_INT i = find_array_ctor_elt (ctor, index, /*insert*/true);
4223 gcc_assert (i >= 0);
4224 constructor_elt *cep = CONSTRUCTOR_ELT (ctor, i);
4225 gcc_assert (cep->index == NULL_TREE
4226 || TREE_CODE (cep->index) != RANGE_EXPR);
4227 return cep;
4229 else
4231 gcc_assert (TREE_CODE (index) == FIELD_DECL
4232 && (same_type_ignoring_top_level_qualifiers_p
4233 (DECL_CONTEXT (index), TREE_TYPE (ctor))));
4235 /* We must keep the CONSTRUCTOR's ELTS in FIELD order.
4236 Usually we meet initializers in that order, but it is
4237 possible for base types to be placed not in program
4238 order. */
4239 tree fields = TYPE_FIELDS (DECL_CONTEXT (index));
4240 unsigned HOST_WIDE_INT idx = 0;
4241 constructor_elt *cep = NULL;
4243 /* Check if we're changing the active member of a union. */
4244 if (TREE_CODE (type) == UNION_TYPE && CONSTRUCTOR_NELTS (ctor)
4245 && CONSTRUCTOR_ELT (ctor, 0)->index != index)
4246 vec_safe_truncate (CONSTRUCTOR_ELTS (ctor), 0);
4247 /* If the bit offset of INDEX is larger than that of the last
4248 constructor_elt, then we can just immediately append a new
4249 constructor_elt to the end of CTOR. */
4250 else if (CONSTRUCTOR_NELTS (ctor)
4251 && tree_int_cst_compare (bit_position (index),
4252 bit_position (CONSTRUCTOR_ELTS (ctor)
4253 ->last().index)) > 0)
4255 idx = CONSTRUCTOR_NELTS (ctor);
4256 goto insert;
4259 /* Otherwise, we need to iterate over CTOR to find or insert INDEX
4260 appropriately. */
4262 for (; vec_safe_iterate (CONSTRUCTOR_ELTS (ctor), idx, &cep);
4263 idx++, fields = DECL_CHAIN (fields))
4265 if (index == cep->index)
4266 goto found;
4268 /* The field we're initializing must be on the field
4269 list. Look to see if it is present before the
4270 field the current ELT initializes. */
4271 for (; fields != cep->index; fields = DECL_CHAIN (fields))
4272 if (index == fields)
4273 goto insert;
4275 /* We fell off the end of the CONSTRUCTOR, so insert a new
4276 entry at the end. */
4278 insert:
4280 constructor_elt ce = { index, NULL_TREE };
4282 vec_safe_insert (CONSTRUCTOR_ELTS (ctor), idx, ce);
4283 cep = CONSTRUCTOR_ELT (ctor, idx);
4285 found:;
4287 return cep;
4291 /* Under the control of CTX, issue a detailed diagnostic for
4292 an out-of-bounds subscript INDEX into the expression ARRAY. */
4294 static void
4295 diag_array_subscript (location_t loc, const constexpr_ctx *ctx, tree array, tree index)
4297 if (!ctx->quiet)
4299 tree arraytype = TREE_TYPE (array);
4301 /* Convert the unsigned array subscript to a signed integer to avoid
4302 printing huge numbers for small negative values. */
4303 tree sidx = fold_convert (ssizetype, index);
4304 STRIP_ANY_LOCATION_WRAPPER (array);
4305 if (DECL_P (array))
4307 auto_diagnostic_group d;
4308 if (TYPE_DOMAIN (arraytype))
4309 error_at (loc, "array subscript value %qE is outside the bounds "
4310 "of array %qD of type %qT", sidx, array, arraytype);
4311 else
4312 error_at (loc, "nonzero array subscript %qE is used with array %qD of "
4313 "type %qT with unknown bounds", sidx, array, arraytype);
4314 inform (DECL_SOURCE_LOCATION (array), "declared here");
4316 else if (TYPE_DOMAIN (arraytype))
4317 error_at (loc, "array subscript value %qE is outside the bounds "
4318 "of array type %qT", sidx, arraytype);
4319 else
4320 error_at (loc, "nonzero array subscript %qE is used with array of type %qT "
4321 "with unknown bounds", sidx, arraytype);
4325 /* Return the number of elements for TYPE (which is an ARRAY_TYPE or
4326 a VECTOR_TYPE). */
4328 static tree
4329 get_array_or_vector_nelts (const constexpr_ctx *ctx, tree type,
4330 bool *non_constant_p, bool *overflow_p)
4332 tree nelts;
4333 if (TREE_CODE (type) == ARRAY_TYPE)
4335 if (TYPE_DOMAIN (type))
4336 nelts = array_type_nelts_top (type);
4337 else
4338 nelts = size_zero_node;
4340 else if (VECTOR_TYPE_P (type))
4341 nelts = size_int (TYPE_VECTOR_SUBPARTS (type));
4342 else
4343 gcc_unreachable ();
4345 /* For VLAs, the number of elements won't be an integer constant. */
4346 nelts = cxx_eval_constant_expression (ctx, nelts, vc_prvalue,
4347 non_constant_p, overflow_p);
4348 return nelts;
4351 /* Extract element INDEX consisting of CHARS_PER_ELT chars from
4352 STRING_CST STRING. */
4354 static tree
4355 extract_string_elt (tree string, unsigned chars_per_elt, unsigned index)
4357 tree type = cv_unqualified (TREE_TYPE (TREE_TYPE (string)));
4358 tree r;
4360 if (chars_per_elt == 1)
4361 r = build_int_cst (type, TREE_STRING_POINTER (string)[index]);
4362 else
4364 const unsigned char *ptr
4365 = ((const unsigned char *)TREE_STRING_POINTER (string)
4366 + index * chars_per_elt);
4367 r = native_interpret_expr (type, ptr, chars_per_elt);
4369 return r;
4372 /* Subroutine of cxx_eval_array_reference. T is an ARRAY_REF; evaluate the
4373 subscript, diagnose any problems with it, and return the result. */
4375 static tree
4376 eval_and_check_array_index (const constexpr_ctx *ctx,
4377 tree t, bool allow_one_past,
4378 bool *non_constant_p, bool *overflow_p)
4380 location_t loc = cp_expr_loc_or_input_loc (t);
4381 tree ary = TREE_OPERAND (t, 0);
4382 t = TREE_OPERAND (t, 1);
4383 tree index = cxx_eval_constant_expression (ctx, t, vc_prvalue,
4384 non_constant_p, overflow_p);
4385 VERIFY_CONSTANT (index);
4387 if (!tree_fits_shwi_p (index)
4388 || tree_int_cst_sgn (index) < 0)
4390 diag_array_subscript (loc, ctx, ary, index);
4391 *non_constant_p = true;
4392 return t;
4395 tree nelts = get_array_or_vector_nelts (ctx, TREE_TYPE (ary), non_constant_p,
4396 overflow_p);
4397 VERIFY_CONSTANT (nelts);
4398 if (allow_one_past
4399 ? !tree_int_cst_le (index, nelts)
4400 : !tree_int_cst_lt (index, nelts))
4402 diag_array_subscript (loc, ctx, ary, index);
4403 *non_constant_p = true;
4404 return t;
4407 return index;
4410 /* Subroutine of cxx_eval_constant_expression.
4411 Attempt to reduce a reference to an array slot. */
4413 static tree
4414 cxx_eval_array_reference (const constexpr_ctx *ctx, tree t,
4415 value_cat lval,
4416 bool *non_constant_p, bool *overflow_p)
4418 tree oldary = TREE_OPERAND (t, 0);
4419 tree ary = cxx_eval_constant_expression (ctx, oldary,
4420 lval,
4421 non_constant_p, overflow_p);
4422 if (*non_constant_p)
4423 return t;
4424 if (!lval
4425 && TREE_CODE (ary) == VIEW_CONVERT_EXPR
4426 && VECTOR_TYPE_P (TREE_TYPE (TREE_OPERAND (ary, 0)))
4427 && (TYPE_MAIN_VARIANT (TREE_TYPE (t))
4428 == TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (TREE_OPERAND (ary, 0))))))
4429 ary = TREE_OPERAND (ary, 0);
4431 tree oldidx = TREE_OPERAND (t, 1);
4432 tree index = eval_and_check_array_index (ctx, t, lval,
4433 non_constant_p, overflow_p);
4434 if (*non_constant_p)
4435 return t;
4437 if (lval && ary == oldary && index == oldidx)
4438 return t;
4439 else if (lval == vc_discard)
4440 return t;
4441 else if (lval)
4442 return build4 (ARRAY_REF, TREE_TYPE (t), ary, index, NULL, NULL);
4444 unsigned len = 0, elem_nchars = 1;
4445 tree elem_type = TREE_TYPE (TREE_TYPE (ary));
4446 if (TREE_CODE (ary) == CONSTRUCTOR)
4447 len = CONSTRUCTOR_NELTS (ary);
4448 else if (TREE_CODE (ary) == STRING_CST)
4450 elem_nchars = (TYPE_PRECISION (elem_type)
4451 / TYPE_PRECISION (char_type_node));
4452 len = (unsigned) TREE_STRING_LENGTH (ary) / elem_nchars;
4454 else if (TREE_CODE (ary) == VECTOR_CST)
4455 /* We don't create variable-length VECTOR_CSTs. */
4456 len = VECTOR_CST_NELTS (ary).to_constant ();
4457 else
4459 /* We can't do anything with other tree codes, so use
4460 VERIFY_CONSTANT to complain and fail. */
4461 VERIFY_CONSTANT (ary);
4462 gcc_unreachable ();
4465 bool found;
4466 HOST_WIDE_INT i = 0;
4467 if (TREE_CODE (ary) == CONSTRUCTOR)
4469 HOST_WIDE_INT ix = find_array_ctor_elt (ary, index);
4470 found = (ix >= 0);
4471 if (found)
4472 i = ix;
4474 else
4476 i = tree_to_shwi (index);
4477 found = (i < len);
4480 if (found)
4482 tree r;
4483 if (TREE_CODE (ary) == CONSTRUCTOR)
4484 r = (*CONSTRUCTOR_ELTS (ary))[i].value;
4485 else if (TREE_CODE (ary) == VECTOR_CST)
4486 r = VECTOR_CST_ELT (ary, i);
4487 else
4488 r = extract_string_elt (ary, elem_nchars, i);
4490 if (r)
4491 /* Don't VERIFY_CONSTANT here. */
4492 return r;
4494 /* Otherwise the element doesn't have a value yet. */
4497 /* Not found. */
4499 if (is_really_empty_class (elem_type, /*ignore_vptr*/false))
4500 return build_constructor (elem_type, NULL);
4502 if (TREE_CODE (ary) == CONSTRUCTOR
4503 && CONSTRUCTOR_NO_CLEARING (ary))
4505 /* 'ary' is part of the aggregate initializer we're currently
4506 building; if there's no initializer for this element yet,
4507 that's an error. */
4508 if (!ctx->quiet)
4509 error ("accessing uninitialized array element");
4510 *non_constant_p = true;
4511 return t;
4514 /* If it's within the array bounds but doesn't have an explicit
4515 initializer, it's initialized from {}. But use build_value_init
4516 directly for non-aggregates to avoid creating a garbage CONSTRUCTOR. */
4517 tree val;
4518 constexpr_ctx new_ctx;
4519 if (CP_AGGREGATE_TYPE_P (elem_type))
4521 tree empty_ctor = build_constructor (init_list_type_node, NULL);
4522 val = digest_init (elem_type, empty_ctor, tf_warning_or_error);
4524 else
4525 val = build_value_init (elem_type, tf_warning_or_error);
4527 /* Create a new constructor only if we don't already have a suitable one. */
4528 const bool new_ctor = (!SCALAR_TYPE_P (elem_type)
4529 && (!ctx->ctor
4530 || !same_type_ignoring_top_level_qualifiers_p
4531 (elem_type, TREE_TYPE (ctx->ctor))));
4532 if (new_ctor)
4534 new_ctx = *ctx;
4535 /* We clear the object here. We used to replace it with T, but that
4536 caused problems (101371, 108158); and anyway, T is the initializer,
4537 not the target object. */
4538 new_ctx.object = NULL_TREE;
4539 new_ctx.ctor = build_constructor (elem_type, NULL);
4540 ctx = &new_ctx;
4542 t = cxx_eval_constant_expression (ctx, val, lval, non_constant_p,
4543 overflow_p);
4544 if (new_ctor && t != ctx->ctor)
4545 free_constructor (ctx->ctor);
4546 return t;
4549 /* Subroutine of cxx_eval_constant_expression.
4550 Attempt to reduce a field access of a value of class type. */
4552 static tree
4553 cxx_eval_component_reference (const constexpr_ctx *ctx, tree t,
4554 value_cat lval,
4555 bool *non_constant_p, bool *overflow_p)
4557 unsigned HOST_WIDE_INT i;
4558 tree field;
4559 tree value;
4560 tree part = TREE_OPERAND (t, 1);
4561 tree orig_whole = TREE_OPERAND (t, 0);
4562 tree whole = cxx_eval_constant_expression (ctx, orig_whole,
4563 lval,
4564 non_constant_p, overflow_p);
4565 if (*non_constant_p)
4566 return t;
4567 if (INDIRECT_REF_P (whole)
4568 && integer_zerop (TREE_OPERAND (whole, 0)))
4570 if (!ctx->quiet)
4571 error ("dereferencing a null pointer in %qE", orig_whole);
4572 *non_constant_p = true;
4573 return t;
4576 if (TREE_CODE (whole) == PTRMEM_CST)
4577 whole = cplus_expand_constant (whole);
4578 if (whole == orig_whole)
4579 return t;
4580 if (lval == vc_discard)
4581 return t;
4582 if (lval)
4583 return fold_build3 (COMPONENT_REF, TREE_TYPE (t),
4584 whole, part, NULL_TREE);
4585 /* Don't VERIFY_CONSTANT here; we only want to check that we got a
4586 CONSTRUCTOR. */
4587 if (TREE_CODE (whole) != CONSTRUCTOR)
4589 if (!ctx->quiet)
4590 error ("%qE is not a constant expression", orig_whole);
4591 *non_constant_p = true;
4592 return t;
4594 if ((cxx_dialect < cxx14 || CONSTRUCTOR_MUTABLE_POISON (whole))
4595 && DECL_MUTABLE_P (part))
4597 if (!ctx->quiet)
4598 error ("mutable %qD is not usable in a constant expression", part);
4599 *non_constant_p = true;
4600 return t;
4603 bool pmf = TYPE_PTRMEMFUNC_P (TREE_TYPE (whole));
4604 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
4606 /* Use name match for PMF fields, as a variant will have a
4607 different FIELD_DECL with a different type. */
4608 if (pmf ? DECL_NAME (field) == DECL_NAME (part)
4609 : field == part)
4611 if (value)
4613 STRIP_ANY_LOCATION_WRAPPER (value);
4614 return value;
4616 else
4617 /* We're in the middle of initializing it. */
4618 break;
4621 if (TREE_CODE (TREE_TYPE (whole)) == UNION_TYPE)
4623 if (CONSTRUCTOR_NELTS (whole) > 0)
4625 /* DR 1188 says we don't have to deal with this. */
4626 if (!ctx->quiet)
4628 constructor_elt *cep = CONSTRUCTOR_ELT (whole, 0);
4629 if (cep->value == NULL_TREE)
4630 error ("accessing uninitialized member %qD", part);
4631 else
4632 error ("accessing %qD member instead of initialized %qD member "
4633 "in constant expression", part, cep->index);
4635 *non_constant_p = true;
4636 return t;
4638 else if (!CONSTRUCTOR_NO_CLEARING (whole))
4640 /* Value-initialized union, check if looking at the first member. */
4641 tree first = next_aggregate_field (TYPE_FIELDS (TREE_TYPE (whole)));
4642 if (first != part)
4644 if (!ctx->quiet)
4645 error ("accessing %qD member instead of initialized %qD "
4646 "member in constant expression", part, first);
4647 *non_constant_p = true;
4648 return t;
4653 /* We only create a CONSTRUCTOR for a subobject when we modify it, so empty
4654 classes never get represented; throw together a value now. */
4655 if (is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
4656 return build_constructor (TREE_TYPE (t), NULL);
4658 gcc_assert (DECL_CONTEXT (part) == TYPE_MAIN_VARIANT (TREE_TYPE (whole)));
4660 if (CONSTRUCTOR_NO_CLEARING (whole))
4662 /* 'whole' is part of the aggregate initializer we're currently
4663 building; if there's no initializer for this member yet, that's an
4664 error. */
4665 if (!ctx->quiet)
4666 error ("accessing uninitialized member %qD", part);
4667 *non_constant_p = true;
4668 return t;
4671 /* If there's no explicit init for this field, it's value-initialized. */
4672 value = build_value_init (TREE_TYPE (t), tf_warning_or_error);
4673 return cxx_eval_constant_expression (ctx, value,
4674 lval,
4675 non_constant_p, overflow_p);
4678 /* Subroutine of cxx_eval_constant_expression.
4679 Attempt to reduce a field access of a value of class type that is
4680 expressed as a BIT_FIELD_REF. */
4682 static tree
4683 cxx_eval_bit_field_ref (const constexpr_ctx *ctx, tree t,
4684 value_cat lval,
4685 bool *non_constant_p, bool *overflow_p)
4687 tree orig_whole = TREE_OPERAND (t, 0);
4688 tree retval, fldval, utype, mask;
4689 bool fld_seen = false;
4690 HOST_WIDE_INT istart, isize;
4691 tree whole = cxx_eval_constant_expression (ctx, orig_whole,
4692 lval,
4693 non_constant_p, overflow_p);
4694 tree start, field, value;
4695 unsigned HOST_WIDE_INT i;
4697 if (whole == orig_whole)
4698 return t;
4699 /* Don't VERIFY_CONSTANT here; we only want to check that we got a
4700 CONSTRUCTOR. */
4701 if (!*non_constant_p
4702 && TREE_CODE (whole) != VECTOR_CST
4703 && TREE_CODE (whole) != CONSTRUCTOR)
4705 if (!ctx->quiet)
4706 error ("%qE is not a constant expression", orig_whole);
4707 *non_constant_p = true;
4709 if (*non_constant_p)
4710 return t;
4712 if (TREE_CODE (whole) == VECTOR_CST || !INTEGRAL_TYPE_P (TREE_TYPE (t)))
4714 if (tree r = fold_ternary (BIT_FIELD_REF, TREE_TYPE (t), whole,
4715 TREE_OPERAND (t, 1), TREE_OPERAND (t, 2)))
4716 return r;
4717 if (!ctx->quiet)
4718 error ("%qE is not a constant expression", orig_whole);
4719 *non_constant_p = true;
4720 return t;
4723 start = TREE_OPERAND (t, 2);
4724 istart = tree_to_shwi (start);
4725 isize = tree_to_shwi (TREE_OPERAND (t, 1));
4726 utype = TREE_TYPE (t);
4727 if (!TYPE_UNSIGNED (utype))
4728 utype = build_nonstandard_integer_type (TYPE_PRECISION (utype), 1);
4729 retval = build_int_cst (utype, 0);
4730 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
4732 tree bitpos = bit_position (field);
4733 STRIP_ANY_LOCATION_WRAPPER (value);
4734 if (bitpos == start && DECL_SIZE (field) == TREE_OPERAND (t, 1))
4735 return value;
4736 if (TREE_CODE (TREE_TYPE (field)) == INTEGER_TYPE
4737 && TREE_CODE (value) == INTEGER_CST
4738 && tree_fits_shwi_p (bitpos)
4739 && tree_fits_shwi_p (DECL_SIZE (field)))
4741 HOST_WIDE_INT bit = tree_to_shwi (bitpos);
4742 HOST_WIDE_INT sz = tree_to_shwi (DECL_SIZE (field));
4743 HOST_WIDE_INT shift;
4744 if (bit >= istart && bit + sz <= istart + isize)
4746 fldval = fold_convert (utype, value);
4747 mask = build_int_cst_type (utype, -1);
4748 mask = fold_build2 (LSHIFT_EXPR, utype, mask,
4749 size_int (TYPE_PRECISION (utype) - sz));
4750 mask = fold_build2 (RSHIFT_EXPR, utype, mask,
4751 size_int (TYPE_PRECISION (utype) - sz));
4752 fldval = fold_build2 (BIT_AND_EXPR, utype, fldval, mask);
4753 shift = bit - istart;
4754 if (BYTES_BIG_ENDIAN)
4755 shift = TYPE_PRECISION (utype) - shift - sz;
4756 fldval = fold_build2 (LSHIFT_EXPR, utype, fldval,
4757 size_int (shift));
4758 retval = fold_build2 (BIT_IOR_EXPR, utype, retval, fldval);
4759 fld_seen = true;
4763 if (fld_seen)
4764 return fold_convert (TREE_TYPE (t), retval);
4765 gcc_unreachable ();
4766 return error_mark_node;
4769 /* Helper for cxx_eval_bit_cast.
4770 Check [bit.cast]/3 rules, bit_cast is constexpr only if the To and From
4771 types and types of all subobjects have is_union_v<T>, is_pointer_v<T>,
4772 is_member_pointer_v<T>, is_volatile_v<T> false and has no non-static
4773 data members of reference type. */
4775 static bool
4776 check_bit_cast_type (const constexpr_ctx *ctx, location_t loc, tree type,
4777 tree orig_type)
4779 if (TREE_CODE (type) == UNION_TYPE)
4781 if (!ctx->quiet)
4783 if (type == orig_type)
4784 error_at (loc, "%qs is not a constant expression because %qT is "
4785 "a union type", "__builtin_bit_cast", type);
4786 else
4787 error_at (loc, "%qs is not a constant expression because %qT "
4788 "contains a union type", "__builtin_bit_cast",
4789 orig_type);
4791 return true;
4793 if (TREE_CODE (type) == POINTER_TYPE)
4795 if (!ctx->quiet)
4797 if (type == orig_type)
4798 error_at (loc, "%qs is not a constant expression because %qT is "
4799 "a pointer type", "__builtin_bit_cast", type);
4800 else
4801 error_at (loc, "%qs is not a constant expression because %qT "
4802 "contains a pointer type", "__builtin_bit_cast",
4803 orig_type);
4805 return true;
4807 if (TREE_CODE (type) == REFERENCE_TYPE)
4809 if (!ctx->quiet)
4811 if (type == orig_type)
4812 error_at (loc, "%qs is not a constant expression because %qT is "
4813 "a reference type", "__builtin_bit_cast", type);
4814 else
4815 error_at (loc, "%qs is not a constant expression because %qT "
4816 "contains a reference type", "__builtin_bit_cast",
4817 orig_type);
4819 return true;
4821 if (TYPE_PTRMEM_P (type))
4823 if (!ctx->quiet)
4825 if (type == orig_type)
4826 error_at (loc, "%qs is not a constant expression because %qT is "
4827 "a pointer to member type", "__builtin_bit_cast",
4828 type);
4829 else
4830 error_at (loc, "%qs is not a constant expression because %qT "
4831 "contains a pointer to member type",
4832 "__builtin_bit_cast", orig_type);
4834 return true;
4836 if (TYPE_VOLATILE (type))
4838 if (!ctx->quiet)
4840 if (type == orig_type)
4841 error_at (loc, "%qs is not a constant expression because %qT is "
4842 "volatile", "__builtin_bit_cast", type);
4843 else
4844 error_at (loc, "%qs is not a constant expression because %qT "
4845 "contains a volatile subobject",
4846 "__builtin_bit_cast", orig_type);
4848 return true;
4850 if (TREE_CODE (type) == RECORD_TYPE)
4851 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
4852 if (TREE_CODE (field) == FIELD_DECL
4853 && check_bit_cast_type (ctx, loc, TREE_TYPE (field), orig_type))
4854 return true;
4855 if (TREE_CODE (type) == ARRAY_TYPE)
4856 return check_bit_cast_type (ctx, loc, TREE_TYPE (type), orig_type);
4857 return false;
4860 /* Helper function for cxx_eval_bit_cast. For unsigned char or
4861 std::byte members of CONSTRUCTOR (recursively) if they contain
4862 some indeterminate bits (as set in MASK), remove the ctor elts,
4863 mark the CONSTRUCTOR as CONSTRUCTOR_NO_CLEARING and clear the
4864 bits in MASK. */
4866 static void
4867 clear_uchar_or_std_byte_in_mask (location_t loc, tree t, unsigned char *mask)
4869 if (TREE_CODE (t) != CONSTRUCTOR)
4870 return;
4872 unsigned i, j = 0;
4873 tree index, value;
4874 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (t), i, index, value)
4876 tree type = TREE_TYPE (value);
4877 if (TREE_CODE (TREE_TYPE (t)) != ARRAY_TYPE
4878 && DECL_BIT_FIELD_TYPE (index) != NULL_TREE)
4880 if (is_byte_access_type_not_plain_char (DECL_BIT_FIELD_TYPE (index)))
4882 HOST_WIDE_INT fldsz = TYPE_PRECISION (TREE_TYPE (index));
4883 gcc_assert (fldsz != 0);
4884 HOST_WIDE_INT pos = int_byte_position (index);
4885 HOST_WIDE_INT bpos
4886 = tree_to_uhwi (DECL_FIELD_BIT_OFFSET (index));
4887 bpos %= BITS_PER_UNIT;
4888 HOST_WIDE_INT end
4889 = ROUND_UP (bpos + fldsz, BITS_PER_UNIT) / BITS_PER_UNIT;
4890 gcc_assert (end == 1 || end == 2);
4891 unsigned char *p = mask + pos;
4892 unsigned char mask_save[2];
4893 mask_save[0] = mask[pos];
4894 mask_save[1] = end == 2 ? mask[pos + 1] : 0;
4895 if (BYTES_BIG_ENDIAN != WORDS_BIG_ENDIAN)
4896 sorry_at (loc, "PDP11 bit-field handling unsupported"
4897 " in %qs", "__builtin_bit_cast");
4898 else if (BYTES_BIG_ENDIAN)
4900 /* Big endian. */
4901 if (bpos + fldsz <= BITS_PER_UNIT)
4902 *p &= ~(((1 << fldsz) - 1)
4903 << (BITS_PER_UNIT - bpos - fldsz));
4904 else
4906 gcc_assert (bpos);
4907 *p &= ~(((1U << BITS_PER_UNIT) - 1) >> bpos);
4908 p++;
4909 fldsz -= BITS_PER_UNIT - bpos;
4910 gcc_assert (fldsz && fldsz < BITS_PER_UNIT);
4911 *p &= ((1U << BITS_PER_UNIT) - 1) >> fldsz;
4914 else
4916 /* Little endian. */
4917 if (bpos + fldsz <= BITS_PER_UNIT)
4918 *p &= ~(((1 << fldsz) - 1) << bpos);
4919 else
4921 gcc_assert (bpos);
4922 *p &= ~(((1 << BITS_PER_UNIT) - 1) << bpos);
4923 p++;
4924 fldsz -= BITS_PER_UNIT - bpos;
4925 gcc_assert (fldsz && fldsz < BITS_PER_UNIT);
4926 *p &= ~((1 << fldsz) - 1);
4929 if (mask_save[0] != mask[pos]
4930 || (end == 2 && mask_save[1] != mask[pos + 1]))
4932 CONSTRUCTOR_NO_CLEARING (t) = 1;
4933 continue;
4937 else if (is_byte_access_type_not_plain_char (type))
4939 HOST_WIDE_INT pos;
4940 if (TREE_CODE (TREE_TYPE (t)) == ARRAY_TYPE)
4941 pos = tree_to_shwi (index);
4942 else
4943 pos = int_byte_position (index);
4944 if (mask[pos])
4946 CONSTRUCTOR_NO_CLEARING (t) = 1;
4947 mask[pos] = 0;
4948 continue;
4951 if (TREE_CODE (value) == CONSTRUCTOR)
4953 HOST_WIDE_INT pos;
4954 if (TREE_CODE (TREE_TYPE (t)) == ARRAY_TYPE)
4955 pos = tree_to_shwi (index)
4956 * tree_to_shwi (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (t))));
4957 else
4958 pos = int_byte_position (index);
4959 clear_uchar_or_std_byte_in_mask (loc, value, mask + pos);
4961 if (i != j)
4963 CONSTRUCTOR_ELT (t, j)->index = index;
4964 CONSTRUCTOR_ELT (t, j)->value = value;
4966 ++j;
4968 if (CONSTRUCTOR_NELTS (t) != j)
4969 vec_safe_truncate (CONSTRUCTOR_ELTS (t), j);
4972 /* Subroutine of cxx_eval_constant_expression.
4973 Attempt to evaluate a BIT_CAST_EXPR. */
4975 static tree
4976 cxx_eval_bit_cast (const constexpr_ctx *ctx, tree t, bool *non_constant_p,
4977 bool *overflow_p)
4979 if (check_bit_cast_type (ctx, EXPR_LOCATION (t), TREE_TYPE (t),
4980 TREE_TYPE (t))
4981 || check_bit_cast_type (ctx, cp_expr_loc_or_loc (TREE_OPERAND (t, 0),
4982 EXPR_LOCATION (t)),
4983 TREE_TYPE (TREE_OPERAND (t, 0)),
4984 TREE_TYPE (TREE_OPERAND (t, 0))))
4986 *non_constant_p = true;
4987 return t;
4990 tree op = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), vc_prvalue,
4991 non_constant_p, overflow_p);
4992 if (*non_constant_p)
4993 return t;
4995 location_t loc = EXPR_LOCATION (t);
4996 if (BITS_PER_UNIT != 8 || CHAR_BIT != 8)
4998 if (!ctx->quiet)
4999 sorry_at (loc, "%qs cannot be constant evaluated on the target",
5000 "__builtin_bit_cast");
5001 *non_constant_p = true;
5002 return t;
5005 if (!tree_fits_shwi_p (TYPE_SIZE_UNIT (TREE_TYPE (t))))
5007 if (!ctx->quiet)
5008 sorry_at (loc, "%qs cannot be constant evaluated because the "
5009 "type is too large", "__builtin_bit_cast");
5010 *non_constant_p = true;
5011 return t;
5014 HOST_WIDE_INT len = tree_to_shwi (TYPE_SIZE_UNIT (TREE_TYPE (t)));
5015 if (len < 0 || (int) len != len)
5017 if (!ctx->quiet)
5018 sorry_at (loc, "%qs cannot be constant evaluated because the "
5019 "type is too large", "__builtin_bit_cast");
5020 *non_constant_p = true;
5021 return t;
5024 unsigned char buf[64];
5025 unsigned char *ptr, *mask;
5026 size_t alen = (size_t) len * 2;
5027 if (alen <= sizeof (buf))
5028 ptr = buf;
5029 else
5030 ptr = XNEWVEC (unsigned char, alen);
5031 mask = ptr + (size_t) len;
5032 /* At the beginning consider everything indeterminate. */
5033 memset (mask, ~0, (size_t) len);
5035 if (native_encode_initializer (op, ptr, len, 0, mask) != len)
5037 if (!ctx->quiet)
5038 sorry_at (loc, "%qs cannot be constant evaluated because the "
5039 "argument cannot be encoded", "__builtin_bit_cast");
5040 *non_constant_p = true;
5041 if (ptr != buf)
5042 XDELETE (ptr);
5043 return t;
5046 tree r = NULL_TREE;
5047 if (can_native_interpret_type_p (TREE_TYPE (t)))
5049 r = native_interpret_expr (TREE_TYPE (t), ptr, len);
5050 if (is_byte_access_type_not_plain_char (TREE_TYPE (t)))
5052 gcc_assert (len == 1);
5053 if (mask[0])
5055 memset (mask, 0, len);
5056 r = build_constructor (TREE_TYPE (r), NULL);
5057 CONSTRUCTOR_NO_CLEARING (r) = 1;
5061 else if (TREE_CODE (TREE_TYPE (t)) == RECORD_TYPE)
5063 r = native_interpret_aggregate (TREE_TYPE (t), ptr, 0, len);
5064 if (r != NULL_TREE)
5066 clear_type_padding_in_mask (TREE_TYPE (t), mask);
5067 clear_uchar_or_std_byte_in_mask (loc, r, mask);
5068 if (CHECKING_P)
5070 tree e = cxx_eval_bare_aggregate (ctx, r, vc_prvalue,
5071 non_constant_p, overflow_p);
5072 gcc_checking_assert (e == r);
5073 r = e;
5078 if (r != NULL_TREE)
5080 for (int i = 0; i < len; i++)
5081 if (mask[i])
5083 if (!ctx->quiet)
5084 error_at (loc, "%qs accessing uninitialized byte at offset %d",
5085 "__builtin_bit_cast", i);
5086 *non_constant_p = true;
5087 r = t;
5088 break;
5090 if (ptr != buf)
5091 XDELETE (ptr);
5092 return r;
5095 if (!ctx->quiet)
5096 sorry_at (loc, "%qs cannot be constant evaluated because the "
5097 "argument cannot be interpreted", "__builtin_bit_cast");
5098 *non_constant_p = true;
5099 if (ptr != buf)
5100 XDELETE (ptr);
5101 return t;
5104 /* Subroutine of cxx_eval_constant_expression.
5105 Evaluate a short-circuited logical expression T in the context
5106 of a given constexpr CALL. BAILOUT_VALUE is the value for
5107 early return. CONTINUE_VALUE is used here purely for
5108 sanity check purposes. */
5110 static tree
5111 cxx_eval_logical_expression (const constexpr_ctx *ctx, tree t,
5112 tree bailout_value, tree continue_value,
5113 bool *non_constant_p, bool *overflow_p)
5115 tree r;
5116 tree lhs = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
5117 vc_prvalue, non_constant_p,
5118 overflow_p);
5119 VERIFY_CONSTANT (lhs);
5120 if (tree_int_cst_equal (lhs, bailout_value))
5121 return lhs;
5122 gcc_assert (tree_int_cst_equal (lhs, continue_value));
5123 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
5124 vc_prvalue, non_constant_p,
5125 overflow_p);
5126 VERIFY_CONSTANT (r);
5127 return r;
5130 /* REF is a COMPONENT_REF designating a particular field. V is a vector of
5131 CONSTRUCTOR elements to initialize (part of) an object containing that
5132 field. Return a pointer to the constructor_elt corresponding to the
5133 initialization of the field. */
5135 static constructor_elt *
5136 base_field_constructor_elt (vec<constructor_elt, va_gc> *v, tree ref)
5138 tree aggr = TREE_OPERAND (ref, 0);
5139 tree field = TREE_OPERAND (ref, 1);
5140 HOST_WIDE_INT i;
5141 constructor_elt *ce;
5143 gcc_assert (TREE_CODE (ref) == COMPONENT_REF);
5145 if (TREE_CODE (aggr) == COMPONENT_REF)
5147 constructor_elt *base_ce
5148 = base_field_constructor_elt (v, aggr);
5149 v = CONSTRUCTOR_ELTS (base_ce->value);
5152 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
5153 if (ce->index == field)
5154 return ce;
5156 gcc_unreachable ();
5157 return NULL;
5160 /* Some of the expressions fed to the constexpr mechanism are calls to
5161 constructors, which have type void. In that case, return the type being
5162 initialized by the constructor. */
5164 static tree
5165 initialized_type (tree t)
5167 if (TYPE_P (t))
5168 return t;
5169 tree type = TREE_TYPE (t);
5170 if (TREE_CODE (t) == CALL_EXPR)
5172 /* A constructor call has void type, so we need to look deeper. */
5173 tree fn = get_function_named_in_call (t);
5174 if (fn && TREE_CODE (fn) == FUNCTION_DECL
5175 && DECL_CXX_CONSTRUCTOR_P (fn))
5176 type = DECL_CONTEXT (fn);
5178 else if (TREE_CODE (t) == COMPOUND_EXPR)
5179 return initialized_type (TREE_OPERAND (t, 1));
5180 else if (TREE_CODE (t) == AGGR_INIT_EXPR)
5181 type = TREE_TYPE (AGGR_INIT_EXPR_SLOT (t));
5182 return cv_unqualified (type);
5185 /* We're about to initialize element INDEX of an array or class from VALUE.
5186 Set up NEW_CTX appropriately by adjusting .object to refer to the
5187 subobject and creating a new CONSTRUCTOR if the element is itself
5188 a class or array. */
5190 static void
5191 init_subob_ctx (const constexpr_ctx *ctx, constexpr_ctx &new_ctx,
5192 tree index, tree &value)
5194 new_ctx = *ctx;
5196 if (index && TREE_CODE (index) != INTEGER_CST
5197 && TREE_CODE (index) != FIELD_DECL
5198 && TREE_CODE (index) != RANGE_EXPR)
5199 /* This won't have an element in the new CONSTRUCTOR. */
5200 return;
5202 tree type = initialized_type (value);
5203 if (!AGGREGATE_TYPE_P (type) && !VECTOR_TYPE_P (type))
5204 /* A non-aggregate member doesn't get its own CONSTRUCTOR. */
5205 return;
5206 if (VECTOR_TYPE_P (type)
5207 && VECTOR_TYPE_P (TREE_TYPE (ctx->ctor))
5208 && index == NULL_TREE)
5209 /* A vector inside of a vector CONSTRUCTOR, e.g. when a larger
5210 vector is constructed from smaller vectors, doesn't get its own
5211 CONSTRUCTOR either. */
5212 return;
5214 /* The sub-aggregate initializer might contain a placeholder;
5215 update object to refer to the subobject and ctor to refer to
5216 the (newly created) sub-initializer. */
5217 if (ctx->object)
5219 if (index == NULL_TREE || TREE_CODE (index) == RANGE_EXPR)
5220 /* There's no well-defined subobject for this index. */
5221 new_ctx.object = NULL_TREE;
5222 else
5223 new_ctx.object = build_ctor_subob_ref (index, type, ctx->object);
5226 if (is_empty_class (type))
5227 /* Leave ctor null for an empty subobject, they aren't represented in the
5228 result of evaluation. */
5229 new_ctx.ctor = NULL_TREE;
5230 else
5232 tree elt = build_constructor (type, NULL);
5233 CONSTRUCTOR_NO_CLEARING (elt) = true;
5234 new_ctx.ctor = elt;
5237 if (TREE_CODE (value) == TARGET_EXPR)
5238 /* Avoid creating another CONSTRUCTOR when we expand the TARGET_EXPR. */
5239 value = TARGET_EXPR_INITIAL (value);
5242 /* We're about to process an initializer for a class or array TYPE. Make
5243 sure that CTX is set up appropriately. */
5245 static void
5246 verify_ctor_sanity (const constexpr_ctx *ctx, tree type)
5248 /* We don't bother building a ctor for an empty base subobject. */
5249 if (is_empty_class (type))
5250 return;
5252 /* We're in the middle of an initializer that might involve placeholders;
5253 our caller should have created a CONSTRUCTOR for us to put the
5254 initializer into. We will either return that constructor or T. */
5255 gcc_assert (ctx->ctor);
5256 gcc_assert (same_type_ignoring_top_level_qualifiers_p
5257 (type, TREE_TYPE (ctx->ctor)));
5258 /* We used to check that ctx->ctor was empty, but that isn't the case when
5259 the object is zero-initialized before calling the constructor. */
5260 if (ctx->object)
5262 tree otype = TREE_TYPE (ctx->object);
5263 gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, otype)
5264 /* Handle flexible array members. */
5265 || (TREE_CODE (otype) == ARRAY_TYPE
5266 && TYPE_DOMAIN (otype) == NULL_TREE
5267 && TREE_CODE (type) == ARRAY_TYPE
5268 && (same_type_ignoring_top_level_qualifiers_p
5269 (TREE_TYPE (type), TREE_TYPE (otype)))));
5271 gcc_assert (!ctx->object || !DECL_P (ctx->object)
5272 || ctx->global->get_value (ctx->object) == ctx->ctor);
5275 /* Subroutine of cxx_eval_constant_expression.
5276 The expression tree T denotes a C-style array or a C-style
5277 aggregate. Reduce it to a constant expression. */
5279 static tree
5280 cxx_eval_bare_aggregate (const constexpr_ctx *ctx, tree t,
5281 value_cat lval,
5282 bool *non_constant_p, bool *overflow_p)
5284 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
5285 bool changed = false;
5286 gcc_assert (!BRACE_ENCLOSED_INITIALIZER_P (t));
5287 tree type = TREE_TYPE (t);
5289 constexpr_ctx new_ctx;
5290 if (TYPE_PTRMEMFUNC_P (type) || VECTOR_TYPE_P (type))
5292 /* We don't really need the ctx->ctor business for a PMF or
5293 vector, but it's simpler to use the same code. */
5294 new_ctx = *ctx;
5295 new_ctx.ctor = build_constructor (type, NULL);
5296 new_ctx.object = NULL_TREE;
5297 ctx = &new_ctx;
5299 verify_ctor_sanity (ctx, type);
5300 vec<constructor_elt, va_gc> **p = nullptr;
5301 if (ctx->ctor)
5303 p = &CONSTRUCTOR_ELTS (ctx->ctor);
5304 vec_alloc (*p, vec_safe_length (v));
5305 if (CONSTRUCTOR_PLACEHOLDER_BOUNDARY (t))
5306 CONSTRUCTOR_PLACEHOLDER_BOUNDARY (ctx->ctor) = 1;
5309 unsigned i;
5310 tree index, value;
5311 bool constant_p = true;
5312 bool side_effects_p = false;
5313 FOR_EACH_CONSTRUCTOR_ELT (v, i, index, value)
5315 tree orig_value = value;
5316 init_subob_ctx (ctx, new_ctx, index, value);
5317 /* Like in cxx_eval_store_expression, omit entries for empty fields. */
5318 bool no_slot = new_ctx.ctor == NULL_TREE;
5319 int pos_hint = -1;
5320 if (new_ctx.ctor != ctx->ctor && !no_slot)
5322 /* If we built a new CONSTRUCTOR, attach it now so that other
5323 initializers can refer to it. */
5324 constructor_elt *cep = get_or_insert_ctor_field (ctx->ctor, index);
5325 cep->value = new_ctx.ctor;
5326 pos_hint = cep - (*p)->begin();
5328 else if (TREE_CODE (type) == UNION_TYPE)
5329 /* Otherwise if we're constructing a non-aggregate union member, set
5330 the active union member now so that we can later detect and diagnose
5331 if its initializer attempts to activate another member. */
5332 get_or_insert_ctor_field (ctx->ctor, index);
5333 tree elt = cxx_eval_constant_expression (&new_ctx, value,
5334 lval,
5335 non_constant_p, overflow_p);
5336 /* Don't VERIFY_CONSTANT here. */
5337 if (ctx->quiet && *non_constant_p)
5338 break;
5339 if (elt != orig_value)
5340 changed = true;
5342 if (!TREE_CONSTANT (elt))
5343 constant_p = false;
5344 if (TREE_SIDE_EFFECTS (elt))
5345 side_effects_p = true;
5346 if (index && TREE_CODE (index) == COMPONENT_REF)
5348 /* This is an initialization of a vfield inside a base
5349 subaggregate that we already initialized; push this
5350 initialization into the previous initialization. */
5351 constructor_elt *inner = base_field_constructor_elt (*p, index);
5352 inner->value = elt;
5353 changed = true;
5355 else if (no_slot)
5356 /* This is an initializer for an empty field; now that we've
5357 checked that it's constant, we can ignore it. */
5358 changed = true;
5359 else if (index
5360 && (TREE_CODE (index) == NOP_EXPR
5361 || TREE_CODE (index) == POINTER_PLUS_EXPR))
5363 /* Old representation of empty bases. FIXME remove. */
5364 gcc_checking_assert (false);
5365 gcc_assert (is_empty_class (TREE_TYPE (TREE_TYPE (index))));
5366 changed = true;
5368 else
5370 if (TREE_CODE (type) == UNION_TYPE
5371 && (*p)->last().index != index)
5372 /* The initializer erroneously changed the active union member that
5373 we're initializing. */
5374 gcc_assert (*non_constant_p);
5375 else
5377 /* The initializer might have mutated the underlying CONSTRUCTOR,
5378 so recompute the location of the target constructer_elt. */
5379 constructor_elt *cep
5380 = get_or_insert_ctor_field (ctx->ctor, index, pos_hint);
5381 cep->value = elt;
5384 /* Adding or replacing an element might change the ctor's flags. */
5385 TREE_CONSTANT (ctx->ctor) = constant_p;
5386 TREE_SIDE_EFFECTS (ctx->ctor) = side_effects_p;
5389 if (*non_constant_p)
5390 return t;
5391 if (!changed)
5393 if (VECTOR_TYPE_P (type))
5394 t = fold (t);
5395 return t;
5397 t = ctx->ctor;
5398 if (!t)
5399 t = build_constructor (type, NULL);
5400 /* We're done building this CONSTRUCTOR, so now we can interpret an
5401 element without an explicit initializer as value-initialized. */
5402 CONSTRUCTOR_NO_CLEARING (t) = false;
5403 TREE_CONSTANT (t) = constant_p;
5404 TREE_SIDE_EFFECTS (t) = side_effects_p;
5405 if (VECTOR_TYPE_P (type))
5406 t = fold (t);
5407 return t;
5410 /* Subroutine of cxx_eval_constant_expression.
5411 The expression tree T is a VEC_INIT_EXPR which denotes the desired
5412 initialization of a non-static data member of array type. Reduce it to a
5413 CONSTRUCTOR.
5415 Note that apart from value-initialization (when VALUE_INIT is true),
5416 this is only intended to support value-initialization and the
5417 initializations done by defaulted constructors for classes with
5418 non-static data members of array type. In this case, VEC_INIT_EXPR_INIT
5419 will either be NULL_TREE for the default constructor, or a COMPONENT_REF
5420 for the copy/move constructor. */
5422 static tree
5423 cxx_eval_vec_init_1 (const constexpr_ctx *ctx, tree atype, tree init,
5424 bool value_init, value_cat lval,
5425 bool *non_constant_p, bool *overflow_p)
5427 tree elttype = TREE_TYPE (atype);
5428 verify_ctor_sanity (ctx, atype);
5429 vec<constructor_elt, va_gc> **p = &CONSTRUCTOR_ELTS (ctx->ctor);
5430 bool pre_init = false;
5431 unsigned HOST_WIDE_INT i;
5432 tsubst_flags_t complain = ctx->quiet ? tf_none : tf_warning_or_error;
5434 if (init && TREE_CODE (init) == CONSTRUCTOR)
5435 return cxx_eval_bare_aggregate (ctx, init, lval,
5436 non_constant_p, overflow_p);
5438 /* For the default constructor, build up a call to the default
5439 constructor of the element type. We only need to handle class types
5440 here, as for a constructor to be constexpr, all members must be
5441 initialized, which for a defaulted default constructor means they must
5442 be of a class type with a constexpr default constructor. */
5443 if (TREE_CODE (elttype) == ARRAY_TYPE)
5444 /* We only do this at the lowest level. */;
5445 else if (value_init)
5447 init = build_value_init (elttype, complain);
5448 pre_init = true;
5450 else if (!init)
5452 releasing_vec argvec;
5453 init = build_special_member_call (NULL_TREE, complete_ctor_identifier,
5454 &argvec, elttype, LOOKUP_NORMAL,
5455 complain);
5456 init = build_aggr_init_expr (elttype, init);
5457 pre_init = true;
5460 bool zeroed_out = false;
5461 if (!CONSTRUCTOR_NO_CLEARING (ctx->ctor))
5463 /* We're initializing an array object that had been zero-initialized
5464 earlier. Truncate ctx->ctor, and propagate its zeroed state by
5465 clearing CONSTRUCTOR_NO_CLEARING on each of the aggregate element
5466 initializers we append to it. */
5467 gcc_checking_assert (initializer_zerop (ctx->ctor));
5468 zeroed_out = true;
5469 vec_safe_truncate (*p, 0);
5472 tree nelts = get_array_or_vector_nelts (ctx, atype, non_constant_p,
5473 overflow_p);
5474 unsigned HOST_WIDE_INT max = tree_to_uhwi (nelts);
5475 for (i = 0; i < max; ++i)
5477 tree idx = build_int_cst (size_type_node, i);
5478 tree eltinit;
5479 bool reuse = false;
5480 constexpr_ctx new_ctx;
5481 init_subob_ctx (ctx, new_ctx, idx, pre_init ? init : elttype);
5482 bool no_slot = new_ctx.ctor == NULL_TREE;
5483 if (new_ctx.ctor != ctx->ctor && !no_slot)
5485 if (zeroed_out)
5486 CONSTRUCTOR_NO_CLEARING (new_ctx.ctor) = false;
5487 CONSTRUCTOR_APPEND_ELT (*p, idx, new_ctx.ctor);
5489 if (TREE_CODE (elttype) == ARRAY_TYPE)
5491 /* A multidimensional array; recurse. */
5492 if (value_init || init == NULL_TREE)
5494 eltinit = NULL_TREE;
5495 reuse = i == 0;
5497 else
5498 eltinit = cp_build_array_ref (input_location, init, idx, complain);
5499 eltinit = cxx_eval_vec_init_1 (&new_ctx, elttype, eltinit, value_init,
5500 lval,
5501 non_constant_p, overflow_p);
5503 else if (pre_init)
5505 /* Initializing an element using value or default initialization
5506 we just pre-built above. */
5507 if (init == void_node)
5508 /* Trivial default-init, don't do anything to the CONSTRUCTOR. */
5509 return ctx->ctor;
5510 eltinit = cxx_eval_constant_expression (&new_ctx, init, lval,
5511 non_constant_p, overflow_p);
5512 reuse = i == 0;
5514 else
5516 /* Copying an element. */
5517 eltinit = cp_build_array_ref (input_location, init, idx, complain);
5518 if (!lvalue_p (init))
5519 eltinit = move (eltinit);
5520 eltinit = (perform_implicit_conversion_flags
5521 (elttype, eltinit, complain,
5522 LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING));
5523 eltinit = cxx_eval_constant_expression (&new_ctx, eltinit, lval,
5524 non_constant_p, overflow_p);
5526 if (*non_constant_p)
5527 break;
5528 if (no_slot)
5530 /* This is an initializer for an empty subobject; now that we've
5531 checked that it's constant, we can ignore it. */
5532 gcc_checking_assert (i == 0);
5533 break;
5535 else if (new_ctx.ctor != ctx->ctor)
5537 /* We appended this element above; update the value. */
5538 gcc_assert ((*p)->last().index == idx);
5539 (*p)->last().value = eltinit;
5541 else
5542 CONSTRUCTOR_APPEND_ELT (*p, idx, eltinit);
5543 /* Reuse the result of cxx_eval_constant_expression call
5544 from the first iteration to all others if it is a constant
5545 initializer that doesn't require relocations. */
5546 if (reuse
5547 && max > 1
5548 && (eltinit == NULL_TREE
5549 || (initializer_constant_valid_p (eltinit, TREE_TYPE (eltinit))
5550 == null_pointer_node)))
5552 if (new_ctx.ctor != ctx->ctor)
5553 eltinit = new_ctx.ctor;
5554 tree range = build2 (RANGE_EXPR, size_type_node,
5555 build_int_cst (size_type_node, 1),
5556 build_int_cst (size_type_node, max - 1));
5557 CONSTRUCTOR_APPEND_ELT (*p, range, unshare_constructor (eltinit));
5558 break;
5560 else if (i == 0)
5561 vec_safe_reserve (*p, max);
5564 if (!*non_constant_p)
5566 init = ctx->ctor;
5567 CONSTRUCTOR_NO_CLEARING (init) = false;
5569 return init;
5572 static tree
5573 cxx_eval_vec_init (const constexpr_ctx *ctx, tree t,
5574 value_cat lval,
5575 bool *non_constant_p, bool *overflow_p)
5577 tree atype = TREE_TYPE (t);
5578 tree init = VEC_INIT_EXPR_INIT (t);
5579 bool value_init = VEC_INIT_EXPR_VALUE_INIT (t);
5580 if (!init || !BRACE_ENCLOSED_INITIALIZER_P (init))
5582 else if (CONSTRUCTOR_NELTS (init) == 0
5583 && !CP_AGGREGATE_TYPE_P (strip_array_types (atype)))
5585 /* Handle {} as value-init. */
5586 init = NULL_TREE;
5587 value_init = true;
5589 else
5591 /* This is a more complicated case, like needing to loop over trailing
5592 elements; call build_vec_init and evaluate the result. */
5593 tsubst_flags_t complain = ctx->quiet ? tf_none : tf_warning_or_error;
5594 constexpr_ctx new_ctx = *ctx;
5595 if (!ctx->object)
5597 /* We want to have an initialization target for an VEC_INIT_EXPR.
5598 If we don't already have one in CTX, use the VEC_INIT_EXPR_SLOT. */
5599 new_ctx.object = VEC_INIT_EXPR_SLOT (t);
5600 tree ctor = new_ctx.ctor = build_constructor (atype, NULL);
5601 CONSTRUCTOR_NO_CLEARING (ctor) = true;
5602 ctx->global->put_value (new_ctx.object, ctor);
5603 ctx = &new_ctx;
5605 init = expand_vec_init_expr (ctx->object, t, complain);
5606 return cxx_eval_constant_expression (ctx, init, lval, non_constant_p,
5607 overflow_p);
5609 tree r = cxx_eval_vec_init_1 (ctx, atype, init, value_init,
5610 lval, non_constant_p, overflow_p);
5611 if (*non_constant_p)
5612 return t;
5613 else
5614 return r;
5617 /* Like same_type_ignoring_top_level_qualifiers_p, but also handle the case
5618 where the desired type is an array of unknown bounds because the variable
5619 has had its bounds deduced since the wrapping expression was created. */
5621 static bool
5622 same_type_ignoring_tlq_and_bounds_p (tree type1, tree type2)
5624 while (TREE_CODE (type1) == ARRAY_TYPE
5625 && TREE_CODE (type2) == ARRAY_TYPE
5626 && (!TYPE_DOMAIN (type1) || !TYPE_DOMAIN (type2)))
5628 type1 = TREE_TYPE (type1);
5629 type2 = TREE_TYPE (type2);
5631 return same_type_ignoring_top_level_qualifiers_p (type1, type2);
5634 /* Try to determine the currently active union member for an expression
5635 with UNION_TYPE. If it can be determined, return the FIELD_DECL,
5636 otherwise return NULL_TREE. */
5638 static tree
5639 cxx_union_active_member (const constexpr_ctx *ctx, tree t)
5641 constexpr_ctx new_ctx = *ctx;
5642 new_ctx.quiet = true;
5643 bool non_constant_p = false, overflow_p = false;
5644 tree ctor = cxx_eval_constant_expression (&new_ctx, t, vc_prvalue,
5645 &non_constant_p,
5646 &overflow_p);
5647 if (TREE_CODE (ctor) == CONSTRUCTOR
5648 && CONSTRUCTOR_NELTS (ctor) == 1
5649 && CONSTRUCTOR_ELT (ctor, 0)->index
5650 && TREE_CODE (CONSTRUCTOR_ELT (ctor, 0)->index) == FIELD_DECL)
5651 return CONSTRUCTOR_ELT (ctor, 0)->index;
5652 return NULL_TREE;
5655 /* Helper function for cxx_fold_indirect_ref_1, called recursively. */
5657 static tree
5658 cxx_fold_indirect_ref_1 (const constexpr_ctx *ctx, location_t loc, tree type,
5659 tree op, unsigned HOST_WIDE_INT off, bool *empty_base)
5661 tree optype = TREE_TYPE (op);
5662 unsigned HOST_WIDE_INT const_nunits;
5663 if (off == 0 && similar_type_p (optype, type))
5664 return op;
5665 else if (TREE_CODE (optype) == COMPLEX_TYPE
5666 && similar_type_p (type, TREE_TYPE (optype)))
5668 /* *(foo *)&complexfoo => __real__ complexfoo */
5669 if (off == 0)
5670 return build1_loc (loc, REALPART_EXPR, type, op);
5671 /* ((foo*)&complexfoo)[1] => __imag__ complexfoo */
5672 else if (tree_to_uhwi (TYPE_SIZE_UNIT (type)) == off)
5673 return build1_loc (loc, IMAGPART_EXPR, type, op);
5675 /* ((foo*)&vectorfoo)[x] => BIT_FIELD_REF<vectorfoo,...> */
5676 else if (VECTOR_TYPE_P (optype)
5677 && similar_type_p (type, TREE_TYPE (optype))
5678 && TYPE_VECTOR_SUBPARTS (optype).is_constant (&const_nunits))
5680 unsigned HOST_WIDE_INT part_width = tree_to_uhwi (TYPE_SIZE_UNIT (type));
5681 unsigned HOST_WIDE_INT max_offset = part_width * const_nunits;
5682 if (off < max_offset && off % part_width == 0)
5684 tree index = bitsize_int (off * BITS_PER_UNIT);
5685 return build3_loc (loc, BIT_FIELD_REF, type, op,
5686 TYPE_SIZE (type), index);
5689 /* ((foo *)&fooarray)[x] => fooarray[x] */
5690 else if (TREE_CODE (optype) == ARRAY_TYPE
5691 && tree_fits_uhwi_p (TYPE_SIZE_UNIT (TREE_TYPE (optype)))
5692 && !integer_zerop (TYPE_SIZE_UNIT (TREE_TYPE (optype))))
5694 tree type_domain = TYPE_DOMAIN (optype);
5695 tree min_val = size_zero_node;
5696 if (type_domain && TYPE_MIN_VALUE (type_domain))
5697 min_val = TYPE_MIN_VALUE (type_domain);
5698 unsigned HOST_WIDE_INT el_sz
5699 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (optype)));
5700 unsigned HOST_WIDE_INT idx = off / el_sz;
5701 unsigned HOST_WIDE_INT rem = off % el_sz;
5702 if (tree_fits_uhwi_p (min_val))
5704 tree index = size_int (idx + tree_to_uhwi (min_val));
5705 op = build4_loc (loc, ARRAY_REF, TREE_TYPE (optype), op, index,
5706 NULL_TREE, NULL_TREE);
5707 return cxx_fold_indirect_ref_1 (ctx, loc, type, op, rem,
5708 empty_base);
5711 /* ((foo *)&struct_with_foo_field)[x] => COMPONENT_REF */
5712 else if (TREE_CODE (optype) == RECORD_TYPE
5713 || TREE_CODE (optype) == UNION_TYPE)
5715 if (TREE_CODE (optype) == UNION_TYPE)
5716 /* For unions prefer the currently active member. */
5717 if (tree field = cxx_union_active_member (ctx, op))
5719 unsigned HOST_WIDE_INT el_sz
5720 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (field)));
5721 if (off < el_sz)
5723 tree cop = build3 (COMPONENT_REF, TREE_TYPE (field),
5724 op, field, NULL_TREE);
5725 if (tree ret = cxx_fold_indirect_ref_1 (ctx, loc, type, cop,
5726 off, empty_base))
5727 return ret;
5731 /* Handle conversion to "as base" type. */
5732 if (CLASS_TYPE_P (optype)
5733 && CLASSTYPE_AS_BASE (optype) == type)
5734 return op;
5736 /* Handle conversion to an empty base class, which is represented with a
5737 NOP_EXPR. Do this before spelunking into the non-empty subobjects,
5738 which is likely to be a waste of time (109678). */
5739 if (is_empty_class (type)
5740 && CLASS_TYPE_P (optype)
5741 && lookup_base (optype, type, ba_any, NULL, tf_none, off))
5743 if (empty_base)
5744 *empty_base = true;
5745 return op;
5748 for (tree field = TYPE_FIELDS (optype);
5749 field; field = DECL_CHAIN (field))
5750 if (TREE_CODE (field) == FIELD_DECL
5751 && TREE_TYPE (field) != error_mark_node
5752 && tree_fits_uhwi_p (TYPE_SIZE_UNIT (TREE_TYPE (field))))
5754 tree pos = byte_position (field);
5755 if (!tree_fits_uhwi_p (pos))
5756 continue;
5757 unsigned HOST_WIDE_INT upos = tree_to_uhwi (pos);
5758 unsigned HOST_WIDE_INT el_sz
5759 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (field)));
5760 if (upos <= off && off < upos + el_sz)
5762 tree cop = build3 (COMPONENT_REF, TREE_TYPE (field),
5763 op, field, NULL_TREE);
5764 if (tree ret = cxx_fold_indirect_ref_1 (ctx, loc, type, cop,
5765 off - upos,
5766 empty_base))
5767 return ret;
5772 return NULL_TREE;
5775 /* A less strict version of fold_indirect_ref_1, which requires cv-quals to
5776 match. We want to be less strict for simple *& folding; if we have a
5777 non-const temporary that we access through a const pointer, that should
5778 work. We handle this here rather than change fold_indirect_ref_1
5779 because we're dealing with things like ADDR_EXPR of INTEGER_CST which
5780 don't really make sense outside of constant expression evaluation. Also
5781 we want to allow folding to COMPONENT_REF, which could cause trouble
5782 with TBAA in fold_indirect_ref_1. */
5784 static tree
5785 cxx_fold_indirect_ref (const constexpr_ctx *ctx, location_t loc, tree type,
5786 tree op0, bool *empty_base /* = NULL*/)
5788 tree sub = op0;
5789 tree subtype;
5791 /* STRIP_NOPS, but stop if REINTERPRET_CAST_P. */
5792 while (CONVERT_EXPR_P (sub) || TREE_CODE (sub) == NON_LVALUE_EXPR
5793 || TREE_CODE (sub) == VIEW_CONVERT_EXPR)
5795 if (TREE_CODE (sub) == NOP_EXPR
5796 && REINTERPRET_CAST_P (sub))
5797 return NULL_TREE;
5798 sub = TREE_OPERAND (sub, 0);
5801 subtype = TREE_TYPE (sub);
5802 if (!INDIRECT_TYPE_P (subtype))
5803 return NULL_TREE;
5805 /* Canonicalizes the given OBJ/OFF pair by iteratively absorbing
5806 the innermost component into the offset until it would make the
5807 offset positive, so that cxx_fold_indirect_ref_1 can identify
5808 more folding opportunities. */
5809 auto canonicalize_obj_off = [] (tree& obj, tree& off) {
5810 while (TREE_CODE (obj) == COMPONENT_REF
5811 /* We need to preserve union member accesses so that we can
5812 later properly diagnose accessing the wrong member. */
5813 && TREE_CODE (TREE_TYPE (TREE_OPERAND (obj, 0))) == RECORD_TYPE
5814 && (tree_int_cst_sign_bit (off) || integer_zerop (off)))
5816 tree field = TREE_OPERAND (obj, 1);
5817 tree pos = byte_position (field);
5818 if (integer_zerop (off) && integer_nonzerop (pos))
5819 /* If the offset is already 0, keep going as long as the
5820 component is at position 0. */
5821 break;
5822 off = int_const_binop (PLUS_EXPR, off, pos);
5823 obj = TREE_OPERAND (obj, 0);
5827 if (TREE_CODE (sub) == ADDR_EXPR)
5829 tree op = TREE_OPERAND (sub, 0);
5830 tree optype = TREE_TYPE (op);
5832 /* *&CONST_DECL -> to the value of the const decl. */
5833 if (TREE_CODE (op) == CONST_DECL)
5834 return DECL_INITIAL (op);
5835 /* *&p => p; make sure to handle *&"str"[cst] here. */
5836 if (similar_type_p (optype, type))
5838 tree fop = fold_read_from_constant_string (op);
5839 if (fop)
5840 return fop;
5841 else
5842 return op;
5844 else
5846 tree off = integer_zero_node;
5847 canonicalize_obj_off (op, off);
5848 gcc_assert (integer_zerop (off));
5849 return cxx_fold_indirect_ref_1 (ctx, loc, type, op, 0, empty_base);
5852 else if (TREE_CODE (sub) == POINTER_PLUS_EXPR
5853 && tree_fits_uhwi_p (TREE_OPERAND (sub, 1)))
5855 tree op00 = TREE_OPERAND (sub, 0);
5856 tree off = TREE_OPERAND (sub, 1);
5858 STRIP_NOPS (op00);
5859 if (TREE_CODE (op00) == ADDR_EXPR)
5861 tree obj = TREE_OPERAND (op00, 0);
5862 canonicalize_obj_off (obj, off);
5863 return cxx_fold_indirect_ref_1 (ctx, loc, type, obj,
5864 tree_to_uhwi (off), empty_base);
5867 /* *(foo *)fooarrptr => (*fooarrptr)[0] */
5868 else if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
5869 && similar_type_p (type, TREE_TYPE (TREE_TYPE (subtype))))
5871 tree type_domain;
5872 tree min_val = size_zero_node;
5873 tree newsub
5874 = cxx_fold_indirect_ref (ctx, loc, TREE_TYPE (subtype), sub, NULL);
5875 if (newsub)
5876 sub = newsub;
5877 else
5878 sub = build1_loc (loc, INDIRECT_REF, TREE_TYPE (subtype), sub);
5879 type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
5880 if (type_domain && TYPE_MIN_VALUE (type_domain))
5881 min_val = TYPE_MIN_VALUE (type_domain);
5882 return build4_loc (loc, ARRAY_REF, type, sub, min_val, NULL_TREE,
5883 NULL_TREE);
5886 return NULL_TREE;
5889 static tree
5890 cxx_eval_indirect_ref (const constexpr_ctx *ctx, tree t,
5891 value_cat lval,
5892 bool *non_constant_p, bool *overflow_p)
5894 tree orig_op0 = TREE_OPERAND (t, 0);
5895 bool empty_base = false;
5897 /* We can handle a MEM_REF like an INDIRECT_REF, if MEM_REF's second
5898 operand is an integer-zero. Otherwise reject the MEM_REF for now. */
5900 if (TREE_CODE (t) == MEM_REF
5901 && (!TREE_OPERAND (t, 1) || !integer_zerop (TREE_OPERAND (t, 1))))
5903 gcc_assert (ctx->quiet);
5904 *non_constant_p = true;
5905 return t;
5908 /* First try to simplify it directly. */
5909 tree r = cxx_fold_indirect_ref (ctx, EXPR_LOCATION (t), TREE_TYPE (t),
5910 orig_op0, &empty_base);
5911 if (!r)
5913 /* If that didn't work, evaluate the operand first. */
5914 tree op0 = cxx_eval_constant_expression (ctx, orig_op0,
5915 vc_prvalue, non_constant_p,
5916 overflow_p);
5917 /* Don't VERIFY_CONSTANT here. */
5918 if (*non_constant_p)
5919 return t;
5921 if (!lval && integer_zerop (op0))
5923 if (!ctx->quiet)
5924 error ("dereferencing a null pointer");
5925 *non_constant_p = true;
5926 return t;
5929 r = cxx_fold_indirect_ref (ctx, EXPR_LOCATION (t), TREE_TYPE (t), op0,
5930 &empty_base);
5931 if (r == NULL_TREE)
5933 /* We couldn't fold to a constant value. Make sure it's not
5934 something we should have been able to fold. */
5935 tree sub = op0;
5936 STRIP_NOPS (sub);
5937 if (TREE_CODE (sub) == ADDR_EXPR)
5939 gcc_assert (!similar_type_p
5940 (TREE_TYPE (TREE_TYPE (sub)), TREE_TYPE (t)));
5941 /* DR 1188 says we don't have to deal with this. */
5942 if (!ctx->quiet)
5943 error_at (cp_expr_loc_or_input_loc (t),
5944 "accessing value of %qE through a %qT glvalue in a "
5945 "constant expression", build_fold_indirect_ref (sub),
5946 TREE_TYPE (t));
5947 *non_constant_p = true;
5948 return t;
5951 if (lval == vc_glvalue && op0 != orig_op0)
5952 return build1 (INDIRECT_REF, TREE_TYPE (t), op0);
5953 if (!lval)
5954 VERIFY_CONSTANT (t);
5955 return t;
5959 r = cxx_eval_constant_expression (ctx, r,
5960 lval, non_constant_p, overflow_p);
5961 if (*non_constant_p)
5962 return t;
5964 /* If we're pulling out the value of an empty base, just return an empty
5965 CONSTRUCTOR. */
5966 if (empty_base && !lval)
5968 r = build_constructor (TREE_TYPE (t), NULL);
5969 TREE_CONSTANT (r) = true;
5972 return r;
5975 /* Complain about R, a DECL that is accessed outside its lifetime. */
5977 static void
5978 outside_lifetime_error (location_t loc, tree r)
5980 auto_diagnostic_group d;
5981 if (DECL_NAME (r) == heap_deleted_identifier)
5983 /* Provide a more accurate message for deleted variables. */
5984 error_at (loc, "use of allocated storage after deallocation "
5985 "in a constant expression");
5986 inform (DECL_SOURCE_LOCATION (r), "allocated here");
5988 else
5990 error_at (loc, "accessing %qE outside its lifetime", r);
5991 inform (DECL_SOURCE_LOCATION (r), "declared here");
5995 /* Complain about R, a VAR_DECL, not being usable in a constant expression.
5996 FUNDEF_P is true if we're checking a constexpr function body.
5997 Shared between potential_constant_expression and
5998 cxx_eval_constant_expression. */
6000 static void
6001 non_const_var_error (location_t loc, tree r, bool fundef_p)
6003 auto_diagnostic_group d;
6004 tree type = TREE_TYPE (r);
6005 if (DECL_NAME (r) == heap_uninit_identifier
6006 || DECL_NAME (r) == heap_identifier
6007 || DECL_NAME (r) == heap_vec_uninit_identifier
6008 || DECL_NAME (r) == heap_vec_identifier)
6010 if (constexpr_error (loc, fundef_p, "the content of uninitialized "
6011 "storage is not usable in a constant expression"))
6012 inform (DECL_SOURCE_LOCATION (r), "allocated here");
6013 return;
6015 if (DECL_NAME (r) == heap_deleted_identifier)
6017 if (constexpr_error (loc, fundef_p, "use of allocated storage after "
6018 "deallocation in a constant expression"))
6019 inform (DECL_SOURCE_LOCATION (r), "allocated here");
6020 return;
6022 if (!constexpr_error (loc, fundef_p, "the value of %qD is not usable in "
6023 "a constant expression", r))
6024 return;
6025 /* Avoid error cascade. */
6026 if (DECL_INITIAL (r) == error_mark_node)
6027 return;
6028 if (DECL_DECLARED_CONSTEXPR_P (r))
6029 inform (DECL_SOURCE_LOCATION (r),
6030 "%qD used in its own initializer", r);
6031 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
6033 if (!CP_TYPE_CONST_P (type))
6034 inform (DECL_SOURCE_LOCATION (r),
6035 "%q#D is not const", r);
6036 else if (CP_TYPE_VOLATILE_P (type))
6037 inform (DECL_SOURCE_LOCATION (r),
6038 "%q#D is volatile", r);
6039 else if (!DECL_INITIAL (r)
6040 || !TREE_CONSTANT (DECL_INITIAL (r))
6041 || !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r))
6042 inform (DECL_SOURCE_LOCATION (r),
6043 "%qD was not initialized with a constant "
6044 "expression", r);
6045 else
6046 gcc_unreachable ();
6048 else if (TYPE_REF_P (type))
6049 inform (DECL_SOURCE_LOCATION (r),
6050 "%qD was not initialized with a constant "
6051 "expression", r);
6052 else
6054 if (cxx_dialect >= cxx11 && !DECL_DECLARED_CONSTEXPR_P (r))
6055 inform (DECL_SOURCE_LOCATION (r),
6056 "%qD was not declared %<constexpr%>", r);
6057 else
6058 inform (DECL_SOURCE_LOCATION (r),
6059 "%qD does not have integral or enumeration type",
6064 /* Subroutine of cxx_eval_constant_expression.
6065 Like cxx_eval_unary_expression, except for trinary expressions. */
6067 static tree
6068 cxx_eval_trinary_expression (const constexpr_ctx *ctx, tree t,
6069 value_cat lval,
6070 bool *non_constant_p, bool *overflow_p)
6072 int i;
6073 tree args[3];
6074 tree val;
6076 for (i = 0; i < 3; i++)
6078 args[i] = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, i),
6079 lval,
6080 non_constant_p, overflow_p);
6081 VERIFY_CONSTANT (args[i]);
6084 val = fold_ternary_loc (EXPR_LOCATION (t), TREE_CODE (t), TREE_TYPE (t),
6085 args[0], args[1], args[2]);
6086 if (val == NULL_TREE)
6087 return t;
6088 VERIFY_CONSTANT (val);
6089 return val;
6092 /* True if T was declared in a function declared to be constexpr, and
6093 therefore potentially constant in C++14. */
6095 bool
6096 var_in_constexpr_fn (tree t)
6098 tree ctx = DECL_CONTEXT (t);
6099 return (ctx && TREE_CODE (ctx) == FUNCTION_DECL
6100 && DECL_DECLARED_CONSTEXPR_P (ctx));
6103 /* True if a function might be constexpr: either a function that was
6104 declared constexpr, or a C++17 lambda op(). */
6106 bool
6107 maybe_constexpr_fn (tree t)
6109 return (DECL_DECLARED_CONSTEXPR_P (t)
6110 || (cxx_dialect >= cxx17 && LAMBDA_FUNCTION_P (t))
6111 || (flag_implicit_constexpr
6112 && DECL_DECLARED_INLINE_P (STRIP_TEMPLATE (t))));
6115 /* True if T was declared in a function that might be constexpr: either a
6116 function that was declared constexpr, or a C++17 lambda op(). */
6118 bool
6119 var_in_maybe_constexpr_fn (tree t)
6121 return (DECL_FUNCTION_SCOPE_P (t)
6122 && maybe_constexpr_fn (DECL_CONTEXT (t)));
6125 /* We're assigning INIT to TARGET. In do_build_copy_constructor and
6126 build_over_call we implement trivial copy of a class with tail padding using
6127 assignment of character arrays, which is valid in normal code, but not in
6128 constexpr evaluation. We don't need to worry about clobbering tail padding
6129 in constexpr evaluation, so strip the type punning. */
6131 static void
6132 maybe_simplify_trivial_copy (tree &target, tree &init)
6134 if (TREE_CODE (target) == MEM_REF
6135 && TREE_CODE (init) == MEM_REF
6136 && TREE_TYPE (target) == TREE_TYPE (init)
6137 && TREE_CODE (TREE_TYPE (target)) == ARRAY_TYPE
6138 && TREE_TYPE (TREE_TYPE (target)) == unsigned_char_type_node)
6140 target = build_fold_indirect_ref (TREE_OPERAND (target, 0));
6141 init = build_fold_indirect_ref (TREE_OPERAND (init, 0));
6145 /* Returns true if REF, which is a COMPONENT_REF, has any fields
6146 of constant type. This does not check for 'mutable', so the
6147 caller is expected to be mindful of that. */
6149 static bool
6150 cref_has_const_field (tree ref)
6152 while (TREE_CODE (ref) == COMPONENT_REF)
6154 if (CP_TYPE_CONST_P (TREE_TYPE (TREE_OPERAND (ref, 1))))
6155 return true;
6156 ref = TREE_OPERAND (ref, 0);
6158 return false;
6161 /* Return true if we are modifying something that is const during constant
6162 expression evaluation. CODE is the code of the statement, OBJ is the
6163 object in question, MUTABLE_P is true if one of the subobjects were
6164 declared mutable. */
6166 static bool
6167 modifying_const_object_p (tree_code code, tree obj, bool mutable_p)
6169 /* If this is initialization, there's no problem. */
6170 if (code != MODIFY_EXPR)
6171 return false;
6173 /* [basic.type.qualifier] "A const object is an object of type
6174 const T or a non-mutable subobject of a const object." */
6175 if (mutable_p)
6176 return false;
6178 if (TREE_READONLY (obj))
6179 return true;
6181 if (CP_TYPE_CONST_P (TREE_TYPE (obj)))
6183 /* Although a COMPONENT_REF may have a const type, we should
6184 only consider it modifying a const object when any of the
6185 field components is const. This can happen when using
6186 constructs such as const_cast<const T &>(m), making something
6187 const even though it wasn't declared const. */
6188 if (TREE_CODE (obj) == COMPONENT_REF)
6189 return cref_has_const_field (obj);
6190 else
6191 return true;
6194 return false;
6197 /* Evaluate an INIT_EXPR or MODIFY_EXPR. */
6199 static tree
6200 cxx_eval_store_expression (const constexpr_ctx *ctx, tree t,
6201 value_cat lval,
6202 bool *non_constant_p, bool *overflow_p)
6204 constexpr_ctx new_ctx = *ctx;
6206 tree init = TREE_OPERAND (t, 1);
6208 if (TREE_CLOBBER_P (init)
6209 && CLOBBER_KIND (init) < CLOBBER_OBJECT_END)
6210 /* Only handle clobbers ending the lifetime of objects. */
6211 return void_node;
6213 /* First we figure out where we're storing to. */
6214 tree target = TREE_OPERAND (t, 0);
6216 maybe_simplify_trivial_copy (target, init);
6218 tree type = TREE_TYPE (target);
6219 bool preeval = SCALAR_TYPE_P (type) || TREE_CODE (t) == MODIFY_EXPR;
6220 if (preeval && !TREE_CLOBBER_P (init))
6222 /* Evaluate the value to be stored without knowing what object it will be
6223 stored in, so that any side-effects happen first. */
6224 if (!SCALAR_TYPE_P (type))
6225 new_ctx.ctor = new_ctx.object = NULL_TREE;
6226 init = cxx_eval_constant_expression (&new_ctx, init, vc_prvalue,
6227 non_constant_p, overflow_p);
6228 if (*non_constant_p)
6229 return t;
6232 bool evaluated = false;
6233 if (lval == vc_glvalue)
6235 /* If we want to return a reference to the target, we need to evaluate it
6236 as a whole; otherwise, only evaluate the innermost piece to avoid
6237 building up unnecessary *_REFs. */
6238 target = cxx_eval_constant_expression (ctx, target, lval,
6239 non_constant_p, overflow_p);
6240 evaluated = true;
6241 if (*non_constant_p)
6242 return t;
6245 /* Find the underlying variable. */
6246 releasing_vec refs;
6247 tree object = NULL_TREE;
6248 /* If we're modifying a const object, save it. */
6249 tree const_object_being_modified = NULL_TREE;
6250 bool mutable_p = false;
6251 for (tree probe = target; object == NULL_TREE; )
6253 switch (TREE_CODE (probe))
6255 case BIT_FIELD_REF:
6256 case COMPONENT_REF:
6257 case ARRAY_REF:
6259 tree ob = TREE_OPERAND (probe, 0);
6260 tree elt = TREE_OPERAND (probe, 1);
6261 if (TREE_CODE (elt) == FIELD_DECL && DECL_MUTABLE_P (elt))
6262 mutable_p = true;
6263 if (TREE_CODE (probe) == ARRAY_REF)
6265 elt = eval_and_check_array_index (ctx, probe, false,
6266 non_constant_p, overflow_p);
6267 if (*non_constant_p)
6268 return t;
6270 /* We don't check modifying_const_object_p for ARRAY_REFs. Given
6271 "int a[10]", an ARRAY_REF "a[2]" can be "const int", even though
6272 the array isn't const. Instead, check "a" in the next iteration;
6273 that will detect modifying "const int a[10]". */
6274 else if (evaluated
6275 && modifying_const_object_p (TREE_CODE (t), probe,
6276 mutable_p)
6277 && const_object_being_modified == NULL_TREE)
6278 const_object_being_modified = probe;
6280 /* Track named member accesses for unions to validate modifications
6281 that change active member. */
6282 if (!evaluated && TREE_CODE (probe) == COMPONENT_REF)
6283 vec_safe_push (refs, probe);
6284 else
6285 vec_safe_push (refs, NULL_TREE);
6287 vec_safe_push (refs, elt);
6288 vec_safe_push (refs, TREE_TYPE (probe));
6289 probe = ob;
6291 break;
6293 case REALPART_EXPR:
6294 gcc_assert (probe == target);
6295 vec_safe_push (refs, NULL_TREE);
6296 vec_safe_push (refs, probe);
6297 vec_safe_push (refs, TREE_TYPE (probe));
6298 probe = TREE_OPERAND (probe, 0);
6299 break;
6301 case IMAGPART_EXPR:
6302 gcc_assert (probe == target);
6303 vec_safe_push (refs, NULL_TREE);
6304 vec_safe_push (refs, probe);
6305 vec_safe_push (refs, TREE_TYPE (probe));
6306 probe = TREE_OPERAND (probe, 0);
6307 break;
6309 default:
6310 if (evaluated)
6311 object = probe;
6312 else
6314 probe = cxx_eval_constant_expression (ctx, probe, vc_glvalue,
6315 non_constant_p, overflow_p);
6316 evaluated = true;
6317 if (*non_constant_p)
6318 return t;
6320 break;
6324 if (modifying_const_object_p (TREE_CODE (t), object, mutable_p)
6325 && const_object_being_modified == NULL_TREE)
6326 const_object_being_modified = object;
6328 if (DECL_P (object)
6329 && TREE_CLOBBER_P (init)
6330 && DECL_NAME (object) == heap_deleted_identifier)
6331 /* Ignore clobbers of deleted allocations for now; we'll get a better error
6332 message later when operator delete is called. */
6333 return void_node;
6335 /* And then find/build up our initializer for the path to the subobject
6336 we're initializing. */
6337 tree *valp;
6338 if (DECL_P (object))
6339 valp = ctx->global->get_value_ptr (object, TREE_CODE (t) == INIT_EXPR);
6340 else
6341 valp = NULL;
6342 if (!valp)
6344 /* A constant-expression cannot modify objects from outside the
6345 constant-expression. */
6346 if (!ctx->quiet)
6348 auto_diagnostic_group d;
6349 if (DECL_P (object) && DECL_NAME (object) == heap_deleted_identifier)
6351 error ("modification of allocated storage after deallocation "
6352 "is not a constant expression");
6353 inform (DECL_SOURCE_LOCATION (object), "allocated here");
6355 else if (DECL_P (object) && ctx->global->is_outside_lifetime (object))
6357 if (TREE_CLOBBER_P (init))
6358 error ("destroying %qE outside its lifetime", object);
6359 else
6360 error ("modification of %qE outside its lifetime "
6361 "is not a constant expression", object);
6362 inform (DECL_SOURCE_LOCATION (object), "declared here");
6364 else
6366 if (TREE_CLOBBER_P (init))
6367 error ("destroying %qE from outside current evaluation "
6368 "is not a constant expression", object);
6369 else
6370 error ("modification of %qE from outside current evaluation "
6371 "is not a constant expression", object);
6374 *non_constant_p = true;
6375 return t;
6378 /* Handle explicit end-of-lifetime. */
6379 if (TREE_CLOBBER_P (init))
6381 if (refs->is_empty ())
6382 ctx->global->destroy_value (object);
6383 return void_node;
6386 type = TREE_TYPE (object);
6387 bool no_zero_init = true;
6389 auto_vec<tree *> ctors;
6390 releasing_vec indexes;
6391 auto_vec<int> index_pos_hints;
6392 bool activated_union_member_p = false;
6393 bool empty_base = false;
6394 while (!refs->is_empty ())
6396 if (*valp == NULL_TREE)
6398 *valp = build_constructor (type, NULL);
6399 CONSTRUCTOR_NO_CLEARING (*valp) = no_zero_init;
6401 else if (STRIP_ANY_LOCATION_WRAPPER (*valp),
6402 TREE_CODE (*valp) == STRING_CST)
6404 /* An array was initialized with a string constant, and now
6405 we're writing into one of its elements. Explode the
6406 single initialization into a set of element
6407 initializations. */
6408 gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
6410 tree string = *valp;
6411 tree elt_type = TREE_TYPE (type);
6412 unsigned chars_per_elt = (TYPE_PRECISION (elt_type)
6413 / TYPE_PRECISION (char_type_node));
6414 unsigned num_elts = TREE_STRING_LENGTH (string) / chars_per_elt;
6415 tree ary_ctor = build_constructor (type, NULL);
6417 vec_safe_reserve (CONSTRUCTOR_ELTS (ary_ctor), num_elts);
6418 for (unsigned ix = 0; ix != num_elts; ix++)
6420 constructor_elt elt =
6422 build_int_cst (size_type_node, ix),
6423 extract_string_elt (string, chars_per_elt, ix)
6425 CONSTRUCTOR_ELTS (ary_ctor)->quick_push (elt);
6428 *valp = ary_ctor;
6431 enum tree_code code = TREE_CODE (type);
6432 tree reftype = refs->pop();
6433 tree index = refs->pop();
6434 bool is_access_expr = refs->pop() != NULL_TREE;
6436 if (code == COMPLEX_TYPE)
6438 if (TREE_CODE (*valp) == COMPLEX_CST)
6439 *valp = build2 (COMPLEX_EXPR, type, TREE_REALPART (*valp),
6440 TREE_IMAGPART (*valp));
6441 else if (TREE_CODE (*valp) == CONSTRUCTOR
6442 && CONSTRUCTOR_NELTS (*valp) == 0
6443 && CONSTRUCTOR_NO_CLEARING (*valp))
6445 tree r = build_constructor (reftype, NULL);
6446 CONSTRUCTOR_NO_CLEARING (r) = 1;
6447 *valp = build2 (COMPLEX_EXPR, type, r, r);
6449 gcc_assert (TREE_CODE (*valp) == COMPLEX_EXPR);
6450 ctors.safe_push (valp);
6451 vec_safe_push (indexes, index);
6452 valp = &TREE_OPERAND (*valp, TREE_CODE (index) == IMAGPART_EXPR);
6453 gcc_checking_assert (refs->is_empty ());
6454 type = reftype;
6455 break;
6458 /* If the value of object is already zero-initialized, any new ctors for
6459 subobjects will also be zero-initialized. */
6460 no_zero_init = CONSTRUCTOR_NO_CLEARING (*valp);
6462 if (code == RECORD_TYPE && is_empty_field (index))
6463 /* Don't build a sub-CONSTRUCTOR for an empty base or field, as they
6464 have no data and might have an offset lower than previously declared
6465 fields, which confuses the middle-end. The code below will notice
6466 that we don't have a CONSTRUCTOR for our inner target and just
6467 return init. */
6469 empty_base = true;
6470 break;
6473 /* If a union is zero-initialized, its first non-static named data member
6474 is zero-initialized (and therefore active). */
6475 if (code == UNION_TYPE
6476 && !no_zero_init
6477 && CONSTRUCTOR_NELTS (*valp) == 0)
6478 if (tree first = next_aggregate_field (TYPE_FIELDS (type)))
6479 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (*valp), first, NULL_TREE);
6481 /* Check for implicit change of active member for a union. */
6482 if (code == UNION_TYPE
6483 && (CONSTRUCTOR_NELTS (*valp) == 0
6484 || CONSTRUCTOR_ELT (*valp, 0)->index != index)
6485 /* An INIT_EXPR of the last member in an access chain is always OK,
6486 but still check implicit change of members earlier on; see
6487 cpp2a/constexpr-union6.C. */
6488 && !(TREE_CODE (t) == INIT_EXPR && refs->is_empty ()))
6490 bool has_active_member = CONSTRUCTOR_NELTS (*valp) != 0;
6491 tree inner = strip_array_types (reftype);
6493 if (has_active_member && cxx_dialect < cxx20)
6495 if (!ctx->quiet)
6496 error_at (cp_expr_loc_or_input_loc (t),
6497 "change of the active member of a union "
6498 "from %qD to %qD is not a constant expression "
6499 "before C++20",
6500 CONSTRUCTOR_ELT (*valp, 0)->index,
6501 index);
6502 *non_constant_p = true;
6504 else if (!is_access_expr
6505 || (TREE_CODE (t) == MODIFY_EXPR
6506 && CLASS_TYPE_P (inner)
6507 && !type_has_non_deleted_trivial_default_ctor (inner)))
6509 /* Diagnose changing active union member after initialization
6510 without a valid member access expression, as described in
6511 [class.union.general] p5. */
6512 if (!ctx->quiet)
6514 auto_diagnostic_group d;
6515 if (has_active_member)
6516 error_at (cp_expr_loc_or_input_loc (t),
6517 "accessing %qD member instead of initialized "
6518 "%qD member in constant expression",
6519 index, CONSTRUCTOR_ELT (*valp, 0)->index);
6520 else
6521 error_at (cp_expr_loc_or_input_loc (t),
6522 "accessing uninitialized member %qD",
6523 index);
6524 if (is_access_expr)
6525 inform (DECL_SOURCE_LOCATION (index),
6526 "%qD does not implicitly begin its lifetime "
6527 "because %qT does not have a non-deleted "
6528 "trivial default constructor, use "
6529 "%<std::construct_at%> instead",
6530 index, inner);
6531 else
6532 inform (DECL_SOURCE_LOCATION (index),
6533 "initializing %qD requires a member access "
6534 "expression as the left operand of the assignment",
6535 index);
6537 *non_constant_p = true;
6539 else if (has_active_member && CONSTRUCTOR_NO_CLEARING (*valp))
6541 /* Diagnose changing the active union member while the union
6542 is in the process of being initialized. */
6543 if (!ctx->quiet)
6544 error_at (cp_expr_loc_or_input_loc (t),
6545 "change of the active member of a union "
6546 "from %qD to %qD during initialization",
6547 CONSTRUCTOR_ELT (*valp, 0)->index,
6548 index);
6549 *non_constant_p = true;
6551 no_zero_init = true;
6554 ctors.safe_push (valp);
6555 vec_safe_push (indexes, index);
6557 constructor_elt *cep
6558 = get_or_insert_ctor_field (*valp, index);
6559 index_pos_hints.safe_push (cep - CONSTRUCTOR_ELTS (*valp)->begin());
6561 if (code == UNION_TYPE)
6562 activated_union_member_p = true;
6564 valp = &cep->value;
6565 type = reftype;
6568 /* For initialization of an empty base, the original target will be
6569 *(base*)this, evaluation of which resolves to the object
6570 argument, which has the derived type rather than the base type. */
6571 if (!empty_base && !(same_type_ignoring_top_level_qualifiers_p
6572 (initialized_type (init), type)))
6574 gcc_assert (is_empty_class (TREE_TYPE (target)));
6575 empty_base = true;
6578 /* Detect modifying a constant object in constexpr evaluation.
6579 We have found a const object that is being modified. Figure out
6580 if we need to issue an error. Consider
6582 struct A {
6583 int n;
6584 constexpr A() : n(1) { n = 2; } // #1
6586 struct B {
6587 const A a;
6588 constexpr B() { a.n = 3; } // #2
6590 constexpr B b{};
6592 #1 is OK, since we're modifying an object under construction, but
6593 #2 is wrong, since "a" is const and has been fully constructed.
6594 To track it, we use the TREE_READONLY bit in the object's CONSTRUCTOR
6595 which means that the object is read-only. For the example above, the
6596 *ctors stack at the point of #2 will look like:
6598 ctors[0] = {.a={.n=2}} TREE_READONLY = 0
6599 ctors[1] = {.n=2} TREE_READONLY = 1
6601 and we're modifying "b.a", so we search the stack and see if the
6602 constructor for "b.a" has already run. */
6603 if (const_object_being_modified)
6605 bool fail = false;
6606 tree const_objtype
6607 = strip_array_types (TREE_TYPE (const_object_being_modified));
6608 if (!CLASS_TYPE_P (const_objtype))
6609 fail = true;
6610 else
6612 /* [class.ctor]p5 "A constructor can be invoked for a const,
6613 volatile, or const volatile object. const and volatile
6614 semantics are not applied on an object under construction.
6615 They come into effect when the constructor for the most
6616 derived object ends." */
6617 for (tree *elt : ctors)
6618 if (same_type_ignoring_top_level_qualifiers_p
6619 (TREE_TYPE (const_object_being_modified), TREE_TYPE (*elt)))
6621 fail = TREE_READONLY (*elt);
6622 break;
6625 if (fail)
6627 if (!ctx->quiet)
6628 modifying_const_object_error (t, const_object_being_modified);
6629 *non_constant_p = true;
6630 return t;
6634 if (!preeval)
6636 /* We're handling an INIT_EXPR of class type, so the value of the
6637 initializer can depend on the object it's initializing. */
6639 /* Create a new CONSTRUCTOR in case evaluation of the initializer
6640 wants to modify it. */
6641 if (*valp == NULL_TREE)
6643 *valp = build_constructor (type, NULL);
6644 CONSTRUCTOR_NO_CLEARING (*valp) = no_zero_init;
6646 new_ctx.ctor = empty_base ? NULL_TREE : *valp;
6647 new_ctx.object = target;
6648 /* Avoid temporary materialization when initializing from a TARGET_EXPR.
6649 We don't need to mess with AGGR_EXPR_SLOT/VEC_INIT_EXPR_SLOT because
6650 expansion of those trees uses ctx instead. */
6651 if (TREE_CODE (init) == TARGET_EXPR)
6652 if (tree tinit = TARGET_EXPR_INITIAL (init))
6653 init = tinit;
6654 init = cxx_eval_constant_expression (&new_ctx, init, vc_prvalue,
6655 non_constant_p, overflow_p);
6656 /* The hash table might have moved since the get earlier, and the
6657 initializer might have mutated the underlying CONSTRUCTORs, so we must
6658 recompute VALP. */
6659 valp = ctx->global->get_value_ptr (object, TREE_CODE (t) == INIT_EXPR);
6660 for (unsigned i = 0; i < vec_safe_length (indexes); i++)
6662 ctors[i] = valp;
6663 constructor_elt *cep
6664 = get_or_insert_ctor_field (*valp, indexes[i], index_pos_hints[i]);
6665 valp = &cep->value;
6669 if (*non_constant_p)
6670 return t;
6672 /* Don't share a CONSTRUCTOR that might be changed later. */
6673 init = unshare_constructor (init);
6675 gcc_checking_assert (!*valp || (same_type_ignoring_top_level_qualifiers_p
6676 (TREE_TYPE (*valp), type)));
6677 if (empty_base)
6679 /* Just evaluate the initializer and return, since there's no actual data
6680 to store, and we didn't build a CONSTRUCTOR. */
6681 if (!*valp)
6683 /* But do make sure we have something in *valp. */
6684 *valp = build_constructor (type, nullptr);
6685 CONSTRUCTOR_NO_CLEARING (*valp) = no_zero_init;
6688 else if (*valp && TREE_CODE (*valp) == CONSTRUCTOR
6689 && TREE_CODE (init) == CONSTRUCTOR)
6691 /* An outer ctx->ctor might be pointing to *valp, so replace
6692 its contents. */
6693 CONSTRUCTOR_ELTS (*valp) = CONSTRUCTOR_ELTS (init);
6694 TREE_CONSTANT (*valp) = TREE_CONSTANT (init);
6695 TREE_SIDE_EFFECTS (*valp) = TREE_SIDE_EFFECTS (init);
6696 CONSTRUCTOR_NO_CLEARING (*valp)
6697 = CONSTRUCTOR_NO_CLEARING (init);
6699 else
6700 *valp = init;
6702 /* After initialization, 'const' semantics apply to the value of the
6703 object. Make a note of this fact by marking the CONSTRUCTOR
6704 TREE_READONLY. */
6705 if (TREE_CODE (t) == INIT_EXPR
6706 && !empty_base
6707 && TREE_CODE (*valp) == CONSTRUCTOR
6708 && TYPE_READONLY (type))
6710 if (INDIRECT_REF_P (target)
6711 && (is_this_parameter
6712 (tree_strip_nop_conversions (TREE_OPERAND (target, 0)))))
6713 /* We've just initialized '*this' (perhaps via the target
6714 constructor of a delegating constructor). Leave it up to the
6715 caller that set 'this' to set TREE_READONLY appropriately. */
6716 gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
6717 (TREE_TYPE (target), type) || empty_base);
6718 else
6719 TREE_READONLY (*valp) = true;
6722 /* Update TREE_CONSTANT and TREE_SIDE_EFFECTS on enclosing
6723 CONSTRUCTORs, if any. */
6724 bool c = TREE_CONSTANT (init);
6725 bool s = TREE_SIDE_EFFECTS (init);
6726 if (!indexes->is_empty ())
6728 tree last = indexes->last ();
6729 if (TREE_CODE (last) == REALPART_EXPR
6730 || TREE_CODE (last) == IMAGPART_EXPR)
6732 /* And canonicalize COMPLEX_EXPR into COMPLEX_CST if
6733 possible. */
6734 tree *cexpr = ctors.last ();
6735 if (tree c = const_binop (COMPLEX_EXPR, TREE_TYPE (*cexpr),
6736 TREE_OPERAND (*cexpr, 0),
6737 TREE_OPERAND (*cexpr, 1)))
6738 *cexpr = c;
6739 else
6741 TREE_CONSTANT (*cexpr)
6742 = (TREE_CONSTANT (TREE_OPERAND (*cexpr, 0))
6743 & TREE_CONSTANT (TREE_OPERAND (*cexpr, 1)));
6744 TREE_SIDE_EFFECTS (*cexpr)
6745 = (TREE_SIDE_EFFECTS (TREE_OPERAND (*cexpr, 0))
6746 | TREE_SIDE_EFFECTS (TREE_OPERAND (*cexpr, 1)));
6748 c = TREE_CONSTANT (*cexpr);
6749 s = TREE_SIDE_EFFECTS (*cexpr);
6752 if (!c || s || activated_union_member_p)
6753 for (tree *elt : ctors)
6755 if (TREE_CODE (*elt) != CONSTRUCTOR)
6756 continue;
6757 if (!c)
6758 TREE_CONSTANT (*elt) = false;
6759 if (s)
6760 TREE_SIDE_EFFECTS (*elt) = true;
6761 /* Clear CONSTRUCTOR_NO_CLEARING since we've activated a member of
6762 this union. */
6763 if (TREE_CODE (TREE_TYPE (*elt)) == UNION_TYPE)
6764 CONSTRUCTOR_NO_CLEARING (*elt) = false;
6767 if (lval)
6768 return target;
6769 else
6770 return init;
6773 /* Evaluate a ++ or -- expression. */
6775 static tree
6776 cxx_eval_increment_expression (const constexpr_ctx *ctx, tree t,
6777 value_cat lval,
6778 bool *non_constant_p, bool *overflow_p)
6780 enum tree_code code = TREE_CODE (t);
6781 tree type = TREE_TYPE (t);
6782 tree op = TREE_OPERAND (t, 0);
6783 tree offset = TREE_OPERAND (t, 1);
6784 gcc_assert (TREE_CONSTANT (offset));
6786 /* OFFSET is constant, but perhaps not constant enough. We need to
6787 e.g. bash FLOAT_EXPRs to REAL_CSTs. */
6788 offset = fold_simple (offset);
6790 /* The operand as an lvalue. */
6791 op = cxx_eval_constant_expression (ctx, op, vc_glvalue,
6792 non_constant_p, overflow_p);
6794 /* The operand as an rvalue. */
6795 tree val
6796 = cxx_eval_constant_expression (ctx, op, vc_prvalue,
6797 non_constant_p, overflow_p);
6798 /* Don't VERIFY_CONSTANT if this might be dealing with a pointer to
6799 a local array in a constexpr function. */
6800 bool ptr = INDIRECT_TYPE_P (TREE_TYPE (val));
6801 if (!ptr)
6802 VERIFY_CONSTANT (val);
6804 /* The modified value. */
6805 bool inc = (code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR);
6806 tree mod;
6807 if (INDIRECT_TYPE_P (type))
6809 /* The middle end requires pointers to use POINTER_PLUS_EXPR. */
6810 offset = convert_to_ptrofftype (offset);
6811 if (!inc)
6812 offset = fold_build1 (NEGATE_EXPR, TREE_TYPE (offset), offset);
6813 mod = fold_build2 (POINTER_PLUS_EXPR, type, val, offset);
6815 else if (c_promoting_integer_type_p (type)
6816 && !TYPE_UNSIGNED (type)
6817 && TYPE_PRECISION (type) < TYPE_PRECISION (integer_type_node))
6819 offset = fold_convert (integer_type_node, offset);
6820 mod = fold_convert (integer_type_node, val);
6821 tree t = fold_build2 (inc ? PLUS_EXPR : MINUS_EXPR, integer_type_node,
6822 mod, offset);
6823 mod = fold_convert (type, t);
6824 if (TREE_OVERFLOW_P (mod) && !TREE_OVERFLOW_P (t))
6825 TREE_OVERFLOW (mod) = false;
6827 else
6828 mod = fold_build2 (inc ? PLUS_EXPR : MINUS_EXPR, type, val, offset);
6829 if (!ptr)
6830 VERIFY_CONSTANT (mod);
6832 /* Storing the modified value. */
6833 tree store = build2_loc (cp_expr_loc_or_loc (t, input_location),
6834 MODIFY_EXPR, type, op, mod);
6835 mod = cxx_eval_constant_expression (ctx, store, lval,
6836 non_constant_p, overflow_p);
6837 ggc_free (store);
6838 if (*non_constant_p)
6839 return t;
6841 /* And the value of the expression. */
6842 if (code == PREINCREMENT_EXPR || code == PREDECREMENT_EXPR)
6843 /* Prefix ops are lvalues, but the caller might want an rvalue;
6844 lval has already been taken into account in the store above. */
6845 return mod;
6846 else
6847 /* Postfix ops are rvalues. */
6848 return val;
6851 /* Predicates for the meaning of *jump_target. */
6853 static bool
6854 returns (tree *jump_target)
6856 return *jump_target
6857 && TREE_CODE (*jump_target) == RETURN_EXPR;
6860 static bool
6861 breaks (tree *jump_target)
6863 return *jump_target
6864 && ((TREE_CODE (*jump_target) == LABEL_DECL
6865 && LABEL_DECL_BREAK (*jump_target))
6866 || TREE_CODE (*jump_target) == BREAK_STMT
6867 || TREE_CODE (*jump_target) == EXIT_EXPR);
6870 static bool
6871 continues (tree *jump_target)
6873 return *jump_target
6874 && ((TREE_CODE (*jump_target) == LABEL_DECL
6875 && LABEL_DECL_CONTINUE (*jump_target))
6876 || TREE_CODE (*jump_target) == CONTINUE_STMT);
6880 static bool
6881 switches (tree *jump_target)
6883 return *jump_target
6884 && TREE_CODE (*jump_target) == INTEGER_CST;
6887 /* Subroutine of cxx_eval_statement_list. Determine whether the statement
6888 STMT matches *jump_target. If we're looking for a case label and we see
6889 the default label, note it in ctx->css_state. */
6891 static bool
6892 label_matches (const constexpr_ctx *ctx, tree *jump_target, tree stmt)
6894 switch (TREE_CODE (*jump_target))
6896 case LABEL_DECL:
6897 if (TREE_CODE (stmt) == LABEL_EXPR
6898 && LABEL_EXPR_LABEL (stmt) == *jump_target)
6899 return true;
6900 break;
6902 case INTEGER_CST:
6903 if (TREE_CODE (stmt) == CASE_LABEL_EXPR)
6905 gcc_assert (ctx->css_state != NULL);
6906 if (!CASE_LOW (stmt))
6908 /* default: should appear just once in a SWITCH_EXPR
6909 body (excluding nested SWITCH_EXPR). */
6910 gcc_assert (*ctx->css_state != css_default_seen);
6911 /* When evaluating SWITCH_EXPR body for the second time,
6912 return true for the default: label. */
6913 if (*ctx->css_state == css_default_processing)
6914 return true;
6915 *ctx->css_state = css_default_seen;
6917 else if (CASE_HIGH (stmt))
6919 if (tree_int_cst_le (CASE_LOW (stmt), *jump_target)
6920 && tree_int_cst_le (*jump_target, CASE_HIGH (stmt)))
6921 return true;
6923 else if (tree_int_cst_equal (*jump_target, CASE_LOW (stmt)))
6924 return true;
6926 break;
6928 case BREAK_STMT:
6929 case CONTINUE_STMT:
6930 /* These two are handled directly in cxx_eval_loop_expr by testing
6931 breaks (jump_target) or continues (jump_target). */
6932 break;
6934 default:
6935 gcc_unreachable ();
6937 return false;
6940 /* Evaluate a STATEMENT_LIST for side-effects. Handles various jump
6941 semantics, for switch, break, continue, and return. */
6943 static tree
6944 cxx_eval_statement_list (const constexpr_ctx *ctx, tree t,
6945 bool *non_constant_p, bool *overflow_p,
6946 tree *jump_target)
6948 tree local_target;
6949 /* In a statement-expression we want to return the last value.
6950 For empty statement expression return void_node. */
6951 tree r = void_node;
6952 if (!jump_target)
6954 local_target = NULL_TREE;
6955 jump_target = &local_target;
6957 for (tree_stmt_iterator i = tsi_start (t); !tsi_end_p (i); ++i)
6959 tree stmt = *i;
6961 /* We've found a continue, so skip everything until we reach
6962 the label its jumping to. */
6963 if (continues (jump_target))
6965 if (label_matches (ctx, jump_target, stmt))
6966 /* Found it. */
6967 *jump_target = NULL_TREE;
6968 else
6969 continue;
6971 if (TREE_CODE (stmt) == DEBUG_BEGIN_STMT)
6972 continue;
6974 value_cat lval = vc_discard;
6975 /* The result of a statement-expression is not wrapped in EXPR_STMT. */
6976 if (tsi_one_before_end_p (i) && TREE_CODE (stmt) != EXPR_STMT)
6977 lval = vc_prvalue;
6979 r = cxx_eval_constant_expression (ctx, stmt, lval,
6980 non_constant_p, overflow_p,
6981 jump_target);
6982 if (*non_constant_p)
6983 break;
6984 if (returns (jump_target) || breaks (jump_target))
6985 break;
6987 if (*jump_target && jump_target == &local_target)
6989 /* We aren't communicating the jump to our caller, so give up. We don't
6990 need to support evaluation of jumps out of statement-exprs. */
6991 if (!ctx->quiet)
6992 error_at (cp_expr_loc_or_input_loc (r),
6993 "statement is not a constant expression");
6994 *non_constant_p = true;
6996 return r;
6999 /* Evaluate a LOOP_EXPR for side-effects. Handles break and return
7000 semantics; continue semantics are covered by cxx_eval_statement_list. */
7002 static tree
7003 cxx_eval_loop_expr (const constexpr_ctx *ctx, tree t,
7004 bool *non_constant_p, bool *overflow_p,
7005 tree *jump_target)
7007 tree local_target;
7008 if (!jump_target)
7010 local_target = NULL_TREE;
7011 jump_target = &local_target;
7014 tree body, cond = NULL_TREE, expr = NULL_TREE;
7015 int count = 0;
7016 switch (TREE_CODE (t))
7018 case LOOP_EXPR:
7019 body = LOOP_EXPR_BODY (t);
7020 break;
7021 case DO_STMT:
7022 body = DO_BODY (t);
7023 cond = DO_COND (t);
7024 break;
7025 case WHILE_STMT:
7026 body = WHILE_BODY (t);
7027 cond = WHILE_COND (t);
7028 count = -1;
7029 break;
7030 case FOR_STMT:
7031 if (FOR_INIT_STMT (t))
7032 cxx_eval_constant_expression (ctx, FOR_INIT_STMT (t), vc_discard,
7033 non_constant_p, overflow_p, jump_target);
7034 if (*non_constant_p)
7035 return NULL_TREE;
7036 body = FOR_BODY (t);
7037 cond = FOR_COND (t);
7038 expr = FOR_EXPR (t);
7039 count = -1;
7040 break;
7041 default:
7042 gcc_unreachable ();
7046 if (count != -1)
7048 if (body)
7049 cxx_eval_constant_expression (ctx, body, vc_discard,
7050 non_constant_p, overflow_p,
7051 jump_target);
7052 if (breaks (jump_target))
7054 *jump_target = NULL_TREE;
7055 break;
7058 if (TREE_CODE (t) != LOOP_EXPR && continues (jump_target))
7059 *jump_target = NULL_TREE;
7061 if (expr)
7062 cxx_eval_constant_expression (ctx, expr, vc_prvalue,
7063 non_constant_p, overflow_p,
7064 jump_target);
7067 if (cond)
7069 tree res
7070 = cxx_eval_constant_expression (ctx, cond, vc_prvalue,
7071 non_constant_p, overflow_p,
7072 jump_target);
7073 if (res)
7075 if (verify_constant (res, ctx->quiet, non_constant_p,
7076 overflow_p))
7077 break;
7078 if (integer_zerop (res))
7079 break;
7081 else
7082 gcc_assert (*jump_target);
7085 if (++count >= constexpr_loop_limit)
7087 if (!ctx->quiet)
7088 error_at (cp_expr_loc_or_input_loc (t),
7089 "%<constexpr%> loop iteration count exceeds limit of %d "
7090 "(use %<-fconstexpr-loop-limit=%> to increase the limit)",
7091 constexpr_loop_limit);
7092 *non_constant_p = true;
7093 break;
7096 while (!returns (jump_target)
7097 && !breaks (jump_target)
7098 && !continues (jump_target)
7099 && (!switches (jump_target) || count == 0)
7100 && !*non_constant_p);
7102 return NULL_TREE;
7105 /* Evaluate a SWITCH_EXPR for side-effects. Handles switch and break jump
7106 semantics. */
7108 static tree
7109 cxx_eval_switch_expr (const constexpr_ctx *ctx, tree t,
7110 bool *non_constant_p, bool *overflow_p,
7111 tree *jump_target)
7113 tree cond
7114 = TREE_CODE (t) == SWITCH_STMT ? SWITCH_STMT_COND (t) : SWITCH_COND (t);
7115 cond = cxx_eval_constant_expression (ctx, cond, vc_prvalue,
7116 non_constant_p, overflow_p);
7117 VERIFY_CONSTANT (cond);
7118 if (TREE_CODE (cond) != INTEGER_CST)
7120 /* If the condition doesn't reduce to an INTEGER_CST it isn't a usable
7121 switch condition even if it's constant enough for other things
7122 (c++/113545). */
7123 gcc_checking_assert (ctx->quiet);
7124 *non_constant_p = true;
7125 return t;
7128 *jump_target = cond;
7130 tree body
7131 = TREE_CODE (t) == SWITCH_STMT ? SWITCH_STMT_BODY (t) : SWITCH_BODY (t);
7132 constexpr_ctx new_ctx = *ctx;
7133 constexpr_switch_state css = css_default_not_seen;
7134 new_ctx.css_state = &css;
7135 cxx_eval_constant_expression (&new_ctx, body, vc_discard,
7136 non_constant_p, overflow_p, jump_target);
7137 if (switches (jump_target) && css == css_default_seen)
7139 /* If the SWITCH_EXPR body has default: label, process it once again,
7140 this time instructing label_matches to return true for default:
7141 label on switches (jump_target). */
7142 css = css_default_processing;
7143 cxx_eval_constant_expression (&new_ctx, body, vc_discard,
7144 non_constant_p, overflow_p, jump_target);
7146 if (breaks (jump_target) || switches (jump_target))
7147 *jump_target = NULL_TREE;
7148 return NULL_TREE;
7151 /* Find the object of TYPE under initialization in CTX. */
7153 static tree
7154 lookup_placeholder (const constexpr_ctx *ctx, value_cat lval, tree type)
7156 if (!ctx)
7157 return NULL_TREE;
7159 /* Prefer the outermost matching object, but don't cross
7160 CONSTRUCTOR_PLACEHOLDER_BOUNDARY constructors. */
7161 if (ctx->ctor && !CONSTRUCTOR_PLACEHOLDER_BOUNDARY (ctx->ctor))
7162 if (tree outer_ob = lookup_placeholder (ctx->parent, lval, type))
7163 return outer_ob;
7165 /* We could use ctx->object unconditionally, but using ctx->ctor when we
7166 can is a minor optimization. */
7167 if (!lval && ctx->ctor && same_type_p (TREE_TYPE (ctx->ctor), type))
7168 return ctx->ctor;
7170 if (!ctx->object)
7171 return NULL_TREE;
7173 /* Since an object cannot have a field of its own type, we can search outward
7174 from ctx->object to find the unique containing object of TYPE. */
7175 tree ob = ctx->object;
7176 while (ob)
7178 if (same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (ob), type))
7179 break;
7180 if (handled_component_p (ob))
7181 ob = TREE_OPERAND (ob, 0);
7182 else
7183 ob = NULL_TREE;
7186 return ob;
7189 /* Complain about an attempt to evaluate inline assembly. If FUNDEF_P is
7190 true, we're checking a constexpr function body. */
7192 static void
7193 inline_asm_in_constexpr_error (location_t loc, bool fundef_p)
7195 auto_diagnostic_group d;
7196 if (constexpr_error (loc, fundef_p, "inline assembly is not a "
7197 "constant expression"))
7198 inform (loc, "only unevaluated inline assembly is allowed in a "
7199 "%<constexpr%> function in C++20");
7202 /* We're getting the constant value of DECL in a manifestly constant-evaluated
7203 context; maybe complain about that. */
7205 static void
7206 maybe_warn_about_constant_value (location_t loc, tree decl)
7208 static bool explained = false;
7209 if (cxx_dialect >= cxx17
7210 && warn_interference_size
7211 && !OPTION_SET_P (param_destruct_interfere_size)
7212 && DECL_CONTEXT (decl) == std_node
7213 && id_equal (DECL_NAME (decl), "hardware_destructive_interference_size")
7214 && (LOCATION_FILE (input_location) != main_input_filename
7215 || module_exporting_p ())
7216 && warning_at (loc, OPT_Winterference_size, "use of %qD", decl)
7217 && !explained)
7219 explained = true;
7220 inform (loc, "its value can vary between compiler versions or "
7221 "with different %<-mtune%> or %<-mcpu%> flags");
7222 inform (loc, "if this use is part of a public ABI, change it to "
7223 "instead use a constant variable you define");
7224 inform (loc, "the default value for the current CPU tuning "
7225 "is %d bytes", param_destruct_interfere_size);
7226 inform (loc, "you can stabilize this value with %<--param "
7227 "hardware_destructive_interference_size=%d%>, or disable "
7228 "this warning with %<-Wno-interference-size%>",
7229 param_destruct_interfere_size);
7233 /* For element type ELT_TYPE, return the appropriate type of the heap object
7234 containing such element(s). COOKIE_SIZE is NULL or the size of cookie
7235 in bytes. If COOKIE_SIZE is NULL, return array type
7236 ELT_TYPE[FULL_SIZE / sizeof(ELT_TYPE)], otherwise return
7237 struct { size_t[COOKIE_SIZE/sizeof(size_t)]; ELT_TYPE[N]; }
7238 where N is computed such that the size of the struct fits into FULL_SIZE.
7239 If ARG_SIZE is non-NULL, it is the first argument to the new operator.
7240 It should be passed if ELT_TYPE is zero sized type in which case FULL_SIZE
7241 will be also 0 and so it is not possible to determine the actual array
7242 size. CTX, NON_CONSTANT_P and OVERFLOW_P are used during constant
7243 expression evaluation of subexpressions of ARG_SIZE. */
7245 static tree
7246 build_new_constexpr_heap_type (const constexpr_ctx *ctx, tree elt_type,
7247 tree cookie_size, tree full_size, tree arg_size,
7248 bool *non_constant_p, bool *overflow_p)
7250 gcc_assert (cookie_size == NULL_TREE || tree_fits_uhwi_p (cookie_size));
7251 gcc_assert (tree_fits_uhwi_p (full_size));
7252 unsigned HOST_WIDE_INT csz = cookie_size ? tree_to_uhwi (cookie_size) : 0;
7253 if (arg_size)
7255 STRIP_NOPS (arg_size);
7256 if (cookie_size)
7258 if (TREE_CODE (arg_size) != PLUS_EXPR)
7259 arg_size = NULL_TREE;
7260 else if (TREE_CODE (TREE_OPERAND (arg_size, 0)) == INTEGER_CST
7261 && tree_int_cst_equal (cookie_size,
7262 TREE_OPERAND (arg_size, 0)))
7264 arg_size = TREE_OPERAND (arg_size, 1);
7265 STRIP_NOPS (arg_size);
7267 else if (TREE_CODE (TREE_OPERAND (arg_size, 1)) == INTEGER_CST
7268 && tree_int_cst_equal (cookie_size,
7269 TREE_OPERAND (arg_size, 1)))
7271 arg_size = TREE_OPERAND (arg_size, 0);
7272 STRIP_NOPS (arg_size);
7274 else
7275 arg_size = NULL_TREE;
7277 if (arg_size && TREE_CODE (arg_size) == MULT_EXPR)
7279 tree op0 = TREE_OPERAND (arg_size, 0);
7280 tree op1 = TREE_OPERAND (arg_size, 1);
7281 if (integer_zerop (op0))
7282 arg_size
7283 = cxx_eval_constant_expression (ctx, op1, vc_prvalue,
7284 non_constant_p, overflow_p);
7285 else if (integer_zerop (op1))
7286 arg_size
7287 = cxx_eval_constant_expression (ctx, op0, vc_prvalue,
7288 non_constant_p, overflow_p);
7289 else
7290 arg_size = NULL_TREE;
7292 else
7293 arg_size = NULL_TREE;
7296 unsigned HOST_WIDE_INT fsz = tree_to_uhwi (arg_size ? arg_size : full_size);
7297 if (!arg_size)
7299 unsigned HOST_WIDE_INT esz = int_size_in_bytes (elt_type);
7300 gcc_assert (fsz >= csz);
7301 fsz -= csz;
7302 if (esz)
7303 fsz /= esz;
7305 tree itype2 = build_index_type (size_int (fsz - 1));
7306 if (!cookie_size)
7307 return build_cplus_array_type (elt_type, itype2);
7308 return build_new_constexpr_heap_type (elt_type, cookie_size, itype2);
7311 /* Attempt to reduce the expression T to a constant value.
7312 On failure, issue diagnostic and return error_mark_node. */
7313 /* FIXME unify with c_fully_fold */
7314 /* FIXME overflow_p is too global */
7316 static tree
7317 cxx_eval_constant_expression (const constexpr_ctx *ctx, tree t,
7318 value_cat lval,
7319 bool *non_constant_p, bool *overflow_p,
7320 tree *jump_target /* = NULL */)
7322 if (jump_target && *jump_target)
7324 /* If we are jumping, ignore all statements/expressions except those
7325 that could have LABEL_EXPR or CASE_LABEL_EXPR in their bodies. */
7326 switch (TREE_CODE (t))
7328 case BIND_EXPR:
7329 case STATEMENT_LIST:
7330 case LOOP_EXPR:
7331 case COND_EXPR:
7332 case IF_STMT:
7333 case DO_STMT:
7334 case WHILE_STMT:
7335 case FOR_STMT:
7336 break;
7337 case LABEL_EXPR:
7338 case CASE_LABEL_EXPR:
7339 if (label_matches (ctx, jump_target, t))
7340 /* Found it. */
7341 *jump_target = NULL_TREE;
7342 return NULL_TREE;
7343 default:
7344 return NULL_TREE;
7347 if (error_operand_p (t))
7349 *non_constant_p = true;
7350 return t;
7353 /* Change the input location to the currently processed expression for
7354 better error messages when a subexpression has no location. */
7355 location_t loc = cp_expr_loc_or_input_loc (t);
7356 iloc_sentinel sentinel (loc);
7358 STRIP_ANY_LOCATION_WRAPPER (t);
7360 if (CONSTANT_CLASS_P (t))
7362 if (TREE_OVERFLOW (t))
7364 if (!ctx->quiet)
7365 permerror (input_location, "overflow in constant expression");
7366 if (!flag_permissive || ctx->quiet)
7367 *overflow_p = true;
7370 if (TREE_CODE (t) == INTEGER_CST
7371 && TYPE_PTR_P (TREE_TYPE (t))
7372 /* INTEGER_CST with pointer-to-method type is only used
7373 for a virtual method in a pointer to member function.
7374 Don't reject those. */
7375 && TREE_CODE (TREE_TYPE (TREE_TYPE (t))) != METHOD_TYPE
7376 && !integer_zerop (t))
7378 if (!ctx->quiet)
7379 error ("value %qE of type %qT is not a constant expression",
7380 t, TREE_TYPE (t));
7381 *non_constant_p = true;
7384 return t;
7387 /* Avoid excessively long constexpr evaluations. */
7388 if (++ctx->global->constexpr_ops_count >= constexpr_ops_limit)
7390 if (!ctx->quiet)
7391 error_at (loc,
7392 "%<constexpr%> evaluation operation count exceeds limit of "
7393 "%wd (use %<-fconstexpr-ops-limit=%> to increase the limit)",
7394 constexpr_ops_limit);
7395 ctx->global->constexpr_ops_count = INTTYPE_MINIMUM (HOST_WIDE_INT);
7396 *non_constant_p = true;
7397 return t;
7400 constexpr_ctx new_ctx;
7401 tree r = t;
7403 tree_code tcode = TREE_CODE (t);
7404 switch (tcode)
7406 case RESULT_DECL:
7407 if (lval)
7408 return t;
7409 /* We ask for an rvalue for the RESULT_DECL when indirecting
7410 through an invisible reference, or in named return value
7411 optimization. */
7412 if (tree v = ctx->global->get_value (t))
7413 return v;
7414 else
7416 if (!ctx->quiet)
7417 error ("%qE is not a constant expression", t);
7418 *non_constant_p = true;
7420 break;
7422 case VAR_DECL:
7423 if (DECL_HAS_VALUE_EXPR_P (t))
7425 if (is_normal_capture_proxy (t)
7426 && current_function_decl == DECL_CONTEXT (t))
7428 /* Function parms aren't constexpr within the function
7429 definition, so don't try to look at the closure. But if the
7430 captured variable is constant, try to evaluate it directly. */
7431 r = DECL_CAPTURED_VARIABLE (t);
7432 tree type = TREE_TYPE (t);
7433 if (TYPE_REF_P (type) != TYPE_REF_P (TREE_TYPE (r)))
7435 /* Adjust r to match the reference-ness of t. */
7436 if (TYPE_REF_P (type))
7437 r = build_address (r);
7438 else
7439 r = convert_from_reference (r);
7442 else
7443 r = DECL_VALUE_EXPR (t);
7444 return cxx_eval_constant_expression (ctx, r, lval, non_constant_p,
7445 overflow_p);
7447 /* fall through */
7448 case CONST_DECL:
7449 /* We used to not check lval for CONST_DECL, but darwin.cc uses
7450 CONST_DECL for aggregate constants. */
7451 if (lval)
7452 return t;
7453 else if (t == ctx->object)
7454 return ctx->ctor;
7455 if (VAR_P (t))
7457 if (tree v = ctx->global->get_value (t))
7459 r = v;
7460 break;
7462 if (ctx->global->is_outside_lifetime (t))
7464 if (!ctx->quiet)
7465 outside_lifetime_error (loc, t);
7466 *non_constant_p = true;
7467 break;
7470 if (ctx->manifestly_const_eval == mce_true)
7471 maybe_warn_about_constant_value (loc, t);
7472 if (COMPLETE_TYPE_P (TREE_TYPE (t))
7473 && is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
7475 /* If the class is empty, we aren't actually loading anything. */
7476 r = build_constructor (TREE_TYPE (t), NULL);
7477 TREE_CONSTANT (r) = true;
7479 else if (ctx->strict)
7480 r = decl_really_constant_value (t, /*unshare_p=*/false);
7481 else
7482 r = decl_constant_value (t, /*unshare_p=*/false);
7483 if (TREE_CODE (r) == TARGET_EXPR
7484 && TREE_CODE (TARGET_EXPR_INITIAL (r)) == CONSTRUCTOR)
7485 r = TARGET_EXPR_INITIAL (r);
7486 if (DECL_P (r)
7487 /* P2280 allows references to unknown. */
7488 && !(VAR_P (t) && TYPE_REF_P (TREE_TYPE (t))))
7490 if (!ctx->quiet)
7491 non_const_var_error (loc, r, /*fundef_p*/false);
7492 *non_constant_p = true;
7494 break;
7496 case DEBUG_BEGIN_STMT:
7497 /* ??? It might be nice to retain this information somehow, so
7498 as to be able to step into a constexpr function call. */
7499 /* Fall through. */
7501 case FUNCTION_DECL:
7502 case TEMPLATE_DECL:
7503 case LABEL_DECL:
7504 case LABEL_EXPR:
7505 case CASE_LABEL_EXPR:
7506 case PREDICT_EXPR:
7507 return t;
7509 case PARM_DECL:
7510 if (lval && !TYPE_REF_P (TREE_TYPE (t)))
7512 /* glvalue use. */
7513 if (TREE_ADDRESSABLE (TREE_TYPE (t)))
7514 if (tree v = ctx->global->get_value (t))
7515 r = v;
7517 else if (tree v = ctx->global->get_value (t))
7519 r = v;
7520 if (TREE_ADDRESSABLE (TREE_TYPE (t)))
7521 r = cxx_eval_constant_expression (ctx, r, vc_prvalue,
7522 non_constant_p, overflow_p);
7524 else if (lval)
7525 /* Defer in case this is only used for its type. */;
7526 else if (ctx->global->is_outside_lifetime (t))
7528 if (!ctx->quiet)
7529 outside_lifetime_error (loc, t);
7530 *non_constant_p = true;
7531 break;
7533 else if (COMPLETE_TYPE_P (TREE_TYPE (t))
7534 && is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
7536 /* If the class is empty, we aren't actually loading anything. */
7537 r = build_constructor (TREE_TYPE (t), NULL);
7538 TREE_CONSTANT (r) = true;
7540 else if (TYPE_REF_P (TREE_TYPE (t)))
7541 /* P2280 allows references to unknown... */;
7542 else if (is_this_parameter (t))
7543 /* ...as well as the this pointer. */;
7544 else
7546 if (!ctx->quiet)
7547 error ("%qE is not a constant expression", t);
7548 *non_constant_p = true;
7550 break;
7552 case CALL_EXPR:
7553 case AGGR_INIT_EXPR:
7554 r = cxx_eval_call_expression (ctx, t, lval,
7555 non_constant_p, overflow_p);
7556 break;
7558 case DECL_EXPR:
7560 r = DECL_EXPR_DECL (t);
7561 if (TREE_CODE (r) == USING_DECL)
7563 r = void_node;
7564 break;
7567 if (VAR_P (r)
7568 && (TREE_STATIC (r)
7569 || (CP_DECL_THREAD_LOCAL_P (r) && !DECL_REALLY_EXTERN (r)))
7570 /* Allow __FUNCTION__ etc. */
7571 && !DECL_ARTIFICIAL (r)
7572 && !decl_constant_var_p (r))
7574 if (!ctx->quiet)
7576 if (CP_DECL_THREAD_LOCAL_P (r))
7577 error_at (loc, "control passes through definition of %qD "
7578 "with thread storage duration", r);
7579 else
7580 error_at (loc, "control passes through definition of %qD "
7581 "with static storage duration", r);
7583 *non_constant_p = true;
7584 break;
7587 /* make_rtl_for_nonlocal_decl could have deferred emission of
7588 a local static var, but if it appears in a statement expression
7589 which is constant expression evaluated to e.g. just the address
7590 of the variable, its DECL_EXPR will never be seen during
7591 gimple lowering's record_vars_into as the statement expression
7592 will not be in the IL at all. */
7593 if (VAR_P (r)
7594 && TREE_STATIC (r)
7595 && !DECL_REALLY_EXTERN (r)
7596 && DECL_FUNCTION_SCOPE_P (r)
7597 && !var_in_maybe_constexpr_fn (r)
7598 && decl_constant_var_p (r))
7600 varpool_node *node = varpool_node::get (r);
7601 if (node == NULL || !node->definition)
7602 rest_of_decl_compilation (r, 0, at_eof);
7605 if (AGGREGATE_TYPE_P (TREE_TYPE (r))
7606 || VECTOR_TYPE_P (TREE_TYPE (r)))
7608 new_ctx = *ctx;
7609 new_ctx.object = r;
7610 new_ctx.ctor = build_constructor (TREE_TYPE (r), NULL);
7611 CONSTRUCTOR_NO_CLEARING (new_ctx.ctor) = true;
7612 ctx->global->put_value (r, new_ctx.ctor);
7613 ctx = &new_ctx;
7616 if (tree init = DECL_INITIAL (r))
7618 init = cxx_eval_constant_expression (ctx, init, vc_prvalue,
7619 non_constant_p, overflow_p);
7620 /* Don't share a CONSTRUCTOR that might be changed. */
7621 init = unshare_constructor (init);
7622 /* Remember that a constant object's constructor has already
7623 run. */
7624 if (CLASS_TYPE_P (TREE_TYPE (r))
7625 && CP_TYPE_CONST_P (TREE_TYPE (r)))
7626 TREE_READONLY (init) = true;
7627 ctx->global->put_value (r, init);
7629 else if (ctx == &new_ctx)
7630 /* We gave it a CONSTRUCTOR above. */;
7631 else
7632 ctx->global->put_value (r, NULL_TREE);
7634 break;
7636 case TARGET_EXPR:
7638 tree type = TREE_TYPE (t);
7640 if (!literal_type_p (type))
7642 if (!ctx->quiet)
7644 auto_diagnostic_group d;
7645 error ("temporary of non-literal type %qT in a "
7646 "constant expression", type);
7647 explain_non_literal_class (type);
7649 *non_constant_p = true;
7650 break;
7652 gcc_checking_assert (!TARGET_EXPR_DIRECT_INIT_P (t));
7653 /* Avoid evaluating a TARGET_EXPR more than once. */
7654 tree slot = TARGET_EXPR_SLOT (t);
7655 if (tree v = ctx->global->get_value (slot))
7657 if (lval)
7658 return slot;
7659 r = v;
7660 break;
7662 if ((AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type)))
7664 /* We're being expanded without an explicit target, so start
7665 initializing a new object; expansion with an explicit target
7666 strips the TARGET_EXPR before we get here. */
7667 new_ctx = *ctx;
7668 /* Link CTX to NEW_CTX so that lookup_placeholder can resolve
7669 any PLACEHOLDER_EXPR within the initializer that refers to the
7670 former object under construction. */
7671 new_ctx.parent = ctx;
7672 new_ctx.ctor = build_constructor (type, NULL);
7673 CONSTRUCTOR_NO_CLEARING (new_ctx.ctor) = true;
7674 new_ctx.object = slot;
7675 ctx->global->put_value (new_ctx.object, new_ctx.ctor);
7676 ctx = &new_ctx;
7678 /* Pass vc_prvalue because this indicates
7679 initialization of a temporary. */
7680 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1), vc_prvalue,
7681 non_constant_p, overflow_p);
7682 if (*non_constant_p)
7683 break;
7684 /* If the initializer is complex, evaluate it to initialize slot. */
7685 bool is_complex = target_expr_needs_replace (t);
7686 if (!is_complex)
7688 r = unshare_constructor (r);
7689 /* Adjust the type of the result to the type of the temporary. */
7690 r = adjust_temp_type (type, r);
7691 ctx->global->put_value (slot, r);
7693 if (TARGET_EXPR_CLEANUP (t) && !CLEANUP_EH_ONLY (t))
7694 ctx->global->cleanups->safe_push (TARGET_EXPR_CLEANUP (t));
7695 if (ctx->save_exprs)
7696 ctx->save_exprs->safe_push (slot);
7697 if (lval)
7698 return slot;
7699 if (is_complex)
7700 r = ctx->global->get_value (slot);
7702 break;
7704 case INIT_EXPR:
7705 case MODIFY_EXPR:
7706 gcc_assert (jump_target == NULL || *jump_target == NULL_TREE);
7707 r = cxx_eval_store_expression (ctx, t, lval,
7708 non_constant_p, overflow_p);
7709 break;
7711 case SCOPE_REF:
7712 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
7713 lval,
7714 non_constant_p, overflow_p);
7715 break;
7717 case RETURN_EXPR:
7718 if (TREE_OPERAND (t, 0) != NULL_TREE)
7719 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
7720 lval,
7721 non_constant_p, overflow_p);
7722 /* FALLTHRU */
7723 case BREAK_STMT:
7724 case CONTINUE_STMT:
7725 if (jump_target)
7726 *jump_target = t;
7727 else
7729 /* Can happen with ({ return true; }) && false; passed to
7730 maybe_constant_value. There is nothing to jump over in this
7731 case, and the bug will be diagnosed later. */
7732 gcc_assert (ctx->quiet);
7733 *non_constant_p = true;
7735 break;
7737 case SAVE_EXPR:
7738 /* Avoid evaluating a SAVE_EXPR more than once. */
7739 if (tree v = ctx->global->get_value (t))
7740 r = v;
7741 else
7743 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), vc_prvalue,
7744 non_constant_p, overflow_p);
7745 if (*non_constant_p)
7746 break;
7747 ctx->global->put_value (t, r);
7748 if (ctx->save_exprs)
7749 ctx->save_exprs->safe_push (t);
7751 break;
7753 case TRY_CATCH_EXPR:
7754 if (TREE_OPERAND (t, 0) == NULL_TREE)
7756 r = void_node;
7757 break;
7759 /* FALLTHRU */
7760 case NON_LVALUE_EXPR:
7761 case TRY_BLOCK:
7762 case MUST_NOT_THROW_EXPR:
7763 case EXPR_STMT:
7764 case EH_SPEC_BLOCK:
7765 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
7766 lval,
7767 non_constant_p, overflow_p,
7768 jump_target);
7769 break;
7771 case CLEANUP_POINT_EXPR:
7773 auto_vec<tree, 2> cleanups;
7774 vec<tree> *prev_cleanups = ctx->global->cleanups;
7775 ctx->global->cleanups = &cleanups;
7777 auto_vec<tree, 10> save_exprs;
7778 constexpr_ctx new_ctx = *ctx;
7779 new_ctx.save_exprs = &save_exprs;
7781 r = cxx_eval_constant_expression (&new_ctx, TREE_OPERAND (t, 0),
7782 lval,
7783 non_constant_p, overflow_p,
7784 jump_target);
7786 ctx->global->cleanups = prev_cleanups;
7787 unsigned int i;
7788 tree cleanup;
7789 /* Evaluate the cleanups. */
7790 FOR_EACH_VEC_ELT_REVERSE (cleanups, i, cleanup)
7791 cxx_eval_constant_expression (&new_ctx, cleanup, vc_discard,
7792 non_constant_p, overflow_p);
7794 /* Forget SAVE_EXPRs and TARGET_EXPRs created by this
7795 full-expression. */
7796 for (tree save_expr : save_exprs)
7797 destroy_value_checked (ctx, save_expr, non_constant_p);
7799 break;
7801 case TRY_FINALLY_EXPR:
7802 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
7803 non_constant_p, overflow_p,
7804 jump_target);
7805 if (!*non_constant_p)
7806 /* Also evaluate the cleanup. */
7807 cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1), vc_discard,
7808 non_constant_p, overflow_p);
7809 break;
7811 case CLEANUP_STMT:
7812 r = cxx_eval_constant_expression (ctx, CLEANUP_BODY (t), lval,
7813 non_constant_p, overflow_p,
7814 jump_target);
7815 if (!CLEANUP_EH_ONLY (t) && !*non_constant_p)
7817 iloc_sentinel ils (loc);
7818 /* Also evaluate the cleanup. */
7819 cxx_eval_constant_expression (ctx, CLEANUP_EXPR (t), vc_discard,
7820 non_constant_p, overflow_p);
7822 break;
7824 /* These differ from cxx_eval_unary_expression in that this doesn't
7825 check for a constant operand or result; an address can be
7826 constant without its operand being, and vice versa. */
7827 case MEM_REF:
7828 case INDIRECT_REF:
7829 r = cxx_eval_indirect_ref (ctx, t, lval,
7830 non_constant_p, overflow_p);
7831 break;
7833 case ADDR_EXPR:
7835 tree oldop = TREE_OPERAND (t, 0);
7836 tree op = cxx_eval_constant_expression (ctx, oldop, vc_glvalue,
7837 non_constant_p, overflow_p);
7838 /* Don't VERIFY_CONSTANT here. */
7839 if (*non_constant_p)
7840 return t;
7841 gcc_checking_assert (TREE_CODE (op) != CONSTRUCTOR);
7842 /* This function does more aggressive folding than fold itself. */
7843 r = build_fold_addr_expr_with_type (op, TREE_TYPE (t));
7844 if (TREE_CODE (r) == ADDR_EXPR && TREE_OPERAND (r, 0) == oldop)
7846 ggc_free (r);
7847 return t;
7849 break;
7852 case REALPART_EXPR:
7853 case IMAGPART_EXPR:
7854 if (lval)
7856 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
7857 non_constant_p, overflow_p);
7858 if (r == error_mark_node)
7860 else if (r == TREE_OPERAND (t, 0) || lval == vc_discard)
7861 r = t;
7862 else
7863 r = fold_build1 (TREE_CODE (t), TREE_TYPE (t), r);
7864 break;
7866 /* FALLTHRU */
7867 case CONJ_EXPR:
7868 case FIX_TRUNC_EXPR:
7869 case FLOAT_EXPR:
7870 case NEGATE_EXPR:
7871 case ABS_EXPR:
7872 case ABSU_EXPR:
7873 case BIT_NOT_EXPR:
7874 case TRUTH_NOT_EXPR:
7875 case FIXED_CONVERT_EXPR:
7876 r = cxx_eval_unary_expression (ctx, t, lval,
7877 non_constant_p, overflow_p);
7878 break;
7880 case SIZEOF_EXPR:
7881 r = fold_sizeof_expr (t);
7882 /* In a template, fold_sizeof_expr may merely create a new SIZEOF_EXPR,
7883 which could lead to an infinite recursion. */
7884 if (TREE_CODE (r) != SIZEOF_EXPR)
7885 r = cxx_eval_constant_expression (ctx, r, lval,
7886 non_constant_p, overflow_p,
7887 jump_target);
7888 else
7890 *non_constant_p = true;
7891 gcc_assert (ctx->quiet);
7894 break;
7896 case COMPOUND_EXPR:
7898 /* check_return_expr sometimes wraps a TARGET_EXPR in a
7899 COMPOUND_EXPR; don't get confused. Also handle EMPTY_CLASS_EXPR
7900 introduced by build_call_a. */
7901 tree op0 = TREE_OPERAND (t, 0);
7902 tree op1 = TREE_OPERAND (t, 1);
7903 STRIP_NOPS (op1);
7904 if ((TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
7905 || TREE_CODE (op1) == EMPTY_CLASS_EXPR)
7906 r = cxx_eval_constant_expression (ctx, op0,
7907 lval, non_constant_p, overflow_p,
7908 jump_target);
7909 else
7911 /* Check that the LHS is constant and then discard it. */
7912 cxx_eval_constant_expression (ctx, op0, vc_discard,
7913 non_constant_p, overflow_p,
7914 jump_target);
7915 if (*non_constant_p)
7916 return t;
7917 op1 = TREE_OPERAND (t, 1);
7918 r = cxx_eval_constant_expression (ctx, op1,
7919 lval, non_constant_p, overflow_p,
7920 jump_target);
7923 break;
7925 case POINTER_PLUS_EXPR:
7926 case POINTER_DIFF_EXPR:
7927 case PLUS_EXPR:
7928 case MINUS_EXPR:
7929 case MULT_EXPR:
7930 case TRUNC_DIV_EXPR:
7931 case CEIL_DIV_EXPR:
7932 case FLOOR_DIV_EXPR:
7933 case ROUND_DIV_EXPR:
7934 case TRUNC_MOD_EXPR:
7935 case CEIL_MOD_EXPR:
7936 case ROUND_MOD_EXPR:
7937 case RDIV_EXPR:
7938 case EXACT_DIV_EXPR:
7939 case MIN_EXPR:
7940 case MAX_EXPR:
7941 case LSHIFT_EXPR:
7942 case RSHIFT_EXPR:
7943 case LROTATE_EXPR:
7944 case RROTATE_EXPR:
7945 case BIT_IOR_EXPR:
7946 case BIT_XOR_EXPR:
7947 case BIT_AND_EXPR:
7948 case TRUTH_XOR_EXPR:
7949 case LT_EXPR:
7950 case LE_EXPR:
7951 case GT_EXPR:
7952 case GE_EXPR:
7953 case EQ_EXPR:
7954 case NE_EXPR:
7955 case SPACESHIP_EXPR:
7956 case UNORDERED_EXPR:
7957 case ORDERED_EXPR:
7958 case UNLT_EXPR:
7959 case UNLE_EXPR:
7960 case UNGT_EXPR:
7961 case UNGE_EXPR:
7962 case UNEQ_EXPR:
7963 case LTGT_EXPR:
7964 case RANGE_EXPR:
7965 case COMPLEX_EXPR:
7966 r = cxx_eval_binary_expression (ctx, t, lval,
7967 non_constant_p, overflow_p);
7968 break;
7970 /* fold can introduce non-IF versions of these; still treat them as
7971 short-circuiting. */
7972 case TRUTH_AND_EXPR:
7973 case TRUTH_ANDIF_EXPR:
7974 r = cxx_eval_logical_expression (ctx, t, boolean_false_node,
7975 boolean_true_node,
7976 non_constant_p, overflow_p);
7977 break;
7979 case TRUTH_OR_EXPR:
7980 case TRUTH_ORIF_EXPR:
7981 r = cxx_eval_logical_expression (ctx, t, boolean_true_node,
7982 boolean_false_node,
7983 non_constant_p, overflow_p);
7984 break;
7986 case ARRAY_REF:
7987 r = cxx_eval_array_reference (ctx, t, lval,
7988 non_constant_p, overflow_p);
7989 break;
7991 case COMPONENT_REF:
7992 if (is_overloaded_fn (t))
7994 /* We can only get here in checking mode via
7995 build_non_dependent_expr, because any expression that
7996 calls or takes the address of the function will have
7997 pulled a FUNCTION_DECL out of the COMPONENT_REF. */
7998 gcc_checking_assert (ctx->quiet || errorcount);
7999 *non_constant_p = true;
8000 return t;
8002 r = cxx_eval_component_reference (ctx, t, lval,
8003 non_constant_p, overflow_p);
8004 break;
8006 case BIT_FIELD_REF:
8007 r = cxx_eval_bit_field_ref (ctx, t, lval,
8008 non_constant_p, overflow_p);
8009 break;
8011 case COND_EXPR:
8012 case IF_STMT:
8013 if (jump_target && *jump_target)
8015 tree orig_jump = *jump_target;
8016 tree arg = ((TREE_CODE (t) != IF_STMT || TREE_OPERAND (t, 1))
8017 ? TREE_OPERAND (t, 1) : void_node);
8018 /* When jumping to a label, the label might be either in the
8019 then or else blocks, so process then block first in skipping
8020 mode first, and if we are still in the skipping mode at its end,
8021 process the else block too. */
8022 r = cxx_eval_constant_expression (ctx, arg, lval, non_constant_p,
8023 overflow_p, jump_target);
8024 /* It's possible that we found the label in the then block. But
8025 it could have been followed by another jumping statement, e.g.
8026 say we're looking for case 1:
8027 if (cond)
8029 // skipped statements
8030 case 1:; // clears up *jump_target
8031 return 1; // and sets it to a RETURN_EXPR
8033 else { ... }
8034 in which case we need not go looking to the else block.
8035 (goto is not allowed in a constexpr function.) */
8036 if (*jump_target == orig_jump)
8038 arg = ((TREE_CODE (t) != IF_STMT || TREE_OPERAND (t, 2))
8039 ? TREE_OPERAND (t, 2) : void_node);
8040 r = cxx_eval_constant_expression (ctx, arg, lval, non_constant_p,
8041 overflow_p, jump_target);
8043 break;
8045 r = cxx_eval_conditional_expression (ctx, t, lval,
8046 non_constant_p, overflow_p,
8047 jump_target);
8048 break;
8049 case VEC_COND_EXPR:
8050 r = cxx_eval_vector_conditional_expression (ctx, t, non_constant_p,
8051 overflow_p);
8052 break;
8054 case CONSTRUCTOR:
8055 if (TREE_CONSTANT (t) && reduced_constant_expression_p (t))
8057 /* Don't re-process a constant CONSTRUCTOR. */
8058 verify_constructor_flags (t);
8059 if (TREE_CONSTANT (t))
8060 return t;
8062 r = cxx_eval_bare_aggregate (ctx, t, lval,
8063 non_constant_p, overflow_p);
8064 break;
8066 case VEC_INIT_EXPR:
8067 /* We can get this in a defaulted constructor for a class with a
8068 non-static data member of array type. Either the initializer will
8069 be NULL, meaning default-initialization, or it will be an lvalue
8070 or xvalue of the same type, meaning direct-initialization from the
8071 corresponding member. */
8072 r = cxx_eval_vec_init (ctx, t, lval,
8073 non_constant_p, overflow_p);
8074 break;
8076 case VEC_PERM_EXPR:
8077 r = cxx_eval_trinary_expression (ctx, t, lval,
8078 non_constant_p, overflow_p);
8079 break;
8081 case PAREN_EXPR:
8082 gcc_assert (!REF_PARENTHESIZED_P (t));
8083 /* A PAREN_EXPR resulting from __builtin_assoc_barrier has no effect in
8084 constant expressions since it's unaffected by -fassociative-math. */
8085 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
8086 non_constant_p, overflow_p);
8087 break;
8089 case NOP_EXPR:
8090 if (REINTERPRET_CAST_P (t))
8092 if (!ctx->quiet)
8093 error_at (loc,
8094 "%<reinterpret_cast%> is not a constant expression");
8095 *non_constant_p = true;
8096 return t;
8098 /* FALLTHROUGH. */
8099 case CONVERT_EXPR:
8100 case VIEW_CONVERT_EXPR:
8101 case UNARY_PLUS_EXPR:
8103 tree oldop = TREE_OPERAND (t, 0);
8105 tree op = cxx_eval_constant_expression (ctx, oldop,
8106 lval,
8107 non_constant_p, overflow_p);
8108 if (*non_constant_p)
8109 return t;
8110 tree type = TREE_TYPE (t);
8112 if (VOID_TYPE_P (type))
8113 return void_node;
8115 if (TREE_CODE (t) == CONVERT_EXPR
8116 && ARITHMETIC_TYPE_P (type)
8117 && INDIRECT_TYPE_P (TREE_TYPE (op))
8118 && ctx->manifestly_const_eval == mce_true)
8120 if (!ctx->quiet)
8121 error_at (loc,
8122 "conversion from pointer type %qT to arithmetic type "
8123 "%qT in a constant expression", TREE_TYPE (op), type);
8124 *non_constant_p = true;
8125 return t;
8128 /* [expr.const]: a conversion from type cv void* to a pointer-to-object
8129 type cannot be part of a core constant expression as a resolution to
8130 DR 1312. */
8131 if (TYPE_PTROB_P (type)
8132 && TYPE_PTR_P (TREE_TYPE (op))
8133 && VOID_TYPE_P (TREE_TYPE (TREE_TYPE (op)))
8134 /* Inside a call to std::construct_at,
8135 std::allocator<T>::{,de}allocate, or
8136 std::source_location::current, we permit casting from void*
8137 because that is compiler-generated code. */
8138 && !is_std_construct_at (ctx->call)
8139 && !is_std_allocator_allocate (ctx->call)
8140 && !is_std_source_location_current (ctx->call))
8142 /* Likewise, don't error when casting from void* when OP is
8143 &heap uninit and similar. */
8144 tree sop = tree_strip_nop_conversions (op);
8145 tree decl = NULL_TREE;
8146 if (TREE_CODE (sop) == ADDR_EXPR)
8147 decl = TREE_OPERAND (sop, 0);
8148 if (decl
8149 && VAR_P (decl)
8150 && DECL_ARTIFICIAL (decl)
8151 && (DECL_NAME (decl) == heap_identifier
8152 || DECL_NAME (decl) == heap_uninit_identifier
8153 || DECL_NAME (decl) == heap_vec_identifier
8154 || DECL_NAME (decl) == heap_vec_uninit_identifier))
8155 /* OK */;
8156 /* P2738 (C++26): a conversion from a prvalue P of type "pointer to
8157 cv void" to a pointer-to-object type T unless P points to an
8158 object whose type is similar to T. */
8159 else if (cxx_dialect > cxx23)
8161 r = cxx_fold_indirect_ref (ctx, loc, TREE_TYPE (type), sop);
8162 if (r)
8164 r = build1 (ADDR_EXPR, type, r);
8165 break;
8167 if (!ctx->quiet)
8169 if (TREE_CODE (sop) == ADDR_EXPR)
8171 auto_diagnostic_group d;
8172 error_at (loc, "cast from %qT is not allowed in a "
8173 "constant expression because "
8174 "pointed-to type %qT is not similar to %qT",
8175 TREE_TYPE (op), TREE_TYPE (TREE_TYPE (sop)),
8176 TREE_TYPE (type));
8177 tree obj = build_fold_indirect_ref (sop);
8178 inform (DECL_SOURCE_LOCATION (obj),
8179 "pointed-to object declared here");
8181 else
8183 gcc_assert (integer_zerop (sop));
8184 error_at (loc, "cast from %qT is not allowed in a "
8185 "constant expression because "
8186 "%qE does not point to an object",
8187 TREE_TYPE (op), oldop);
8190 *non_constant_p = true;
8191 return t;
8193 else
8195 if (!ctx->quiet)
8196 error_at (loc, "cast from %qT is not allowed in a "
8197 "constant expression before C++26",
8198 TREE_TYPE (op));
8199 *non_constant_p = true;
8200 return t;
8204 if (TREE_CODE (op) == PTRMEM_CST && !TYPE_PTRMEM_P (type))
8206 op = cplus_expand_constant (op);
8207 if (TREE_CODE (op) == PTRMEM_CST)
8209 if (!ctx->quiet)
8210 error_at (loc, "%qE is not a constant expression when the "
8211 "class %qT is still incomplete", op,
8212 PTRMEM_CST_CLASS (op));
8213 *non_constant_p = true;
8214 return t;
8218 if (TREE_CODE (op) == PTRMEM_CST && tcode == NOP_EXPR)
8220 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (op))
8221 && !can_convert_qual (type, op))
8222 op = cplus_expand_constant (op);
8223 return cp_fold_convert (type, op);
8226 if (INDIRECT_TYPE_P (type) && TREE_CODE (op) == INTEGER_CST)
8228 if (integer_zerop (op))
8230 if (TYPE_REF_P (type))
8232 if (!ctx->quiet)
8233 error_at (loc, "dereferencing a null pointer");
8234 *non_constant_p = true;
8235 return t;
8238 else
8240 /* This detects for example:
8241 reinterpret_cast<void*>(sizeof 0)
8243 if (!ctx->quiet)
8244 error_at (loc, "%<reinterpret_cast<%T>(%E)%> is not "
8245 "a constant expression",
8246 type, op);
8247 *non_constant_p = true;
8248 return t;
8252 if (INDIRECT_TYPE_P (type)
8253 && TREE_CODE (op) == NOP_EXPR
8254 && TREE_TYPE (op) == ptr_type_node
8255 && TREE_CODE (TREE_OPERAND (op, 0)) == ADDR_EXPR
8256 && VAR_P (TREE_OPERAND (TREE_OPERAND (op, 0), 0))
8257 && (DECL_NAME (TREE_OPERAND (TREE_OPERAND (op, 0),
8258 0)) == heap_uninit_identifier
8259 || DECL_NAME (TREE_OPERAND (TREE_OPERAND (op, 0),
8260 0)) == heap_vec_uninit_identifier))
8262 tree var = TREE_OPERAND (TREE_OPERAND (op, 0), 0);
8263 tree var_size = TYPE_SIZE_UNIT (TREE_TYPE (var));
8264 tree elt_type = TREE_TYPE (type);
8265 tree cookie_size = NULL_TREE;
8266 tree arg_size = NULL_TREE;
8267 if (TREE_CODE (elt_type) == RECORD_TYPE
8268 && TYPE_NAME (elt_type) == heap_identifier)
8270 tree fld1 = TYPE_FIELDS (elt_type);
8271 tree fld2 = DECL_CHAIN (fld1);
8272 elt_type = TREE_TYPE (TREE_TYPE (fld2));
8273 cookie_size = TYPE_SIZE_UNIT (TREE_TYPE (fld1));
8275 DECL_NAME (var)
8276 = (DECL_NAME (var) == heap_uninit_identifier
8277 ? heap_identifier : heap_vec_identifier);
8278 /* For zero sized elt_type, try to recover how many outer_nelts
8279 it should have. */
8280 if ((cookie_size ? tree_int_cst_equal (var_size, cookie_size)
8281 : integer_zerop (var_size))
8282 && !int_size_in_bytes (elt_type)
8283 && TREE_CODE (oldop) == CALL_EXPR
8284 && call_expr_nargs (oldop) >= 1)
8285 if (tree fun = get_function_named_in_call (oldop))
8286 if (cxx_replaceable_global_alloc_fn (fun)
8287 && IDENTIFIER_NEW_OP_P (DECL_NAME (fun)))
8288 arg_size = CALL_EXPR_ARG (oldop, 0);
8289 TREE_TYPE (var)
8290 = build_new_constexpr_heap_type (ctx, elt_type, cookie_size,
8291 var_size, arg_size,
8292 non_constant_p, overflow_p);
8293 TREE_TYPE (TREE_OPERAND (op, 0))
8294 = build_pointer_type (TREE_TYPE (var));
8297 if (op == oldop && tcode != UNARY_PLUS_EXPR)
8298 /* We didn't fold at the top so we could check for ptr-int
8299 conversion. */
8300 return fold (t);
8302 tree sop;
8304 /* Handle an array's bounds having been deduced after we built
8305 the wrapping expression. */
8306 if (same_type_ignoring_tlq_and_bounds_p (type, TREE_TYPE (op)))
8307 r = op;
8308 else if (sop = tree_strip_nop_conversions (op),
8309 sop != op && (same_type_ignoring_tlq_and_bounds_p
8310 (type, TREE_TYPE (sop))))
8311 r = sop;
8312 else if (tcode == UNARY_PLUS_EXPR)
8313 r = fold_convert (TREE_TYPE (t), op);
8314 else
8315 r = fold_build1 (tcode, type, op);
8317 /* Conversion of an out-of-range value has implementation-defined
8318 behavior; the language considers it different from arithmetic
8319 overflow, which is undefined. */
8320 if (TREE_OVERFLOW_P (r) && !TREE_OVERFLOW_P (op))
8321 TREE_OVERFLOW (r) = false;
8323 break;
8325 case EXCESS_PRECISION_EXPR:
8327 tree oldop = TREE_OPERAND (t, 0);
8329 tree op = cxx_eval_constant_expression (ctx, oldop,
8330 lval,
8331 non_constant_p, overflow_p);
8332 if (*non_constant_p)
8333 return t;
8334 r = fold_convert (TREE_TYPE (t), op);
8335 break;
8338 case EMPTY_CLASS_EXPR:
8339 /* Handle EMPTY_CLASS_EXPR produced by build_call_a by lowering
8340 it to an appropriate CONSTRUCTOR. */
8341 return build_constructor (TREE_TYPE (t), NULL);
8343 case STATEMENT_LIST:
8344 new_ctx = *ctx;
8345 new_ctx.ctor = new_ctx.object = NULL_TREE;
8346 return cxx_eval_statement_list (&new_ctx, t,
8347 non_constant_p, overflow_p, jump_target);
8349 case BIND_EXPR:
8350 /* Pre-emptively clear the vars declared by this BIND_EXPR from the value
8351 map, so that when checking whether they're already destroyed later we
8352 don't get confused by remnants of previous calls. */
8353 for (tree decl = BIND_EXPR_VARS (t); decl; decl = DECL_CHAIN (decl))
8354 ctx->global->clear_value (decl);
8355 r = cxx_eval_constant_expression (ctx, BIND_EXPR_BODY (t),
8356 lval,
8357 non_constant_p, overflow_p,
8358 jump_target);
8359 for (tree decl = BIND_EXPR_VARS (t); decl; decl = DECL_CHAIN (decl))
8360 destroy_value_checked (ctx, decl, non_constant_p);
8361 break;
8363 case PREINCREMENT_EXPR:
8364 case POSTINCREMENT_EXPR:
8365 case PREDECREMENT_EXPR:
8366 case POSTDECREMENT_EXPR:
8367 return cxx_eval_increment_expression (ctx, t,
8368 lval, non_constant_p, overflow_p);
8370 case LAMBDA_EXPR:
8371 case NEW_EXPR:
8372 case VEC_NEW_EXPR:
8373 case DELETE_EXPR:
8374 case VEC_DELETE_EXPR:
8375 case THROW_EXPR:
8376 case MODOP_EXPR:
8377 /* GCC internal stuff. */
8378 case VA_ARG_EXPR:
8379 case BASELINK:
8380 case OFFSET_REF:
8381 if (!ctx->quiet)
8382 error_at (loc, "expression %qE is not a constant expression", t);
8383 *non_constant_p = true;
8384 break;
8386 case OBJ_TYPE_REF:
8387 /* Virtual function lookup. We don't need to do anything fancy. */
8388 return cxx_eval_constant_expression (ctx, OBJ_TYPE_REF_EXPR (t),
8389 lval, non_constant_p, overflow_p);
8391 case PLACEHOLDER_EXPR:
8392 /* Use of the value or address of the current object. */
8393 if (tree ctor = lookup_placeholder (ctx, lval, TREE_TYPE (t)))
8395 if (TREE_CODE (ctor) == CONSTRUCTOR)
8396 return ctor;
8397 else
8398 return cxx_eval_constant_expression (ctx, ctor, lval,
8399 non_constant_p, overflow_p);
8401 /* A placeholder without a referent. We can get here when
8402 checking whether NSDMIs are noexcept, or in massage_init_elt;
8403 just say it's non-constant for now. */
8404 gcc_assert (ctx->quiet);
8405 *non_constant_p = true;
8406 break;
8408 case EXIT_EXPR:
8410 tree cond = TREE_OPERAND (t, 0);
8411 cond = cxx_eval_constant_expression (ctx, cond, vc_prvalue,
8412 non_constant_p, overflow_p);
8413 VERIFY_CONSTANT (cond);
8414 if (integer_nonzerop (cond))
8415 *jump_target = t;
8417 break;
8419 case GOTO_EXPR:
8420 if (breaks (&TREE_OPERAND (t, 0))
8421 || continues (&TREE_OPERAND (t, 0)))
8422 *jump_target = TREE_OPERAND (t, 0);
8423 else
8425 gcc_assert (cxx_dialect >= cxx23);
8426 if (!ctx->quiet)
8427 error_at (loc, "%<goto%> is not a constant expression");
8428 *non_constant_p = true;
8430 break;
8432 case LOOP_EXPR:
8433 case DO_STMT:
8434 case WHILE_STMT:
8435 case FOR_STMT:
8436 cxx_eval_loop_expr (ctx, t,
8437 non_constant_p, overflow_p, jump_target);
8438 break;
8440 case SWITCH_EXPR:
8441 case SWITCH_STMT:
8442 cxx_eval_switch_expr (ctx, t,
8443 non_constant_p, overflow_p, jump_target);
8444 break;
8446 case REQUIRES_EXPR:
8447 /* It's possible to get a requires-expression in a constant
8448 expression. For example:
8450 template<typename T> concept bool C() {
8451 return requires (T t) { t; };
8454 template<typename T> requires !C<T>() void f(T);
8456 Normalization leaves f with the associated constraint
8457 '!requires (T t) { ... }' which is not transformed into
8458 a constraint. */
8459 if (!processing_template_decl)
8460 return evaluate_requires_expr (t);
8461 else
8462 *non_constant_p = true;
8463 return t;
8465 case ANNOTATE_EXPR:
8466 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
8467 lval,
8468 non_constant_p, overflow_p,
8469 jump_target);
8470 break;
8472 case USING_STMT:
8473 r = void_node;
8474 break;
8476 case ASSERTION_STMT:
8477 case PRECONDITION_STMT:
8478 case POSTCONDITION_STMT:
8480 contract_semantic semantic = get_contract_semantic (t);
8481 if (semantic == CCS_IGNORE)
8482 break;
8484 if (!cxx_eval_assert (ctx, CONTRACT_CONDITION (t),
8485 G_("contract predicate is false in "
8486 "constant expression"),
8487 EXPR_LOCATION (t), checked_contract_p (semantic),
8488 non_constant_p, overflow_p))
8489 *non_constant_p = true;
8490 r = void_node;
8492 break;
8494 case TEMPLATE_ID_EXPR:
8496 /* We can evaluate template-id that refers to a concept only if
8497 the template arguments are non-dependent. */
8498 tree id = unpack_concept_check (t);
8499 tree tmpl = TREE_OPERAND (id, 0);
8500 if (!concept_definition_p (tmpl))
8501 internal_error ("unexpected template-id %qE", t);
8503 if (function_concept_p (tmpl))
8505 if (!ctx->quiet)
8506 error_at (cp_expr_loc_or_input_loc (t),
8507 "function concept must be called");
8508 r = error_mark_node;
8509 break;
8512 if (!value_dependent_expression_p (t)
8513 && !uid_sensitive_constexpr_evaluation_p ())
8514 r = evaluate_concept_check (t);
8515 else
8516 *non_constant_p = true;
8518 break;
8521 case ASM_EXPR:
8522 if (!ctx->quiet)
8523 inline_asm_in_constexpr_error (loc, /*constexpr_fundef_p*/false);
8524 *non_constant_p = true;
8525 return t;
8527 case BIT_CAST_EXPR:
8528 if (lval)
8530 if (!ctx->quiet)
8531 error_at (EXPR_LOCATION (t),
8532 "address of a call to %qs is not a constant expression",
8533 "__builtin_bit_cast");
8534 *non_constant_p = true;
8535 return t;
8537 r = cxx_eval_bit_cast (ctx, t, non_constant_p, overflow_p);
8538 break;
8540 case OMP_PARALLEL:
8541 case OMP_TASK:
8542 case OMP_FOR:
8543 case OMP_SIMD:
8544 case OMP_DISTRIBUTE:
8545 case OMP_TASKLOOP:
8546 case OMP_LOOP:
8547 case OMP_TEAMS:
8548 case OMP_TARGET_DATA:
8549 case OMP_TARGET:
8550 case OMP_SECTIONS:
8551 case OMP_ORDERED:
8552 case OMP_CRITICAL:
8553 case OMP_SINGLE:
8554 case OMP_SCAN:
8555 case OMP_SCOPE:
8556 case OMP_SECTION:
8557 case OMP_STRUCTURED_BLOCK:
8558 case OMP_MASTER:
8559 case OMP_MASKED:
8560 case OMP_TASKGROUP:
8561 case OMP_TARGET_UPDATE:
8562 case OMP_TARGET_ENTER_DATA:
8563 case OMP_TARGET_EXIT_DATA:
8564 case OMP_ATOMIC:
8565 case OMP_ATOMIC_READ:
8566 case OMP_ATOMIC_CAPTURE_OLD:
8567 case OMP_ATOMIC_CAPTURE_NEW:
8568 case OMP_DEPOBJ:
8569 case OACC_PARALLEL:
8570 case OACC_KERNELS:
8571 case OACC_SERIAL:
8572 case OACC_DATA:
8573 case OACC_HOST_DATA:
8574 case OACC_LOOP:
8575 case OACC_CACHE:
8576 case OACC_DECLARE:
8577 case OACC_ENTER_DATA:
8578 case OACC_EXIT_DATA:
8579 case OACC_UPDATE:
8580 if (!ctx->quiet)
8581 error_at (EXPR_LOCATION (t),
8582 "statement is not a constant expression");
8583 *non_constant_p = true;
8584 break;
8586 default:
8587 if (STATEMENT_CODE_P (TREE_CODE (t)))
8589 /* This function doesn't know how to deal with pre-genericize
8590 statements; this can only happen with statement-expressions,
8591 so for now just fail. */
8592 if (!ctx->quiet)
8593 error_at (EXPR_LOCATION (t),
8594 "statement is not a constant expression");
8596 else
8597 internal_error ("unexpected expression %qE of kind %s", t,
8598 get_tree_code_name (TREE_CODE (t)));
8599 *non_constant_p = true;
8600 break;
8603 if (r == error_mark_node)
8604 *non_constant_p = true;
8606 if (*non_constant_p)
8607 return t;
8608 else
8609 return r;
8612 /* P0859: A function is needed for constant evaluation if it is a constexpr
8613 function that is named by an expression ([basic.def.odr]) that is
8614 potentially constant evaluated.
8616 So we need to instantiate any constexpr functions mentioned by the
8617 expression even if the definition isn't needed for evaluating the
8618 expression. */
8620 static tree
8621 instantiate_cx_fn_r (tree *tp, int *walk_subtrees, void */*data*/)
8623 if (TREE_CODE (*tp) == FUNCTION_DECL
8624 && DECL_DECLARED_CONSTEXPR_P (*tp)
8625 && !DECL_INITIAL (*tp)
8626 && !trivial_fn_p (*tp)
8627 && (DECL_TEMPLOID_INSTANTIATION (*tp) || DECL_DEFAULTED_FN (*tp))
8628 && !uid_sensitive_constexpr_evaluation_p ())
8630 ++function_depth;
8631 if (DECL_TEMPLOID_INSTANTIATION (*tp))
8632 instantiate_decl (*tp, /*defer_ok*/false, /*expl_inst*/false);
8633 else
8634 synthesize_method (*tp);
8635 --function_depth;
8637 else if (TREE_CODE (*tp) == CALL_EXPR
8638 || TREE_CODE (*tp) == AGGR_INIT_EXPR)
8640 if (EXPR_HAS_LOCATION (*tp))
8641 input_location = EXPR_LOCATION (*tp);
8644 if (!EXPR_P (*tp))
8645 *walk_subtrees = 0;
8647 return NULL_TREE;
8650 static void
8651 instantiate_constexpr_fns (tree t)
8653 location_t loc = input_location;
8654 cp_walk_tree_without_duplicates (&t, instantiate_cx_fn_r, NULL);
8655 input_location = loc;
8658 /* Look for heap variables in the expression *TP. */
8660 static tree
8661 find_heap_var_refs (tree *tp, int *walk_subtrees, void */*data*/)
8663 if (VAR_P (*tp)
8664 && (DECL_NAME (*tp) == heap_uninit_identifier
8665 || DECL_NAME (*tp) == heap_identifier
8666 || DECL_NAME (*tp) == heap_vec_uninit_identifier
8667 || DECL_NAME (*tp) == heap_vec_identifier
8668 || DECL_NAME (*tp) == heap_deleted_identifier))
8669 return *tp;
8671 if (TYPE_P (*tp))
8672 *walk_subtrees = 0;
8673 return NULL_TREE;
8676 /* Find immediate function decls in *TP if any. */
8678 static tree
8679 find_immediate_fndecl (tree *tp, int */*walk_subtrees*/, void */*data*/)
8681 if (TREE_CODE (*tp) == FUNCTION_DECL && DECL_IMMEDIATE_FUNCTION_P (*tp))
8682 return *tp;
8683 if (TREE_CODE (*tp) == PTRMEM_CST
8684 && TREE_CODE (PTRMEM_CST_MEMBER (*tp)) == FUNCTION_DECL
8685 && DECL_IMMEDIATE_FUNCTION_P (PTRMEM_CST_MEMBER (*tp)))
8686 return PTRMEM_CST_MEMBER (*tp);
8687 return NULL_TREE;
8690 /* T has TREE_CONSTANT set but has been deemed not a valid C++ constant
8691 expression. Return a version of T that has TREE_CONSTANT cleared. */
8693 static tree
8694 mark_non_constant (tree t)
8696 gcc_checking_assert (TREE_CONSTANT (t));
8698 /* This isn't actually constant, so unset TREE_CONSTANT.
8699 Don't clear TREE_CONSTANT on ADDR_EXPR, as the middle-end requires
8700 it to be set if it is invariant address, even when it is not
8701 a valid C++ constant expression. Wrap it with a NOP_EXPR
8702 instead. */
8703 if (EXPR_P (t) && TREE_CODE (t) != ADDR_EXPR)
8704 t = copy_node (t);
8705 else if (TREE_CODE (t) == CONSTRUCTOR)
8706 t = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (t), t);
8707 else
8708 t = build_nop (TREE_TYPE (t), t);
8709 TREE_CONSTANT (t) = false;
8710 return t;
8713 /* ALLOW_NON_CONSTANT is false if T is required to be a constant expression.
8714 STRICT has the same sense as for constant_value_1: true if we only allow
8715 conforming C++ constant expressions, or false if we want a constant value
8716 even if it doesn't conform.
8717 MANIFESTLY_CONST_EVAL is true if T is manifestly const-evaluated as
8718 per P0595 even when ALLOW_NON_CONSTANT is true.
8719 CONSTEXPR_DTOR is true when evaluating the dtor of a constexpr variable.
8720 OBJECT must be non-NULL in that case. */
8722 static tree
8723 cxx_eval_outermost_constant_expr (tree t, bool allow_non_constant,
8724 bool strict = true,
8725 mce_value manifestly_const_eval = mce_unknown,
8726 bool constexpr_dtor = false,
8727 tree object = NULL_TREE)
8729 auto_timevar time (TV_CONSTEXPR);
8731 bool non_constant_p = false;
8732 bool overflow_p = false;
8734 if (BRACE_ENCLOSED_INITIALIZER_P (t))
8736 gcc_checking_assert (allow_non_constant);
8737 return t;
8740 constexpr_global_ctx global_ctx;
8741 constexpr_ctx ctx = { &global_ctx, NULL, NULL, NULL, NULL, NULL, NULL,
8742 allow_non_constant, strict,
8743 !allow_non_constant ? mce_true : manifestly_const_eval };
8745 /* Turn off -frounding-math for manifestly constant evaluation. */
8746 warning_sentinel rm (flag_rounding_math,
8747 ctx.manifestly_const_eval == mce_true);
8748 tree type = initialized_type (t);
8749 tree r = t;
8750 bool is_consteval = false;
8751 if (VOID_TYPE_P (type))
8753 if (constexpr_dtor)
8754 /* Used for destructors of array elements. */
8755 type = TREE_TYPE (object);
8756 else
8758 if (cxx_dialect < cxx20)
8759 return t;
8760 if (TREE_CODE (t) != CALL_EXPR && TREE_CODE (t) != AGGR_INIT_EXPR)
8761 return t;
8762 /* Calls to immediate functions returning void need to be
8763 evaluated. */
8764 tree fndecl = cp_get_callee_fndecl_nofold (t);
8765 if (fndecl == NULL_TREE || !DECL_IMMEDIATE_FUNCTION_P (fndecl))
8766 return t;
8767 else
8768 is_consteval = true;
8771 else if (cxx_dialect >= cxx20
8772 && (TREE_CODE (t) == CALL_EXPR
8773 || TREE_CODE (t) == AGGR_INIT_EXPR
8774 || TREE_CODE (t) == TARGET_EXPR))
8776 /* For non-concept checks, determine if it is consteval. */
8777 if (!concept_check_p (t))
8779 tree x = t;
8780 if (TREE_CODE (x) == TARGET_EXPR)
8781 x = TARGET_EXPR_INITIAL (x);
8782 tree fndecl = cp_get_callee_fndecl_nofold (x);
8783 if (fndecl && DECL_IMMEDIATE_FUNCTION_P (fndecl))
8784 is_consteval = true;
8787 if (AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type))
8789 /* In C++14 an NSDMI can participate in aggregate initialization,
8790 and can refer to the address of the object being initialized, so
8791 we need to pass in the relevant VAR_DECL if we want to do the
8792 evaluation in a single pass. The evaluation will dynamically
8793 update ctx.values for the VAR_DECL. We use the same strategy
8794 for C++11 constexpr constructors that refer to the object being
8795 initialized. */
8796 if (constexpr_dtor)
8798 gcc_assert (object && VAR_P (object));
8799 gcc_assert (DECL_DECLARED_CONSTEXPR_P (object));
8800 gcc_assert (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (object));
8801 if (error_operand_p (DECL_INITIAL (object)))
8802 return t;
8803 ctx.ctor = unshare_expr (DECL_INITIAL (object));
8804 TREE_READONLY (ctx.ctor) = false;
8805 /* Temporarily force decl_really_constant_value to return false
8806 for it, we want to use ctx.ctor for the current value instead. */
8807 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (object) = false;
8809 else
8811 ctx.ctor = build_constructor (type, NULL);
8812 CONSTRUCTOR_NO_CLEARING (ctx.ctor) = true;
8814 if (!object)
8816 if (TREE_CODE (t) == CALL_EXPR)
8818 /* If T is calling a constructor to initialize an object, reframe
8819 it as an AGGR_INIT_EXPR to avoid trying to modify an object
8820 from outside the constant evaluation, which will fail even if
8821 the value is actually constant (is_constant_evaluated3.C). */
8822 tree fn = cp_get_callee_fndecl_nofold (t);
8823 if (fn && DECL_CONSTRUCTOR_P (fn))
8825 object = CALL_EXPR_ARG (t, 0);
8826 object = build_fold_indirect_ref (object);
8827 r = build_aggr_init_expr (type, r);
8830 else if (TREE_CODE (t) == TARGET_EXPR)
8831 object = TARGET_EXPR_SLOT (t);
8832 else if (TREE_CODE (t) == AGGR_INIT_EXPR)
8833 object = AGGR_INIT_EXPR_SLOT (t);
8835 ctx.object = object;
8836 if (object)
8837 gcc_assert (same_type_ignoring_top_level_qualifiers_p
8838 (type, TREE_TYPE (object)));
8839 if (object && DECL_P (object))
8840 global_ctx.put_value (object, ctx.ctor);
8841 if (TREE_CODE (r) == TARGET_EXPR)
8842 /* Avoid creating another CONSTRUCTOR when we expand the
8843 TARGET_EXPR. */
8844 r = TARGET_EXPR_INITIAL (r);
8847 auto_vec<tree, 16> cleanups;
8848 global_ctx.cleanups = &cleanups;
8850 if (manifestly_const_eval == mce_true)
8851 instantiate_constexpr_fns (r);
8852 r = cxx_eval_constant_expression (&ctx, r, vc_prvalue,
8853 &non_constant_p, &overflow_p);
8855 if (!constexpr_dtor)
8856 verify_constant (r, allow_non_constant, &non_constant_p, &overflow_p);
8857 else
8858 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (object) = true;
8860 unsigned int i;
8861 tree cleanup;
8862 /* Evaluate the cleanups. */
8863 FOR_EACH_VEC_ELT_REVERSE (cleanups, i, cleanup)
8864 cxx_eval_constant_expression (&ctx, cleanup, vc_discard,
8865 &non_constant_p, &overflow_p);
8867 /* Mutable logic is a bit tricky: we want to allow initialization of
8868 constexpr variables with mutable members, but we can't copy those
8869 members to another constexpr variable. */
8870 if (TREE_CODE (r) == CONSTRUCTOR && CONSTRUCTOR_MUTABLE_POISON (r))
8872 if (!allow_non_constant)
8873 error ("%qE is not a constant expression because it refers to "
8874 "mutable subobjects of %qT", t, type);
8875 non_constant_p = true;
8878 if (TREE_CODE (r) == CONSTRUCTOR && CONSTRUCTOR_NO_CLEARING (r))
8880 if (!allow_non_constant)
8881 error ("%qE is not a constant expression because it refers to "
8882 "an incompletely initialized variable", t);
8883 TREE_CONSTANT (r) = false;
8884 non_constant_p = true;
8887 if (!non_constant_p && cxx_dialect >= cxx20
8888 && !global_ctx.heap_vars.is_empty ())
8890 tree heap_var = cp_walk_tree_without_duplicates (&r, find_heap_var_refs,
8891 NULL);
8892 unsigned int i;
8893 if (heap_var)
8895 if (!allow_non_constant && !non_constant_p)
8896 error_at (DECL_SOURCE_LOCATION (heap_var),
8897 "%qE is not a constant expression because it refers to "
8898 "a result of %<operator new%>", t);
8899 r = t;
8900 non_constant_p = true;
8902 FOR_EACH_VEC_ELT (global_ctx.heap_vars, i, heap_var)
8904 if (DECL_NAME (heap_var) != heap_deleted_identifier)
8906 if (!allow_non_constant && !non_constant_p)
8907 error_at (DECL_SOURCE_LOCATION (heap_var),
8908 "%qE is not a constant expression because allocated "
8909 "storage has not been deallocated", t);
8910 r = t;
8911 non_constant_p = true;
8913 varpool_node::get (heap_var)->remove ();
8917 /* Check that immediate invocation does not return an expression referencing
8918 any immediate function decls. */
8919 if (!non_constant_p && cxx_dialect >= cxx20)
8920 if (tree immediate_fndecl
8921 = cp_walk_tree_without_duplicates (&r, find_immediate_fndecl,
8922 NULL))
8924 if (!allow_non_constant && !non_constant_p)
8926 if (is_consteval)
8927 error_at (cp_expr_loc_or_input_loc (t),
8928 "immediate evaluation returns address of immediate "
8929 "function %qD", immediate_fndecl);
8930 else
8931 error_at (cp_expr_loc_or_input_loc (t),
8932 "constant evaluation returns address of immediate "
8933 "function %qD", immediate_fndecl);
8935 r = t;
8936 non_constant_p = true;
8939 if (non_constant_p)
8940 /* If we saw something bad, go back to our argument. The wrapping below is
8941 only for the cases of TREE_CONSTANT argument or overflow. */
8942 r = t;
8944 if (!non_constant_p && overflow_p)
8945 non_constant_p = true;
8947 /* Unshare the result. */
8948 bool should_unshare = true;
8949 if (r == t || (TREE_CODE (t) == TARGET_EXPR
8950 && TARGET_EXPR_INITIAL (t) == r))
8951 should_unshare = false;
8953 if (non_constant_p && !allow_non_constant)
8954 return error_mark_node;
8955 else if (constexpr_dtor)
8956 return r;
8957 else if (non_constant_p && TREE_CONSTANT (r))
8958 r = mark_non_constant (r);
8959 else if (non_constant_p)
8960 return t;
8962 if (should_unshare)
8963 r = unshare_expr (r);
8965 if (TREE_CODE (r) == CONSTRUCTOR && CLASS_TYPE_P (TREE_TYPE (r)))
8967 r = adjust_temp_type (type, r);
8968 if (TREE_CODE (t) == TARGET_EXPR
8969 && TARGET_EXPR_INITIAL (t) == r)
8970 return t;
8971 else if (TREE_CODE (t) == CONSTRUCTOR || TREE_CODE (t) == CALL_EXPR)
8972 /* Don't add a TARGET_EXPR if our argument didn't have one. */;
8973 else if (TREE_CODE (t) == TARGET_EXPR && TARGET_EXPR_CLEANUP (t))
8974 r = get_target_expr (r);
8975 else
8977 r = get_target_expr (r, tf_warning_or_error | tf_no_cleanup);
8978 TREE_CONSTANT (r) = true;
8982 if (TREE_CODE (t) == TARGET_EXPR
8983 && TREE_CODE (r) == TARGET_EXPR)
8985 /* Preserve this flag for potential_constant_expression, and the others
8986 for good measure. */
8987 TARGET_EXPR_ELIDING_P (r) = TARGET_EXPR_ELIDING_P (t);
8988 TARGET_EXPR_IMPLICIT_P (r) = TARGET_EXPR_IMPLICIT_P (t);
8989 TARGET_EXPR_LIST_INIT_P (r) = TARGET_EXPR_LIST_INIT_P (t);
8990 TARGET_EXPR_DIRECT_INIT_P (r) = TARGET_EXPR_DIRECT_INIT_P (t);
8993 /* Remember the original location if that wouldn't need a wrapper. */
8994 if (location_t loc = EXPR_LOCATION (t))
8995 protected_set_expr_location (r, loc);
8997 return r;
9000 /* If T represents a constant expression returns its reduced value.
9001 Otherwise return error_mark_node. */
9003 tree
9004 cxx_constant_value (tree t, tree decl /* = NULL_TREE */,
9005 tsubst_flags_t complain /* = tf_error */)
9007 bool sfinae = !(complain & tf_error);
9008 tree r = cxx_eval_outermost_constant_expr (t, sfinae, true, mce_true, false, decl);
9009 if (sfinae && !TREE_CONSTANT (r))
9010 r = error_mark_node;
9011 return r;
9014 /* Like cxx_constant_value, but used for evaluation of constexpr destructors
9015 of constexpr variables. The actual initializer of DECL is not modified. */
9017 void
9018 cxx_constant_dtor (tree t, tree decl)
9020 cxx_eval_outermost_constant_expr (t, false, true, mce_true, true, decl);
9023 /* Helper routine for fold_simple function. Either return simplified
9024 expression T, otherwise NULL_TREE.
9025 In contrast to cp_fully_fold, and to maybe_constant_value, we try to fold
9026 even if we are within template-declaration. So be careful on call, as in
9027 such case types can be undefined. */
9029 static tree
9030 fold_simple_1 (tree t)
9032 tree op1;
9033 enum tree_code code = TREE_CODE (t);
9035 switch (code)
9037 case INTEGER_CST:
9038 case REAL_CST:
9039 case VECTOR_CST:
9040 case FIXED_CST:
9041 case COMPLEX_CST:
9042 return t;
9044 case SIZEOF_EXPR:
9045 return fold_sizeof_expr (t);
9047 case ABS_EXPR:
9048 case ABSU_EXPR:
9049 case CONJ_EXPR:
9050 case REALPART_EXPR:
9051 case IMAGPART_EXPR:
9052 case NEGATE_EXPR:
9053 case BIT_NOT_EXPR:
9054 case TRUTH_NOT_EXPR:
9055 case VIEW_CONVERT_EXPR:
9056 CASE_CONVERT:
9057 case FLOAT_EXPR:
9058 case FIX_TRUNC_EXPR:
9059 case FIXED_CONVERT_EXPR:
9060 case ADDR_SPACE_CONVERT_EXPR:
9062 op1 = TREE_OPERAND (t, 0);
9064 t = const_unop (code, TREE_TYPE (t), op1);
9065 if (!t)
9066 return NULL_TREE;
9068 if (CONVERT_EXPR_CODE_P (code)
9069 && TREE_OVERFLOW_P (t) && !TREE_OVERFLOW_P (op1))
9070 TREE_OVERFLOW (t) = false;
9071 return t;
9073 default:
9074 return NULL_TREE;
9078 /* If T is a simple constant expression, returns its simplified value.
9079 Otherwise returns T. In contrast to maybe_constant_value we
9080 simplify only few operations on constant-expressions, and we don't
9081 try to simplify constexpressions. */
9083 tree
9084 fold_simple (tree t)
9086 if (processing_template_decl)
9087 return t;
9089 tree r = fold_simple_1 (t);
9090 if (r)
9091 return r;
9093 return t;
9096 /* Try folding the expression T to a simple constant.
9097 Returns that constant, otherwise returns T. */
9099 tree
9100 fold_to_constant (tree t)
9102 tree r = fold (t);
9103 if (CONSTANT_CLASS_P (r) && !TREE_OVERFLOW (r))
9104 return r;
9105 else
9106 return t;
9109 /* If T is a constant expression, returns its reduced value.
9110 Otherwise, if T does not have TREE_CONSTANT set, returns T.
9111 Otherwise, returns a version of T without TREE_CONSTANT.
9112 MANIFESTLY_CONST_EVAL is true if T is manifestly const-evaluated
9113 as per P0595. */
9115 static GTY((deletable)) hash_map<tree, tree> *cv_cache;
9117 tree
9118 maybe_constant_value (tree t, tree decl /* = NULL_TREE */,
9119 mce_value manifestly_const_eval /* = mce_unknown */)
9121 tree r;
9123 if (!is_nondependent_constant_expression (t))
9125 if (TREE_OVERFLOW_P (t)
9126 || (!processing_template_decl && TREE_CONSTANT (t)))
9127 t = mark_non_constant (t);
9128 return t;
9130 else if (CONSTANT_CLASS_P (t))
9131 /* No caching or evaluation needed. */
9132 return t;
9134 /* Don't constant evaluate an unevaluated non-manifestly-constant operand,
9135 but at least try folding it to a simple constant. */
9136 if (cp_unevaluated_operand && manifestly_const_eval != mce_true)
9137 return fold_to_constant (t);
9139 if (manifestly_const_eval != mce_unknown)
9140 return cxx_eval_outermost_constant_expr (t, true, true,
9141 manifestly_const_eval, false, decl);
9143 if (cv_cache == NULL)
9144 cv_cache = hash_map<tree, tree>::create_ggc (101);
9145 if (tree *cached = cv_cache->get (t))
9147 r = *cached;
9148 if (r != t)
9150 /* Clear processing_template_decl for sake of break_out_target_exprs;
9151 entries in the cv_cache are non-templated. */
9152 processing_template_decl_sentinel ptds;
9154 r = break_out_target_exprs (r, /*clear_loc*/true);
9155 protected_set_expr_location (r, EXPR_LOCATION (t));
9157 return r;
9160 uid_sensitive_constexpr_evaluation_checker c;
9161 r = cxx_eval_outermost_constant_expr (t, true, true,
9162 manifestly_const_eval, false, decl);
9163 gcc_checking_assert (r == t
9164 || CONVERT_EXPR_P (t)
9165 || TREE_CODE (t) == VIEW_CONVERT_EXPR
9166 || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
9167 || !cp_tree_equal (r, t));
9168 if (!c.evaluation_restricted_p ())
9169 cv_cache->put (t, r);
9170 return r;
9173 /* Dispose of the whole CV_CACHE. */
9175 static void
9176 clear_cv_cache (void)
9178 if (cv_cache != NULL)
9179 cv_cache->empty ();
9182 /* Dispose of the whole CV_CACHE and FOLD_CACHE. */
9184 void
9185 clear_cv_and_fold_caches ()
9187 clear_cv_cache ();
9188 clear_fold_cache ();
9191 /* Internal function handling expressions in templates for
9192 fold_non_dependent_expr and fold_non_dependent_init.
9194 If we're in a template, but T isn't value dependent, simplify
9195 it. We're supposed to treat:
9197 template <typename T> void f(T[1 + 1]);
9198 template <typename T> void f(T[2]);
9200 as two declarations of the same function, for example. */
9202 static tree
9203 fold_non_dependent_expr_template (tree t, tsubst_flags_t complain,
9204 bool manifestly_const_eval,
9205 tree object)
9207 gcc_assert (processing_template_decl);
9209 if (is_nondependent_constant_expression (t))
9211 processing_template_decl_sentinel s;
9212 t = instantiate_non_dependent_expr_internal (t, complain);
9214 if (type_unknown_p (t) || BRACE_ENCLOSED_INITIALIZER_P (t))
9216 if (TREE_OVERFLOW_P (t))
9218 t = build_nop (TREE_TYPE (t), t);
9219 TREE_CONSTANT (t) = false;
9221 return t;
9223 else if (CONSTANT_CLASS_P (t))
9224 /* No evaluation needed. */
9225 return t;
9227 /* Don't constant evaluate an unevaluated non-manifestly-constant operand,
9228 but at least try folding it to a simple constant. */
9229 if (cp_unevaluated_operand && !manifestly_const_eval)
9230 return fold_to_constant (t);
9232 tree r = cxx_eval_outermost_constant_expr (t, true, true,
9233 mce_value (manifestly_const_eval),
9234 false, object);
9235 /* cp_tree_equal looks through NOPs, so allow them. */
9236 gcc_checking_assert (r == t
9237 || CONVERT_EXPR_P (t)
9238 || TREE_CODE (t) == VIEW_CONVERT_EXPR
9239 || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
9240 || !cp_tree_equal (r, t));
9241 return r;
9243 else if (TREE_OVERFLOW_P (t))
9245 t = build_nop (TREE_TYPE (t), t);
9246 TREE_CONSTANT (t) = false;
9249 return t;
9252 /* Like maybe_constant_value but first fully instantiate the argument.
9254 Note: this is equivalent to instantiate_non_dependent_expr (t, complain)
9255 followed by maybe_constant_value but is more efficient,
9256 because it calls instantiation_dependent_expression_p and
9257 potential_constant_expression at most once.
9258 The manifestly_const_eval argument is passed to maybe_constant_value.
9260 Callers should generally pass their active complain, or if they are in a
9261 non-template, diagnosing context, they can use the default of
9262 tf_warning_or_error. Callers that might be within a template context, don't
9263 have a complain parameter, and aren't going to remember the result for long
9264 (e.g. null_ptr_cst_p), can pass tf_none and deal with error_mark_node
9265 appropriately. */
9267 tree
9268 fold_non_dependent_expr (tree t,
9269 tsubst_flags_t complain /* = tf_warning_or_error */,
9270 bool manifestly_const_eval /* = false */,
9271 tree object /* = NULL_TREE */)
9273 if (t == NULL_TREE)
9274 return NULL_TREE;
9276 if (processing_template_decl)
9277 return fold_non_dependent_expr_template (t, complain,
9278 manifestly_const_eval, object);
9280 return maybe_constant_value (t, object, mce_value (manifestly_const_eval));
9283 /* Like fold_non_dependent_expr, but if EXPR couldn't be folded to a constant,
9284 return the original expression. */
9286 tree
9287 maybe_fold_non_dependent_expr (tree expr,
9288 tsubst_flags_t complain/*=tf_warning_or_error*/)
9290 tree t = fold_non_dependent_expr (expr, complain);
9291 if (t && TREE_CONSTANT (t))
9292 return t;
9294 return expr;
9297 /* Like maybe_constant_init but first fully instantiate the argument. */
9299 tree
9300 fold_non_dependent_init (tree t,
9301 tsubst_flags_t complain /*=tf_warning_or_error*/,
9302 bool manifestly_const_eval /*=false*/,
9303 tree object /* = NULL_TREE */)
9305 if (t == NULL_TREE)
9306 return NULL_TREE;
9308 if (processing_template_decl)
9310 t = fold_non_dependent_expr_template (t, complain,
9311 manifestly_const_eval, object);
9312 /* maybe_constant_init does this stripping, so do it here too. */
9313 if (TREE_CODE (t) == TARGET_EXPR)
9315 tree init = TARGET_EXPR_INITIAL (t);
9316 if (TREE_CODE (init) == CONSTRUCTOR)
9317 t = init;
9319 return t;
9322 return maybe_constant_init (t, object, manifestly_const_eval);
9325 /* Like maybe_constant_value, but returns a CONSTRUCTOR directly, rather
9326 than wrapped in a TARGET_EXPR.
9327 ALLOW_NON_CONSTANT is false if T is required to be a constant expression.
9328 MANIFESTLY_CONST_EVAL is true if T is manifestly const-evaluated as
9329 per P0595 even when ALLOW_NON_CONSTANT is true. */
9331 static tree
9332 maybe_constant_init_1 (tree t, tree decl, bool allow_non_constant,
9333 bool manifestly_const_eval)
9335 if (!t)
9336 return t;
9337 if (TREE_CODE (t) == EXPR_STMT)
9338 t = TREE_OPERAND (t, 0);
9339 if (TREE_CODE (t) == CONVERT_EXPR
9340 && VOID_TYPE_P (TREE_TYPE (t)))
9341 t = TREE_OPERAND (t, 0);
9342 if (TREE_CODE (t) == INIT_EXPR)
9343 t = TREE_OPERAND (t, 1);
9344 if (TREE_CODE (t) == TARGET_EXPR)
9345 t = TARGET_EXPR_INITIAL (t);
9346 if (!is_nondependent_static_init_expression (t))
9347 /* Don't try to evaluate it. */;
9348 else if (CONSTANT_CLASS_P (t) && TREE_CODE (t) != PTRMEM_CST)
9349 /* No evaluation needed. PTRMEM_CST needs the immediate fn check. */;
9350 else
9352 /* [basic.start.static] allows constant-initialization of variables with
9353 static or thread storage duration even if it isn't required, but we
9354 shouldn't bend the rules the same way for automatic variables. */
9355 bool is_static = (decl && DECL_P (decl)
9356 && (TREE_STATIC (decl) || DECL_EXTERNAL (decl)));
9357 if (is_static)
9358 manifestly_const_eval = true;
9360 if (cp_unevaluated_operand && !manifestly_const_eval)
9361 return fold_to_constant (t);
9363 t = cxx_eval_outermost_constant_expr (t, allow_non_constant, !is_static,
9364 mce_value (manifestly_const_eval),
9365 false, decl);
9367 if (TREE_CODE (t) == TARGET_EXPR)
9369 tree init = TARGET_EXPR_INITIAL (t);
9370 if (TREE_CODE (init) == CONSTRUCTOR)
9371 t = init;
9373 return t;
9376 /* Wrapper for maybe_constant_init_1 which permits non constants. */
9378 tree
9379 maybe_constant_init (tree t, tree decl, bool manifestly_const_eval)
9381 return maybe_constant_init_1 (t, decl, true, manifestly_const_eval);
9384 /* Wrapper for maybe_constant_init_1 which does not permit non constants. */
9386 tree
9387 cxx_constant_init (tree t, tree decl)
9389 return maybe_constant_init_1 (t, decl, false, true);
9392 #if 0
9393 /* FIXME see ADDR_EXPR section in potential_constant_expression_1. */
9394 /* Return true if the object referred to by REF has automatic or thread
9395 local storage. */
9397 enum { ck_ok, ck_bad, ck_unknown };
9398 static int
9399 check_automatic_or_tls (tree ref)
9401 machine_mode mode;
9402 poly_int64 bitsize, bitpos;
9403 tree offset;
9404 int volatilep = 0, unsignedp = 0;
9405 tree decl = get_inner_reference (ref, &bitsize, &bitpos, &offset,
9406 &mode, &unsignedp, &volatilep, false);
9407 duration_kind dk;
9409 /* If there isn't a decl in the middle, we don't know the linkage here,
9410 and this isn't a constant expression anyway. */
9411 if (!DECL_P (decl))
9412 return ck_unknown;
9413 dk = decl_storage_duration (decl);
9414 return (dk == dk_auto || dk == dk_thread) ? ck_bad : ck_ok;
9416 #endif
9418 /* Data structure for passing data from potential_constant_expression_1
9419 to check_for_return_continue via cp_walk_tree. */
9420 struct check_for_return_continue_data {
9421 hash_set<tree> *pset;
9422 tree continue_stmt;
9423 tree break_stmt;
9426 /* Helper function for potential_constant_expression_1 SWITCH_STMT handling,
9427 called through cp_walk_tree. Return the first RETURN_EXPR found, or note
9428 the first CONTINUE_STMT and/or BREAK_STMT if RETURN_EXPR is not found. */
9429 static tree
9430 check_for_return_continue (tree *tp, int *walk_subtrees, void *data)
9432 tree t = *tp, s, b;
9433 check_for_return_continue_data *d = (check_for_return_continue_data *) data;
9434 switch (TREE_CODE (t))
9436 case RETURN_EXPR:
9437 return t;
9439 case CONTINUE_STMT:
9440 if (d->continue_stmt == NULL_TREE)
9441 d->continue_stmt = t;
9442 break;
9444 case BREAK_STMT:
9445 if (d->break_stmt == NULL_TREE)
9446 d->break_stmt = t;
9447 break;
9449 #define RECUR(x) \
9450 if (tree r = cp_walk_tree (&x, check_for_return_continue, data, \
9451 d->pset)) \
9452 return r
9454 /* For loops, walk subtrees manually, so that continue stmts found
9455 inside of the bodies of the loops are ignored. */
9456 case DO_STMT:
9457 *walk_subtrees = 0;
9458 RECUR (DO_COND (t));
9459 s = d->continue_stmt;
9460 b = d->break_stmt;
9461 RECUR (DO_BODY (t));
9462 d->continue_stmt = s;
9463 d->break_stmt = b;
9464 break;
9466 case WHILE_STMT:
9467 *walk_subtrees = 0;
9468 RECUR (WHILE_COND (t));
9469 s = d->continue_stmt;
9470 b = d->break_stmt;
9471 RECUR (WHILE_BODY (t));
9472 d->continue_stmt = s;
9473 d->break_stmt = b;
9474 break;
9476 case FOR_STMT:
9477 *walk_subtrees = 0;
9478 RECUR (FOR_INIT_STMT (t));
9479 RECUR (FOR_COND (t));
9480 RECUR (FOR_EXPR (t));
9481 s = d->continue_stmt;
9482 b = d->break_stmt;
9483 RECUR (FOR_BODY (t));
9484 d->continue_stmt = s;
9485 d->break_stmt = b;
9486 break;
9488 case RANGE_FOR_STMT:
9489 *walk_subtrees = 0;
9490 RECUR (RANGE_FOR_EXPR (t));
9491 s = d->continue_stmt;
9492 b = d->break_stmt;
9493 RECUR (RANGE_FOR_BODY (t));
9494 d->continue_stmt = s;
9495 d->break_stmt = b;
9496 break;
9498 case SWITCH_STMT:
9499 *walk_subtrees = 0;
9500 RECUR (SWITCH_STMT_COND (t));
9501 b = d->break_stmt;
9502 RECUR (SWITCH_STMT_BODY (t));
9503 d->break_stmt = b;
9504 break;
9505 #undef RECUR
9507 case STATEMENT_LIST:
9508 case CONSTRUCTOR:
9509 break;
9511 default:
9512 if (!EXPR_P (t))
9513 *walk_subtrees = 0;
9514 break;
9517 return NULL_TREE;
9520 /* Return true if T denotes a potentially constant expression. Issue
9521 diagnostic as appropriate under control of FLAGS. If WANT_RVAL is true,
9522 an lvalue-rvalue conversion is implied. If NOW is true, we want to
9523 consider the expression in the current context, independent of constexpr
9524 substitution. If FUNDEF_P is true, we're checking a constexpr function body
9525 and hard errors should not be reported by constexpr_error.
9527 C++0x [expr.const] used to say
9529 6 An expression is a potential constant expression if it is
9530 a constant expression where all occurrences of function
9531 parameters are replaced by arbitrary constant expressions
9532 of the appropriate type.
9534 2 A conditional expression is a constant expression unless it
9535 involves one of the following as a potentially evaluated
9536 subexpression (3.2), but subexpressions of logical AND (5.14),
9537 logical OR (5.15), and conditional (5.16) operations that are
9538 not evaluated are not considered. */
9540 static bool
9541 potential_constant_expression_1 (tree t, bool want_rval, bool strict, bool now,
9542 bool fundef_p, tsubst_flags_t flags,
9543 tree *jump_target)
9545 #define RECUR(T,RV) \
9546 potential_constant_expression_1 ((T), (RV), strict, now, fundef_p, flags, \
9547 jump_target)
9549 enum { any = false, rval = true };
9550 int i;
9551 tree tmp;
9553 if (t == error_mark_node)
9554 return false;
9555 if (t == NULL_TREE)
9556 return true;
9557 location_t loc = cp_expr_loc_or_input_loc (t);
9559 if (*jump_target)
9560 /* If we are jumping, ignore everything. This is simpler than the
9561 cxx_eval_constant_expression handling because we only need to be
9562 conservatively correct, and we don't necessarily have a constant value
9563 available, so we don't bother with switch tracking. */
9564 return true;
9566 if (TREE_THIS_VOLATILE (t) && want_rval
9567 && !FUNC_OR_METHOD_TYPE_P (TREE_TYPE (t)))
9569 if (flags & tf_error)
9570 constexpr_error (loc, fundef_p, "lvalue-to-rvalue conversion of "
9571 "a volatile lvalue %qE with type %qT", t,
9572 TREE_TYPE (t));
9573 return false;
9575 if (CONSTANT_CLASS_P (t))
9576 return true;
9577 if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_TYPED)
9578 && TREE_TYPE (t) == error_mark_node)
9579 return false;
9581 switch (TREE_CODE (t))
9583 case FUNCTION_DECL:
9584 case BASELINK:
9585 case TEMPLATE_DECL:
9586 case OVERLOAD:
9587 case TEMPLATE_ID_EXPR:
9588 case LABEL_DECL:
9589 case CASE_LABEL_EXPR:
9590 case PREDICT_EXPR:
9591 case CONST_DECL:
9592 case SIZEOF_EXPR:
9593 case ALIGNOF_EXPR:
9594 case OFFSETOF_EXPR:
9595 case NOEXCEPT_EXPR:
9596 case TEMPLATE_PARM_INDEX:
9597 case TRAIT_EXPR:
9598 case IDENTIFIER_NODE:
9599 case USERDEF_LITERAL:
9600 /* We can see a FIELD_DECL in a pointer-to-member expression. */
9601 case FIELD_DECL:
9602 case RESULT_DECL:
9603 case USING_DECL:
9604 case USING_STMT:
9605 case PLACEHOLDER_EXPR:
9606 case REQUIRES_EXPR:
9607 case STATIC_ASSERT:
9608 case DEBUG_BEGIN_STMT:
9609 return true;
9611 case RETURN_EXPR:
9612 if (!RECUR (TREE_OPERAND (t, 0), any))
9613 return false;
9614 /* FALLTHROUGH */
9616 case BREAK_STMT:
9617 case CONTINUE_STMT:
9618 *jump_target = t;
9619 return true;
9621 case PARM_DECL:
9622 if (now && want_rval)
9624 tree type = TREE_TYPE (t);
9625 if (dependent_type_p (type)
9626 || !COMPLETE_TYPE_P (processing_template_decl
9627 ? type : complete_type (type))
9628 || is_really_empty_class (type, /*ignore_vptr*/false))
9629 /* An empty class has no data to read. */
9630 return true;
9631 if (flags & tf_error)
9632 constexpr_error (input_location, fundef_p,
9633 "%qE is not a constant expression", t);
9634 return false;
9636 return true;
9638 case AGGR_INIT_EXPR:
9639 case CALL_EXPR:
9640 /* -- an invocation of a function other than a constexpr function
9641 or a constexpr constructor. */
9643 tree fun = get_function_named_in_call (t);
9644 const int nargs = call_expr_nargs (t);
9645 i = 0;
9647 if (fun == NULL_TREE)
9649 /* Reset to allow the function to continue past the end
9650 of the block below. Otherwise return early. */
9651 bool bail = true;
9653 if (TREE_CODE (t) == CALL_EXPR
9654 && CALL_EXPR_FN (t) == NULL_TREE)
9655 switch (CALL_EXPR_IFN (t))
9657 /* These should be ignored, they are optimized away from
9658 constexpr functions. */
9659 case IFN_UBSAN_NULL:
9660 case IFN_UBSAN_BOUNDS:
9661 case IFN_UBSAN_VPTR:
9662 case IFN_FALLTHROUGH:
9663 case IFN_ASSUME:
9664 return true;
9666 case IFN_ADD_OVERFLOW:
9667 case IFN_SUB_OVERFLOW:
9668 case IFN_MUL_OVERFLOW:
9669 case IFN_LAUNDER:
9670 case IFN_VEC_CONVERT:
9671 bail = false;
9672 break;
9674 default:
9675 break;
9678 if (bail)
9680 /* fold_call_expr can't do anything with IFN calls. */
9681 if (flags & tf_error)
9682 constexpr_error (loc, fundef_p,
9683 "call to internal function %qE", t);
9684 return false;
9688 if (fun && is_overloaded_fn (fun))
9690 if (!RECUR (fun, true))
9691 return false;
9692 fun = get_fns (fun);
9694 if (TREE_CODE (fun) == FUNCTION_DECL)
9696 if (builtin_valid_in_constant_expr_p (fun))
9697 return true;
9698 if (!maybe_constexpr_fn (fun)
9699 /* Allow any built-in function; if the expansion
9700 isn't constant, we'll deal with that then. */
9701 && !fndecl_built_in_p (fun)
9702 /* In C++20, replaceable global allocation functions
9703 are constant expressions. */
9704 && (!cxx_replaceable_global_alloc_fn (fun)
9705 || TREE_CODE (t) != CALL_EXPR
9706 || (!CALL_FROM_NEW_OR_DELETE_P (t)
9707 && (current_function_decl == NULL_TREE
9708 || !is_std_allocator_allocate
9709 (current_function_decl))))
9710 /* Allow placement new in std::construct_at. */
9711 && (!cxx_placement_new_fn (fun)
9712 || TREE_CODE (t) != CALL_EXPR
9713 || current_function_decl == NULL_TREE
9714 || !is_std_construct_at (current_function_decl))
9715 && !cxx_dynamic_cast_fn_p (fun))
9717 if ((flags & tf_error)
9718 && constexpr_error (loc, fundef_p,
9719 "call to non-%<constexpr%> "
9720 "function %qD", fun))
9721 explain_invalid_constexpr_fn (fun);
9722 return false;
9726 fun = OVL_FIRST (fun);
9727 /* Skip initial arguments to base constructors. */
9728 if (DECL_BASE_CONSTRUCTOR_P (fun))
9729 i = num_artificial_parms_for (fun);
9731 else if (fun)
9733 if (TREE_TYPE (fun)
9734 && FUNCTION_POINTER_TYPE_P (TREE_TYPE (fun)))
9735 want_rval = rval;
9736 else
9737 want_rval = any;
9738 if (RECUR (fun, want_rval))
9739 /* Might end up being a constant function pointer. But it
9740 could also be a function object with constexpr op(), so
9741 we pass 'any' so that the underlying VAR_DECL is deemed
9742 as potentially-constant even though it wasn't declared
9743 constexpr. */;
9744 else
9745 return false;
9747 for (; i < nargs; ++i)
9749 tree x = get_nth_callarg (t, i);
9750 /* In a template, reference arguments haven't been converted to
9751 REFERENCE_TYPE and we might not even know if the parameter
9752 is a reference, so accept lvalue constants too. */
9753 bool rv = processing_template_decl ? any : rval;
9754 /* Don't require an immediately constant value, as constexpr
9755 substitution might not use the value of the argument. */
9756 bool sub_now = false;
9757 if (!potential_constant_expression_1 (x, rv, strict,
9758 sub_now, fundef_p, flags,
9759 jump_target))
9760 return false;
9762 return true;
9765 case NON_LVALUE_EXPR:
9766 /* -- an lvalue-to-rvalue conversion (4.1) unless it is applied to
9767 -- an lvalue of integral type that refers to a non-volatile
9768 const variable or static data member initialized with
9769 constant expressions, or
9771 -- an lvalue of literal type that refers to non-volatile
9772 object defined with constexpr, or that refers to a
9773 sub-object of such an object; */
9774 return RECUR (TREE_OPERAND (t, 0), rval);
9776 case EXCESS_PRECISION_EXPR:
9777 return RECUR (TREE_OPERAND (t, 0), rval);
9779 case VAR_DECL:
9780 if (DECL_HAS_VALUE_EXPR_P (t))
9782 if (now && is_normal_capture_proxy (t))
9784 /* -- in a lambda-expression, a reference to this or to a
9785 variable with automatic storage duration defined outside that
9786 lambda-expression, where the reference would be an
9787 odr-use. */
9789 if (want_rval)
9790 /* Since we're doing an lvalue-rvalue conversion, this might
9791 not be an odr-use, so evaluate the variable directly. */
9792 return RECUR (DECL_CAPTURED_VARIABLE (t), rval);
9794 if (flags & tf_error)
9796 tree cap = DECL_CAPTURED_VARIABLE (t);
9797 auto_diagnostic_group d;
9798 if (constexpr_error (input_location, fundef_p,
9799 "lambda capture of %qE is not a "
9800 "constant expression", cap)
9801 && decl_constant_var_p (cap))
9802 inform (input_location, "because it is used as a glvalue");
9804 return false;
9806 /* Treat __PRETTY_FUNCTION__ inside a template function as
9807 potentially-constant. */
9808 else if (DECL_PRETTY_FUNCTION_P (t)
9809 && DECL_VALUE_EXPR (t) == error_mark_node)
9810 return true;
9811 return RECUR (DECL_VALUE_EXPR (t), rval);
9813 if (want_rval
9814 && (now || !var_in_maybe_constexpr_fn (t))
9815 && !type_dependent_expression_p (t)
9816 && !decl_maybe_constant_var_p (t)
9817 && (strict
9818 || !CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (t))
9819 || (DECL_INITIAL (t)
9820 && !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t)))
9821 && COMPLETE_TYPE_P (TREE_TYPE (t))
9822 && !is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
9824 if (flags & tf_error)
9825 non_const_var_error (loc, t, fundef_p);
9826 return false;
9828 return true;
9830 case NOP_EXPR:
9831 if (REINTERPRET_CAST_P (t))
9833 if (flags & tf_error)
9834 constexpr_error (loc, fundef_p, "%<reinterpret_cast%> is not a "
9835 "constant expression");
9836 return false;
9838 /* FALLTHRU */
9839 case CONVERT_EXPR:
9840 case VIEW_CONVERT_EXPR:
9841 /* -- a reinterpret_cast. FIXME not implemented, and this rule
9842 may change to something more specific to type-punning (DR 1312). */
9844 tree from = TREE_OPERAND (t, 0);
9845 if (location_wrapper_p (t))
9847 iloc_sentinel ils = loc;
9848 return (RECUR (from, want_rval));
9850 if (INDIRECT_TYPE_P (TREE_TYPE (t)))
9852 STRIP_ANY_LOCATION_WRAPPER (from);
9853 if (TREE_CODE (from) == INTEGER_CST
9854 && !integer_zerop (from))
9856 if (flags & tf_error)
9857 constexpr_error (loc, fundef_p,
9858 "%<reinterpret_cast%> from integer to "
9859 "pointer");
9860 return false;
9863 return (RECUR (from, TREE_CODE (t) != VIEW_CONVERT_EXPR));
9866 case ADDRESSOF_EXPR:
9867 /* This is like ADDR_EXPR, except it won't form pointer-to-member. */
9868 t = TREE_OPERAND (t, 0);
9869 goto handle_addr_expr;
9871 case ADDR_EXPR:
9872 /* -- a unary operator & that is applied to an lvalue that
9873 designates an object with thread or automatic storage
9874 duration; */
9875 t = TREE_OPERAND (t, 0);
9877 if (TREE_CODE (t) == OFFSET_REF && PTRMEM_OK_P (t))
9878 /* A pointer-to-member constant. */
9879 return true;
9881 handle_addr_expr:
9882 #if 0
9883 /* FIXME adjust when issue 1197 is fully resolved. For now don't do
9884 any checking here, as we might dereference the pointer later. If
9885 we remove this code, also remove check_automatic_or_tls. */
9886 i = check_automatic_or_tls (t);
9887 if (i == ck_ok)
9888 return true;
9889 if (i == ck_bad)
9891 if (flags & tf_error)
9892 error ("address-of an object %qE with thread local or "
9893 "automatic storage is not a constant expression", t);
9894 return false;
9896 #endif
9897 return RECUR (t, any);
9899 case COMPONENT_REF:
9900 case ARROW_EXPR:
9901 case OFFSET_REF:
9902 /* -- a class member access unless its postfix-expression is
9903 of literal type or of pointer to literal type. */
9904 /* This test would be redundant, as it follows from the
9905 postfix-expression being a potential constant expression. */
9906 if (type_unknown_p (t))
9907 return true;
9908 if (is_overloaded_fn (t))
9909 /* In a template, a COMPONENT_REF of a function expresses ob.fn(),
9910 which uses ob as an lvalue. */
9911 want_rval = false;
9912 gcc_fallthrough ();
9914 case REALPART_EXPR:
9915 case IMAGPART_EXPR:
9916 case BIT_FIELD_REF:
9917 return RECUR (TREE_OPERAND (t, 0), want_rval);
9919 case EXPR_PACK_EXPANSION:
9920 return RECUR (PACK_EXPANSION_PATTERN (t), want_rval);
9922 case INDIRECT_REF:
9924 tree x = TREE_OPERAND (t, 0);
9925 STRIP_NOPS (x);
9926 if (is_this_parameter (x) && !is_capture_proxy (x))
9928 if (now || !var_in_maybe_constexpr_fn (x))
9930 if (flags & tf_error)
9931 constexpr_error (loc, fundef_p, "use of %<this%> in a "
9932 "constant expression");
9933 return false;
9935 return true;
9937 return RECUR (x, rval);
9940 case STATEMENT_LIST:
9941 for (tree stmt : tsi_range (t))
9942 if (!RECUR (stmt, any))
9943 return false;
9944 return true;
9946 case MODIFY_EXPR:
9947 if (cxx_dialect < cxx14)
9948 goto fail;
9949 if (!RECUR (TREE_OPERAND (t, 0), any))
9950 return false;
9951 /* Just ignore clobbers. */
9952 if (TREE_CLOBBER_P (TREE_OPERAND (t, 1)))
9953 return true;
9954 if (!RECUR (TREE_OPERAND (t, 1), rval))
9955 return false;
9956 return true;
9958 case MODOP_EXPR:
9959 if (cxx_dialect < cxx14)
9960 goto fail;
9961 if (!RECUR (TREE_OPERAND (t, 0), rval))
9962 return false;
9963 if (!RECUR (TREE_OPERAND (t, 2), rval))
9964 return false;
9965 return true;
9967 case DO_STMT:
9968 if (!RECUR (DO_COND (t), rval))
9969 return false;
9970 if (!RECUR (DO_BODY (t), any))
9971 return false;
9972 if (breaks (jump_target) || continues (jump_target))
9973 *jump_target = NULL_TREE;
9974 return true;
9976 case FOR_STMT:
9977 if (!RECUR (FOR_INIT_STMT (t), any))
9978 return false;
9979 tmp = FOR_COND (t);
9980 if (!RECUR (tmp, rval))
9981 return false;
9982 if (tmp)
9984 if (!processing_template_decl)
9985 tmp = cxx_eval_outermost_constant_expr (tmp, true);
9986 /* If we couldn't evaluate the condition, it might not ever be
9987 true. */
9988 if (!integer_onep (tmp))
9990 /* Before returning true, check if the for body can contain
9991 a return. */
9992 hash_set<tree> pset;
9993 check_for_return_continue_data data = { &pset, NULL_TREE,
9994 NULL_TREE };
9995 if (tree ret_expr
9996 = cp_walk_tree (&FOR_BODY (t), check_for_return_continue,
9997 &data, &pset))
9998 *jump_target = ret_expr;
9999 return true;
10002 if (!RECUR (FOR_EXPR (t), any))
10003 return false;
10004 if (!RECUR (FOR_BODY (t), any))
10005 return false;
10006 if (breaks (jump_target) || continues (jump_target))
10007 *jump_target = NULL_TREE;
10008 return true;
10010 case RANGE_FOR_STMT:
10011 if (!RECUR (RANGE_FOR_INIT_STMT (t), any))
10012 return false;
10013 if (!RECUR (RANGE_FOR_EXPR (t), any))
10014 return false;
10015 if (!RECUR (RANGE_FOR_BODY (t), any))
10016 return false;
10017 if (breaks (jump_target) || continues (jump_target))
10018 *jump_target = NULL_TREE;
10019 return true;
10021 case WHILE_STMT:
10022 tmp = WHILE_COND (t);
10023 if (!RECUR (tmp, rval))
10024 return false;
10025 if (!processing_template_decl)
10026 tmp = cxx_eval_outermost_constant_expr (tmp, true);
10027 /* If we couldn't evaluate the condition, it might not ever be true. */
10028 if (!integer_onep (tmp))
10030 /* Before returning true, check if the while body can contain
10031 a return. */
10032 hash_set<tree> pset;
10033 check_for_return_continue_data data = { &pset, NULL_TREE,
10034 NULL_TREE };
10035 if (tree ret_expr
10036 = cp_walk_tree (&WHILE_BODY (t), check_for_return_continue,
10037 &data, &pset))
10038 *jump_target = ret_expr;
10039 return true;
10041 if (!RECUR (WHILE_BODY (t), any))
10042 return false;
10043 if (breaks (jump_target) || continues (jump_target))
10044 *jump_target = NULL_TREE;
10045 return true;
10047 case SWITCH_STMT:
10048 if (!RECUR (SWITCH_STMT_COND (t), rval))
10049 return false;
10050 /* FIXME we don't check SWITCH_STMT_BODY currently, because even
10051 unreachable labels would be checked and it is enough if there is
10052 a single switch cond value for which it is a valid constant
10053 expression. We need to check if there are any RETURN_EXPRs
10054 or CONTINUE_STMTs inside of the body though, as in that case
10055 we need to set *jump_target. */
10056 else
10058 hash_set<tree> pset;
10059 check_for_return_continue_data data = { &pset, NULL_TREE,
10060 NULL_TREE };
10061 if (tree ret_expr
10062 = cp_walk_tree (&SWITCH_STMT_BODY (t), check_for_return_continue,
10063 &data, &pset))
10064 /* The switch might return. */
10065 *jump_target = ret_expr;
10066 else if (data.continue_stmt)
10067 /* The switch can't return, but might continue. */
10068 *jump_target = data.continue_stmt;
10070 return true;
10072 case STMT_EXPR:
10073 return RECUR (STMT_EXPR_STMT (t), rval);
10075 case LAMBDA_EXPR:
10076 if (cxx_dialect >= cxx17)
10077 /* In C++17 lambdas can be constexpr, don't give up yet. */
10078 return true;
10079 else if (flags & tf_error)
10080 constexpr_error (loc, fundef_p, "lambda-expression is not a "
10081 "constant expression before C++17");
10082 return false;
10084 case NEW_EXPR:
10085 case VEC_NEW_EXPR:
10086 case DELETE_EXPR:
10087 case VEC_DELETE_EXPR:
10088 if (cxx_dialect >= cxx20)
10089 /* In C++20, new-expressions are potentially constant. */
10090 return true;
10091 else if (flags & tf_error)
10092 constexpr_error (loc, fundef_p, "new-expression is not a "
10093 "constant expression before C++20");
10094 return false;
10096 case DYNAMIC_CAST_EXPR:
10097 case PSEUDO_DTOR_EXPR:
10098 case THROW_EXPR:
10099 case OMP_PARALLEL:
10100 case OMP_TASK:
10101 case OMP_FOR:
10102 case OMP_SIMD:
10103 case OMP_DISTRIBUTE:
10104 case OMP_TASKLOOP:
10105 case OMP_LOOP:
10106 case OMP_TEAMS:
10107 case OMP_TARGET_DATA:
10108 case OMP_TARGET:
10109 case OMP_SECTIONS:
10110 case OMP_ORDERED:
10111 case OMP_CRITICAL:
10112 case OMP_SINGLE:
10113 case OMP_SCAN:
10114 case OMP_SCOPE:
10115 case OMP_SECTION:
10116 case OMP_MASTER:
10117 case OMP_MASKED:
10118 case OMP_TASKGROUP:
10119 case OMP_TARGET_UPDATE:
10120 case OMP_TARGET_ENTER_DATA:
10121 case OMP_TARGET_EXIT_DATA:
10122 case OMP_ATOMIC:
10123 case OMP_ATOMIC_READ:
10124 case OMP_ATOMIC_CAPTURE_OLD:
10125 case OMP_ATOMIC_CAPTURE_NEW:
10126 case OMP_DEPOBJ:
10127 case OACC_PARALLEL:
10128 case OACC_KERNELS:
10129 case OACC_SERIAL:
10130 case OACC_DATA:
10131 case OACC_HOST_DATA:
10132 case OACC_LOOP:
10133 case OACC_CACHE:
10134 case OACC_DECLARE:
10135 case OACC_ENTER_DATA:
10136 case OACC_EXIT_DATA:
10137 case OACC_UPDATE:
10138 case OMP_ARRAY_SECTION:
10139 /* GCC internal stuff. */
10140 case VA_ARG_EXPR:
10141 case TRANSACTION_EXPR:
10142 case AT_ENCODE_EXPR:
10143 fail:
10144 if (flags & tf_error)
10145 constexpr_error (loc, fundef_p, "expression %qE is not a constant "
10146 "expression", t);
10147 return false;
10149 case ASM_EXPR:
10150 if (flags & tf_error)
10151 inline_asm_in_constexpr_error (loc, fundef_p);
10152 return false;
10154 case OBJ_TYPE_REF:
10155 if (cxx_dialect >= cxx20)
10156 /* In C++20 virtual calls can be constexpr, don't give up yet. */
10157 return true;
10158 else if (flags & tf_error)
10159 constexpr_error (loc, fundef_p, "virtual functions cannot be "
10160 "%<constexpr%> before C++20");
10161 return false;
10163 case TYPEID_EXPR:
10164 /* In C++20, a typeid expression whose operand is of polymorphic
10165 class type can be constexpr. */
10167 tree e = TREE_OPERAND (t, 0);
10168 if (cxx_dialect < cxx20
10169 && strict
10170 && !TYPE_P (e)
10171 && !type_dependent_expression_p (e)
10172 && TYPE_POLYMORPHIC_P (TREE_TYPE (e)))
10174 if (flags & tf_error)
10175 constexpr_error (loc, fundef_p, "%<typeid%> is not a "
10176 "constant expression because %qE is "
10177 "of polymorphic type", e);
10178 return false;
10180 return true;
10183 case POINTER_DIFF_EXPR:
10184 case MINUS_EXPR:
10185 want_rval = true;
10186 goto binary;
10188 case LT_EXPR:
10189 case LE_EXPR:
10190 case GT_EXPR:
10191 case GE_EXPR:
10192 case EQ_EXPR:
10193 case NE_EXPR:
10194 case SPACESHIP_EXPR:
10195 want_rval = true;
10196 goto binary;
10198 case PREINCREMENT_EXPR:
10199 case POSTINCREMENT_EXPR:
10200 case PREDECREMENT_EXPR:
10201 case POSTDECREMENT_EXPR:
10202 if (cxx_dialect < cxx14)
10203 goto fail;
10204 goto unary;
10206 case BIT_NOT_EXPR:
10207 /* A destructor. */
10208 if (TYPE_P (TREE_OPERAND (t, 0)))
10209 return true;
10210 /* fall through. */
10212 case CONJ_EXPR:
10213 case SAVE_EXPR:
10214 case FIX_TRUNC_EXPR:
10215 case FLOAT_EXPR:
10216 case NEGATE_EXPR:
10217 case ABS_EXPR:
10218 case ABSU_EXPR:
10219 case TRUTH_NOT_EXPR:
10220 case FIXED_CONVERT_EXPR:
10221 case UNARY_PLUS_EXPR:
10222 case UNARY_LEFT_FOLD_EXPR:
10223 case UNARY_RIGHT_FOLD_EXPR:
10224 unary:
10225 return RECUR (TREE_OPERAND (t, 0), rval);
10227 case CAST_EXPR:
10228 case CONST_CAST_EXPR:
10229 case STATIC_CAST_EXPR:
10230 case REINTERPRET_CAST_EXPR:
10231 case IMPLICIT_CONV_EXPR:
10232 if (!cast_valid_in_integral_constant_expression_p (TREE_TYPE (t)))
10233 /* In C++98, a conversion to non-integral type can't be part of a
10234 constant expression. */
10236 if (flags & tf_error)
10237 constexpr_error (loc, fundef_p,
10238 "cast to non-integral type %qT in a constant "
10239 "expression", TREE_TYPE (t));
10240 return false;
10242 /* This might be a conversion from a class to a (potentially) literal
10243 type. Let's consider it potentially constant since the conversion
10244 might be a constexpr user-defined conversion. */
10245 else if (cxx_dialect >= cxx11
10246 && (dependent_type_p (TREE_TYPE (t))
10247 || !COMPLETE_TYPE_P (TREE_TYPE (t))
10248 || literal_type_p (TREE_TYPE (t)))
10249 && TREE_OPERAND (t, 0))
10251 tree type = TREE_TYPE (TREE_OPERAND (t, 0));
10252 /* If this is a dependent type, it could end up being a class
10253 with conversions. */
10254 if (type == NULL_TREE || WILDCARD_TYPE_P (type))
10255 return true;
10256 /* Or a non-dependent class which has conversions. */
10257 else if (CLASS_TYPE_P (type)
10258 && (TYPE_HAS_CONVERSION (type) || dependent_scope_p (type)))
10259 return true;
10262 return (RECUR (TREE_OPERAND (t, 0),
10263 !TYPE_REF_P (TREE_TYPE (t))));
10265 case BIND_EXPR:
10266 return RECUR (BIND_EXPR_BODY (t), want_rval);
10268 case CLEANUP_POINT_EXPR:
10269 case MUST_NOT_THROW_EXPR:
10270 case TRY_CATCH_EXPR:
10271 case TRY_BLOCK:
10272 case EH_SPEC_BLOCK:
10273 case EXPR_STMT:
10274 case PAREN_EXPR:
10275 /* For convenience. */
10276 case LOOP_EXPR:
10277 case EXIT_EXPR:
10278 return RECUR (TREE_OPERAND (t, 0), want_rval);
10280 case DECL_EXPR:
10281 tmp = DECL_EXPR_DECL (t);
10282 if (VAR_P (tmp) && !DECL_ARTIFICIAL (tmp)
10283 && (processing_template_decl
10284 ? !decl_maybe_constant_var_p (tmp)
10285 : !decl_constant_var_p (tmp)))
10287 if (CP_DECL_THREAD_LOCAL_P (tmp) && !DECL_REALLY_EXTERN (tmp))
10289 if (flags & tf_error)
10290 constexpr_error (DECL_SOURCE_LOCATION (tmp), fundef_p,
10291 "%qD defined %<thread_local%> in "
10292 "%<constexpr%> context", tmp);
10293 return false;
10295 else if (TREE_STATIC (tmp))
10297 if (flags & tf_error)
10298 constexpr_error (DECL_SOURCE_LOCATION (tmp), fundef_p,
10299 "%qD defined %<static%> in %<constexpr%> "
10300 "context", tmp);
10301 return false;
10303 else if (!check_for_uninitialized_const_var
10304 (tmp, /*constexpr_context_p=*/true, flags))
10305 return false;
10307 if (VAR_P (tmp))
10308 return RECUR (DECL_INITIAL (tmp), want_rval);
10309 return true;
10311 case TRY_FINALLY_EXPR:
10312 return (RECUR (TREE_OPERAND (t, 0), want_rval)
10313 && RECUR (TREE_OPERAND (t, 1), any));
10315 case SCOPE_REF:
10316 return RECUR (TREE_OPERAND (t, 1), want_rval);
10318 case TARGET_EXPR:
10319 if (!TARGET_EXPR_DIRECT_INIT_P (t)
10320 && !TARGET_EXPR_ELIDING_P (t)
10321 && !literal_type_p (TREE_TYPE (t)))
10323 if (flags & tf_error)
10325 auto_diagnostic_group d;
10326 if (constexpr_error (loc, fundef_p,
10327 "temporary of non-literal type %qT in a "
10328 "constant expression", TREE_TYPE (t)))
10329 explain_non_literal_class (TREE_TYPE (t));
10331 return false;
10333 /* FALLTHRU */
10334 case INIT_EXPR:
10335 return RECUR (TREE_OPERAND (t, 1), rval);
10337 case CONSTRUCTOR:
10339 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
10340 constructor_elt *ce;
10341 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
10342 if (!RECUR (ce->value, want_rval))
10343 return false;
10344 return true;
10347 case TREE_LIST:
10349 gcc_assert (TREE_PURPOSE (t) == NULL_TREE
10350 || DECL_P (TREE_PURPOSE (t)));
10351 if (!RECUR (TREE_VALUE (t), want_rval))
10352 return false;
10353 if (TREE_CHAIN (t) == NULL_TREE)
10354 return true;
10355 return RECUR (TREE_CHAIN (t), want_rval);
10358 case TRUNC_DIV_EXPR:
10359 case CEIL_DIV_EXPR:
10360 case FLOOR_DIV_EXPR:
10361 case ROUND_DIV_EXPR:
10362 case TRUNC_MOD_EXPR:
10363 case CEIL_MOD_EXPR:
10364 case ROUND_MOD_EXPR:
10366 tree denom = TREE_OPERAND (t, 1);
10367 if (!RECUR (denom, rval))
10368 return false;
10369 /* We can't call cxx_eval_outermost_constant_expr on an expression
10370 that hasn't been through instantiate_non_dependent_expr yet. */
10371 if (!processing_template_decl)
10372 denom = cxx_eval_outermost_constant_expr (denom, true);
10373 if (integer_zerop (denom))
10375 if (flags & tf_error)
10376 constexpr_error (input_location, fundef_p,
10377 "division by zero is not a constant expression");
10378 return false;
10380 else
10382 want_rval = true;
10383 return RECUR (TREE_OPERAND (t, 0), want_rval);
10387 case COMPOUND_EXPR:
10389 /* check_return_expr sometimes wraps a TARGET_EXPR in a
10390 COMPOUND_EXPR; don't get confused. */
10391 tree op0 = TREE_OPERAND (t, 0);
10392 tree op1 = TREE_OPERAND (t, 1);
10393 STRIP_NOPS (op1);
10394 if (TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
10395 return RECUR (op0, want_rval);
10396 else
10397 goto binary;
10400 /* If the first operand is the non-short-circuit constant, look at
10401 the second operand; otherwise we only care about the first one for
10402 potentiality. */
10403 case TRUTH_AND_EXPR:
10404 case TRUTH_ANDIF_EXPR:
10405 tmp = boolean_true_node;
10406 goto truth;
10407 case TRUTH_OR_EXPR:
10408 case TRUTH_ORIF_EXPR:
10409 tmp = boolean_false_node;
10410 truth:
10412 tree op0 = TREE_OPERAND (t, 0);
10413 tree op1 = TREE_OPERAND (t, 1);
10414 if (!RECUR (op0, rval))
10415 return false;
10416 if (!(flags & tf_error) && RECUR (op1, rval))
10417 /* When quiet, try to avoid expensive trial evaluation by first
10418 checking potentiality of the second operand. */
10419 return true;
10420 if (!processing_template_decl)
10421 op0 = cxx_eval_outermost_constant_expr (op0, true);
10422 if (tree_int_cst_equal (op0, tmp))
10423 return (flags & tf_error) ? RECUR (op1, rval) : false;
10424 else
10425 return true;
10428 case PLUS_EXPR:
10429 case MULT_EXPR:
10430 case POINTER_PLUS_EXPR:
10431 case RDIV_EXPR:
10432 case EXACT_DIV_EXPR:
10433 case MIN_EXPR:
10434 case MAX_EXPR:
10435 case LSHIFT_EXPR:
10436 case RSHIFT_EXPR:
10437 case LROTATE_EXPR:
10438 case RROTATE_EXPR:
10439 case BIT_IOR_EXPR:
10440 case BIT_XOR_EXPR:
10441 case BIT_AND_EXPR:
10442 case TRUTH_XOR_EXPR:
10443 case UNORDERED_EXPR:
10444 case ORDERED_EXPR:
10445 case UNLT_EXPR:
10446 case UNLE_EXPR:
10447 case UNGT_EXPR:
10448 case UNGE_EXPR:
10449 case UNEQ_EXPR:
10450 case LTGT_EXPR:
10451 case RANGE_EXPR:
10452 case COMPLEX_EXPR:
10453 want_rval = true;
10454 /* Fall through. */
10455 case ARRAY_REF:
10456 case ARRAY_RANGE_REF:
10457 case MEMBER_REF:
10458 case DOTSTAR_EXPR:
10459 case MEM_REF:
10460 case BINARY_LEFT_FOLD_EXPR:
10461 case BINARY_RIGHT_FOLD_EXPR:
10462 binary:
10463 for (i = 0; i < 2; ++i)
10464 if (!RECUR (TREE_OPERAND (t, i), want_rval))
10465 return false;
10466 return true;
10468 case VEC_PERM_EXPR:
10469 for (i = 0; i < 3; ++i)
10470 if (!RECUR (TREE_OPERAND (t, i), true))
10471 return false;
10472 return true;
10474 case COND_EXPR:
10475 if (COND_EXPR_IS_VEC_DELETE (t) && cxx_dialect < cxx20)
10477 if (flags & tf_error)
10478 constexpr_error (loc, fundef_p, "%<delete[]%> is not a "
10479 "constant expression");
10480 return false;
10482 /* Fall through. */
10483 case IF_STMT:
10484 case VEC_COND_EXPR:
10485 /* If the condition is a known constant, we know which of the legs we
10486 care about; otherwise we only require that the condition and
10487 either of the legs be potentially constant. */
10488 tmp = TREE_OPERAND (t, 0);
10489 if (!RECUR (tmp, rval))
10490 return false;
10491 if (!processing_template_decl)
10492 tmp = cxx_eval_outermost_constant_expr (tmp, true);
10493 /* potential_constant_expression* isn't told if it is called for
10494 manifestly_const_eval or not, so for consteval if always
10495 process both branches as if the condition is not a known
10496 constant. */
10497 if (TREE_CODE (t) != IF_STMT || !IF_STMT_CONSTEVAL_P (t))
10499 if (integer_zerop (tmp))
10500 return RECUR (TREE_OPERAND (t, 2), want_rval);
10501 else if (TREE_CODE (tmp) == INTEGER_CST)
10502 return RECUR (TREE_OPERAND (t, 1), want_rval);
10504 tmp = *jump_target;
10505 for (i = 1; i < 3; ++i)
10507 tree this_jump_target = tmp;
10508 if (potential_constant_expression_1 (TREE_OPERAND (t, i),
10509 want_rval, strict, now, fundef_p,
10510 tf_none, &this_jump_target))
10512 if (returns (&this_jump_target))
10513 *jump_target = this_jump_target;
10514 else if (!returns (jump_target))
10516 if (breaks (&this_jump_target)
10517 || continues (&this_jump_target))
10518 *jump_target = this_jump_target;
10519 if (i == 1)
10521 /* If the then branch is potentially constant, but
10522 does not return, check if the else branch
10523 couldn't return, break or continue. */
10524 hash_set<tree> pset;
10525 check_for_return_continue_data data = { &pset, NULL_TREE,
10526 NULL_TREE };
10527 if (tree ret_expr
10528 = cp_walk_tree (&TREE_OPERAND (t, 2),
10529 check_for_return_continue, &data,
10530 &pset))
10531 *jump_target = ret_expr;
10532 else if (*jump_target == NULL_TREE)
10534 if (data.continue_stmt)
10535 *jump_target = data.continue_stmt;
10536 else if (data.break_stmt)
10537 *jump_target = data.break_stmt;
10541 return true;
10544 if (flags & tf_error)
10546 if (TREE_CODE (t) == IF_STMT)
10547 constexpr_error (loc, fundef_p, "neither branch of %<if%> is a "
10548 "constant expression");
10549 else
10550 constexpr_error (loc, fundef_p, "expression %qE is not a "
10551 "constant expression", t);
10553 return false;
10555 case VEC_INIT_EXPR:
10556 if (VEC_INIT_EXPR_IS_CONSTEXPR (t))
10557 return true;
10558 if (flags & tf_error)
10560 if (constexpr_error (loc, fundef_p, "non-constant array "
10561 "initialization"))
10562 diagnose_non_constexpr_vec_init (t);
10564 return false;
10566 case TYPE_DECL:
10567 case TAG_DEFN:
10568 /* We can see these in statement-expressions. */
10569 return true;
10571 case CLEANUP_STMT:
10572 if (!RECUR (CLEANUP_BODY (t), any))
10573 return false;
10574 if (!CLEANUP_EH_ONLY (t) && !RECUR (CLEANUP_EXPR (t), any))
10575 return false;
10576 return true;
10578 case EMPTY_CLASS_EXPR:
10579 return true;
10581 case GOTO_EXPR:
10583 tree *target = &TREE_OPERAND (t, 0);
10584 /* Gotos representing break, continue and cdtor return are OK. */
10585 if (breaks (target) || continues (target) || returns (target))
10587 *jump_target = *target;
10588 return true;
10590 if (flags & tf_error)
10591 constexpr_error (loc, fundef_p, "%<goto%> is not a constant "
10592 "expression");
10593 return false;
10596 case ASSERTION_STMT:
10597 case PRECONDITION_STMT:
10598 case POSTCONDITION_STMT:
10599 if (!checked_contract_p (get_contract_semantic (t)))
10600 return true;
10601 return RECUR (CONTRACT_CONDITION (t), rval);
10603 case LABEL_EXPR:
10604 t = LABEL_EXPR_LABEL (t);
10605 if (DECL_ARTIFICIAL (t) || cxx_dialect >= cxx23)
10606 return true;
10607 else if (flags & tf_error)
10608 constexpr_error (loc, fundef_p, "label definition in %<constexpr%> "
10609 "function only available with %<-std=c++2b%> or "
10610 "%<-std=gnu++2b%>");
10611 return false;
10613 case ANNOTATE_EXPR:
10614 return RECUR (TREE_OPERAND (t, 0), rval);
10616 case BIT_CAST_EXPR:
10617 return RECUR (TREE_OPERAND (t, 0), rval);
10619 /* Coroutine await, yield and return expressions are not. */
10620 case CO_AWAIT_EXPR:
10621 case CO_YIELD_EXPR:
10622 case CO_RETURN_EXPR:
10623 return false;
10625 case NONTYPE_ARGUMENT_PACK:
10627 tree args = ARGUMENT_PACK_ARGS (t);
10628 int len = TREE_VEC_LENGTH (args);
10629 for (int i = 0; i < len; ++i)
10630 if (!RECUR (TREE_VEC_ELT (args, i), any))
10631 return false;
10632 return true;
10635 default:
10636 if (objc_non_constant_expr_p (t))
10637 return false;
10639 sorry ("unexpected AST of kind %s", get_tree_code_name (TREE_CODE (t)));
10640 gcc_unreachable ();
10641 return false;
10643 #undef RECUR
10646 bool
10647 potential_constant_expression_1 (tree t, bool want_rval, bool strict, bool now,
10648 bool fundef_p, tsubst_flags_t flags)
10650 if (flags & tf_error)
10652 /* Check potentiality quietly first, as that could be performed more
10653 efficiently in some cases (currently only for TRUTH_*_EXPR). If
10654 that fails, replay the check noisily to give errors. */
10655 flags &= ~tf_error;
10656 if (potential_constant_expression_1 (t, want_rval, strict, now, fundef_p,
10657 flags))
10658 return true;
10659 flags |= tf_error;
10662 tree target = NULL_TREE;
10663 return potential_constant_expression_1 (t, want_rval, strict, now, fundef_p,
10664 flags, &target);
10667 /* The main entry point to the above. */
10669 bool
10670 potential_constant_expression (tree t)
10672 return potential_constant_expression_1 (t, /*want_rval*/false, /*strict*/true,
10673 /*now*/false, /*fundef_p*/false,
10674 tf_none);
10677 /* As above, but require a constant rvalue. */
10679 bool
10680 potential_rvalue_constant_expression (tree t)
10682 return potential_constant_expression_1 (t, /*want_rval*/true, /*strict*/true,
10683 /*now*/false, /*fundef_p*/false,
10684 tf_none);
10687 /* Like above, but complain about non-constant expressions. */
10689 bool
10690 require_potential_constant_expression (tree t)
10692 return potential_constant_expression_1 (t, /*want_rval*/false, /*strict*/true,
10693 /*now*/false, /*fundef_p*/false,
10694 tf_warning_or_error);
10697 /* Cross product of the above. */
10699 bool
10700 require_potential_rvalue_constant_expression (tree t)
10702 return potential_constant_expression_1 (t, /*want_rval*/true, /*strict*/true,
10703 /*now*/false, /*fundef_p*/false,
10704 tf_warning_or_error);
10707 /* Like require_potential_rvalue_constant_expression, but fundef_p is true. */
10709 bool
10710 require_potential_rvalue_constant_expression_fncheck (tree t)
10712 return potential_constant_expression_1 (t, /*want_rval*/true, /*strict*/true,
10713 /*now*/false, /*fundef_p*/true,
10714 tf_warning_or_error);
10717 /* Like above, but don't consider PARM_DECL a potential_constant_expression. */
10719 bool
10720 require_rvalue_constant_expression (tree t)
10722 return potential_constant_expression_1 (t, /*want_rval*/true, /*strict*/true,
10723 /*now*/true, /*fundef_p*/false,
10724 tf_warning_or_error);
10727 /* Like potential_constant_expression, but don't consider possible constexpr
10728 substitution of the current function. That is, PARM_DECL qualifies under
10729 potential_constant_expression, but not here.
10731 This is basically what you can check when any actual constant values might
10732 be value-dependent. */
10734 bool
10735 is_constant_expression (tree t)
10737 return potential_constant_expression_1 (t, /*want_rval*/false, /*strict*/true,
10738 /*now*/true, /*fundef_p*/false,
10739 tf_none);
10742 /* As above, but expect an rvalue. */
10744 bool
10745 is_rvalue_constant_expression (tree t)
10747 return potential_constant_expression_1 (t, /*want_rval*/true, /*strict*/true,
10748 /*now*/true, /*fundef_p*/false,
10749 tf_none);
10752 /* Like above, but complain about non-constant expressions. */
10754 bool
10755 require_constant_expression (tree t)
10757 return potential_constant_expression_1 (t, /*want_rval*/false, /*strict*/true,
10758 /*now*/true, /*fundef_p*/false,
10759 tf_warning_or_error);
10762 /* Like is_constant_expression, but allow const variables that are not allowed
10763 under constexpr rules. */
10765 bool
10766 is_static_init_expression (tree t)
10768 return potential_constant_expression_1 (t, /*want_rval*/false,
10769 /*strict*/false, /*now*/true,
10770 /*fundef_p*/false, tf_none);
10773 /* Returns true if T is a potential constant expression that is not
10774 instantiation-dependent, and therefore a candidate for constant folding even
10775 in a template. */
10777 bool
10778 is_nondependent_constant_expression (tree t)
10780 return (!type_unknown_p (t)
10781 && is_constant_expression (t)
10782 && !instantiation_dependent_expression_p (t));
10785 /* Returns true if T is a potential static initializer expression that is not
10786 instantiation-dependent. */
10788 bool
10789 is_nondependent_static_init_expression (tree t)
10791 return (!type_unknown_p (t)
10792 && is_static_init_expression (t)
10793 && !instantiation_dependent_expression_p (t));
10796 /* True iff FN is an implicitly constexpr function. */
10798 bool
10799 decl_implicit_constexpr_p (tree fn)
10801 if (!(flag_implicit_constexpr
10802 && TREE_CODE (fn) == FUNCTION_DECL
10803 && DECL_DECLARED_CONSTEXPR_P (fn)))
10804 return false;
10806 if (DECL_CLONED_FUNCTION_P (fn))
10807 fn = DECL_CLONED_FUNCTION (fn);
10809 return (DECL_LANG_SPECIFIC (fn)
10810 && DECL_LANG_SPECIFIC (fn)->u.fn.implicit_constexpr);
10813 /* Finalize constexpr processing after parsing. */
10815 void
10816 fini_constexpr (void)
10818 /* The contexpr call and fundef copies tables are no longer needed. */
10819 constexpr_call_table = NULL;
10820 fundef_copies_table = NULL;
10823 #include "gt-cp-constexpr.h"