c++: fix in-charge parm in constexpr
[official-gcc.git] / gcc / cp / constexpr.cc
blob9d9e96c2afdd207c2e18225f5f2aadc68d981244
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-2023 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))
267 if (cxx_dialect < cxx20)
269 ret = false;
270 if (complain)
271 error_at (DECL_SOURCE_LOCATION (fun),
272 "%<constexpr%> destructors only available"
273 " with %<-std=c++20%> or %<-std=gnu++20%>");
276 else if (!DECL_CONSTRUCTOR_P (fun))
278 tree rettype = TREE_TYPE (TREE_TYPE (fun));
279 if (!literal_type_p (rettype))
281 ret = false;
282 if (complain)
284 auto_diagnostic_group d;
285 if (constexpr_error (input_location, /*constexpr_fundef_p*/true,
286 "invalid return type %qT of %<constexpr%> "
287 "function %q+D", rettype, fun))
288 explain_non_literal_class (rettype);
292 /* C++14 DR 1684 removed this restriction. */
293 if (cxx_dialect < cxx14
294 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fun)
295 && !CLASSTYPE_LITERAL_P (DECL_CONTEXT (fun)))
297 ret = false;
298 if (complain)
300 auto_diagnostic_group d;
301 if (pedwarn (DECL_SOURCE_LOCATION (fun), OPT_Wpedantic,
302 "enclosing class of %<constexpr%> non-static"
303 " member function %q+#D is not a literal type",
304 fun))
305 explain_non_literal_class (DECL_CONTEXT (fun));
309 else if (CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fun)))
311 ret = false;
312 if (complain)
313 error ("%q#T has virtual base classes", DECL_CONTEXT (fun));
316 return ret;
319 /* Subroutine of build_data_member_initialization. MEMBER is a COMPONENT_REF
320 for a member of an anonymous aggregate, INIT is the initializer for that
321 member, and VEC_OUTER is the vector of constructor elements for the class
322 whose constructor we are processing. Add the initializer to the vector
323 and return true to indicate success. */
325 static bool
326 build_anon_member_initialization (tree member, tree init,
327 vec<constructor_elt, va_gc> **vec_outer)
329 /* MEMBER presents the relevant fields from the inside out, but we need
330 to build up the initializer from the outside in so that we can reuse
331 previously built CONSTRUCTORs if this is, say, the second field in an
332 anonymous struct. So we use a vec as a stack. */
333 auto_vec<tree, 2> fields;
336 fields.safe_push (TREE_OPERAND (member, 1));
337 member = TREE_OPERAND (member, 0);
339 while (ANON_AGGR_TYPE_P (TREE_TYPE (member))
340 && TREE_CODE (member) == COMPONENT_REF);
342 /* VEC has the constructor elements vector for the context of FIELD.
343 If FIELD is an anonymous aggregate, we will push inside it. */
344 vec<constructor_elt, va_gc> **vec = vec_outer;
345 tree field;
346 while (field = fields.pop(),
347 ANON_AGGR_TYPE_P (TREE_TYPE (field)))
349 tree ctor;
350 /* If there is already an outer constructor entry for the anonymous
351 aggregate FIELD, use it; otherwise, insert one. */
352 if (vec_safe_is_empty (*vec)
353 || (*vec)->last().index != field)
355 ctor = build_constructor (TREE_TYPE (field), NULL);
356 CONSTRUCTOR_APPEND_ELT (*vec, field, ctor);
358 else
359 ctor = (*vec)->last().value;
360 vec = &CONSTRUCTOR_ELTS (ctor);
363 /* Now we're at the innermost field, the one that isn't an anonymous
364 aggregate. Add its initializer to the CONSTRUCTOR and we're done. */
365 gcc_assert (fields.is_empty());
366 CONSTRUCTOR_APPEND_ELT (*vec, field, init);
368 return true;
371 /* Subroutine of build_constexpr_constructor_member_initializers.
372 The expression tree T represents a data member initialization
373 in a (constexpr) constructor definition. Build a pairing of
374 the data member with its initializer, and prepend that pair
375 to the existing initialization pair INITS. */
377 static bool
378 build_data_member_initialization (tree t, vec<constructor_elt, va_gc> **vec)
380 tree member, init;
381 if (TREE_CODE (t) == CLEANUP_POINT_EXPR)
382 t = TREE_OPERAND (t, 0);
383 if (TREE_CODE (t) == EXPR_STMT)
384 t = TREE_OPERAND (t, 0);
385 if (t == error_mark_node)
386 return false;
387 if (TREE_CODE (t) == STATEMENT_LIST)
389 for (tree stmt : tsi_range (t))
390 if (! build_data_member_initialization (stmt, vec))
391 return false;
392 return true;
394 if (TREE_CODE (t) == CLEANUP_STMT)
396 /* We can't see a CLEANUP_STMT in a constructor for a literal class,
397 but we can in a constexpr constructor for a non-literal class. Just
398 ignore it; either all the initialization will be constant, in which
399 case the cleanup can't run, or it can't be constexpr.
400 Still recurse into CLEANUP_BODY. */
401 return build_data_member_initialization (CLEANUP_BODY (t), vec);
403 if (TREE_CODE (t) == CONVERT_EXPR)
404 t = TREE_OPERAND (t, 0);
405 if (TREE_CODE (t) == INIT_EXPR
406 /* vptr initialization shows up as a MODIFY_EXPR. In C++14 we only
407 use what this function builds for cx_check_missing_mem_inits, and
408 assignment in the ctor body doesn't count. */
409 || (cxx_dialect < cxx14 && TREE_CODE (t) == MODIFY_EXPR))
411 member = TREE_OPERAND (t, 0);
412 init = break_out_target_exprs (TREE_OPERAND (t, 1));
414 else if (TREE_CODE (t) == CALL_EXPR)
416 tree fn = get_callee_fndecl (t);
417 if (!fn || !DECL_CONSTRUCTOR_P (fn))
418 /* We're only interested in calls to subobject constructors. */
419 return true;
420 member = CALL_EXPR_ARG (t, 0);
421 /* We don't use build_cplus_new here because it complains about
422 abstract bases. Leaving the call unwrapped means that it has the
423 wrong type, but cxx_eval_constant_expression doesn't care. */
424 init = break_out_target_exprs (t);
426 else if (TREE_CODE (t) == BIND_EXPR)
427 return build_data_member_initialization (BIND_EXPR_BODY (t), vec);
428 else
429 /* Don't add anything else to the CONSTRUCTOR. */
430 return true;
431 if (INDIRECT_REF_P (member))
432 member = TREE_OPERAND (member, 0);
433 if (TREE_CODE (member) == NOP_EXPR)
435 tree op = member;
436 STRIP_NOPS (op);
437 if (TREE_CODE (op) == ADDR_EXPR)
439 gcc_assert (same_type_ignoring_top_level_qualifiers_p
440 (TREE_TYPE (TREE_TYPE (op)),
441 TREE_TYPE (TREE_TYPE (member))));
442 /* Initializing a cv-qualified member; we need to look through
443 the const_cast. */
444 member = op;
446 else if (op == current_class_ptr
447 && (same_type_ignoring_top_level_qualifiers_p
448 (TREE_TYPE (TREE_TYPE (member)),
449 current_class_type)))
450 /* Delegating constructor. */
451 member = op;
452 else
454 /* This is an initializer for an empty base; keep it for now so
455 we can check it in cxx_eval_bare_aggregate. */
456 gcc_assert (is_empty_class (TREE_TYPE (TREE_TYPE (member))));
459 if (TREE_CODE (member) == ADDR_EXPR)
460 member = TREE_OPERAND (member, 0);
461 if (TREE_CODE (member) == COMPONENT_REF)
463 tree aggr = TREE_OPERAND (member, 0);
464 if (TREE_CODE (aggr) == VAR_DECL)
465 /* Initializing a local variable, don't add anything. */
466 return true;
467 if (TREE_CODE (aggr) != COMPONENT_REF)
468 /* Normal member initialization. */
469 member = TREE_OPERAND (member, 1);
470 else if (ANON_AGGR_TYPE_P (TREE_TYPE (aggr)))
471 /* Initializing a member of an anonymous union. */
472 return build_anon_member_initialization (member, init, vec);
473 else
474 /* We're initializing a vtable pointer in a base. Leave it as
475 COMPONENT_REF so we remember the path to get to the vfield. */
476 gcc_assert (TREE_TYPE (member) == vtbl_ptr_type_node);
479 /* Value-initialization can produce multiple initializers for the
480 same field; use the last one. */
481 if (!vec_safe_is_empty (*vec) && (*vec)->last().index == member)
482 (*vec)->last().value = init;
483 else
484 CONSTRUCTOR_APPEND_ELT (*vec, member, init);
485 return true;
488 /* Subroutine of check_constexpr_ctor_body_1 and constexpr_fn_retval.
489 In C++11 mode checks that the TYPE_DECLs in the BIND_EXPR_VARS of a
490 BIND_EXPR conform to 7.1.5/3/4 on typedef and alias declarations. */
492 static bool
493 check_constexpr_bind_expr_vars (tree t)
495 gcc_assert (TREE_CODE (t) == BIND_EXPR);
497 for (tree var = BIND_EXPR_VARS (t); var; var = DECL_CHAIN (var))
498 if (TREE_CODE (var) == TYPE_DECL
499 && DECL_IMPLICIT_TYPEDEF_P (var)
500 && !LAMBDA_TYPE_P (TREE_TYPE (var)))
501 return false;
502 return true;
505 /* Subroutine of check_constexpr_ctor_body. */
507 static bool
508 check_constexpr_ctor_body_1 (tree last, tree list)
510 switch (TREE_CODE (list))
512 case DECL_EXPR:
513 if (TREE_CODE (DECL_EXPR_DECL (list)) == USING_DECL
514 || TREE_CODE (DECL_EXPR_DECL (list)) == TYPE_DECL)
515 return true;
516 return false;
518 case CLEANUP_POINT_EXPR:
519 return check_constexpr_ctor_body (last, TREE_OPERAND (list, 0),
520 /*complain=*/false);
522 case BIND_EXPR:
523 if (!check_constexpr_bind_expr_vars (list)
524 || !check_constexpr_ctor_body (last, BIND_EXPR_BODY (list),
525 /*complain=*/false))
526 return false;
527 return true;
529 case USING_STMT:
530 case STATIC_ASSERT:
531 case DEBUG_BEGIN_STMT:
532 return true;
534 default:
535 return false;
539 /* Make sure that there are no statements after LAST in the constructor
540 body represented by LIST. */
542 bool
543 check_constexpr_ctor_body (tree last, tree list, bool complain)
545 /* C++14 doesn't require a constexpr ctor to have an empty body. */
546 if (cxx_dialect >= cxx14)
547 return true;
549 bool ok = true;
550 if (TREE_CODE (list) == STATEMENT_LIST)
552 tree_stmt_iterator i = tsi_last (list);
553 for (; !tsi_end_p (i); tsi_prev (&i))
555 tree t = tsi_stmt (i);
556 if (t == last)
557 break;
558 if (!check_constexpr_ctor_body_1 (last, t))
560 ok = false;
561 break;
565 else if (list != last
566 && !check_constexpr_ctor_body_1 (last, list))
567 ok = false;
568 if (!ok)
570 if (complain)
571 error ("%<constexpr%> constructor does not have empty body");
572 DECL_DECLARED_CONSTEXPR_P (current_function_decl) = false;
574 return ok;
577 /* V is a vector of constructor elements built up for the base and member
578 initializers of a constructor for TYPE. They need to be in increasing
579 offset order, which they might not be yet if TYPE has a primary base
580 which is not first in the base-clause or a vptr and at least one base
581 all of which are non-primary. */
583 static vec<constructor_elt, va_gc> *
584 sort_constexpr_mem_initializers (tree type, vec<constructor_elt, va_gc> *v)
586 tree pri = CLASSTYPE_PRIMARY_BINFO (type);
587 tree field_type;
588 unsigned i;
589 constructor_elt *ce;
591 if (pri)
592 field_type = BINFO_TYPE (pri);
593 else if (TYPE_CONTAINS_VPTR_P (type))
594 field_type = vtbl_ptr_type_node;
595 else
596 return v;
598 /* Find the element for the primary base or vptr and move it to the
599 beginning of the vec. */
600 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
601 if (TREE_TYPE (ce->index) == field_type)
602 break;
604 if (i > 0 && i < vec_safe_length (v))
606 vec<constructor_elt, va_gc> &vref = *v;
607 constructor_elt elt = vref[i];
608 for (; i > 0; --i)
609 vref[i] = vref[i-1];
610 vref[0] = elt;
613 return v;
616 /* Build compile-time evalable representations of member-initializer list
617 for a constexpr constructor. */
619 static tree
620 build_constexpr_constructor_member_initializers (tree type, tree body)
622 vec<constructor_elt, va_gc> *vec = NULL;
623 bool ok = true;
624 while (true)
625 switch (TREE_CODE (body))
627 case MUST_NOT_THROW_EXPR:
628 case EH_SPEC_BLOCK:
629 body = TREE_OPERAND (body, 0);
630 break;
632 case STATEMENT_LIST:
633 for (tree stmt : tsi_range (body))
635 body = stmt;
636 if (TREE_CODE (body) == BIND_EXPR)
637 break;
639 break;
641 case BIND_EXPR:
642 body = BIND_EXPR_BODY (body);
643 goto found;
645 default:
646 gcc_unreachable ();
648 found:
649 if (TREE_CODE (body) == TRY_BLOCK)
651 body = TREE_OPERAND (body, 0);
652 if (TREE_CODE (body) == BIND_EXPR)
653 body = BIND_EXPR_BODY (body);
655 if (TREE_CODE (body) == CLEANUP_POINT_EXPR)
657 body = TREE_OPERAND (body, 0);
658 if (TREE_CODE (body) == EXPR_STMT)
659 body = TREE_OPERAND (body, 0);
660 if (TREE_CODE (body) == INIT_EXPR
661 && (same_type_ignoring_top_level_qualifiers_p
662 (TREE_TYPE (TREE_OPERAND (body, 0)),
663 current_class_type)))
665 /* Trivial copy. */
666 return TREE_OPERAND (body, 1);
668 ok = build_data_member_initialization (body, &vec);
670 else if (TREE_CODE (body) == STATEMENT_LIST)
672 for (tree stmt : tsi_range (body))
674 ok = build_data_member_initialization (stmt, &vec);
675 if (!ok)
676 break;
679 else if (EXPR_P (body))
680 ok = build_data_member_initialization (body, &vec);
681 else
682 gcc_assert (errorcount > 0);
683 if (ok)
685 if (vec_safe_length (vec) > 0)
687 /* In a delegating constructor, return the target. */
688 constructor_elt *ce = &(*vec)[0];
689 if (ce->index == current_class_ptr)
691 body = ce->value;
692 vec_free (vec);
693 return body;
696 vec = sort_constexpr_mem_initializers (type, vec);
697 return build_constructor (type, vec);
699 else
700 return error_mark_node;
703 /* We have an expression tree T that represents a call, either CALL_EXPR
704 or AGGR_INIT_EXPR. If the call is lexically to a named function,
705 retrun the _DECL for that function. */
707 static tree
708 get_function_named_in_call (tree t)
710 tree fun = cp_get_callee (t);
711 if (fun && TREE_CODE (fun) == ADDR_EXPR
712 && TREE_CODE (TREE_OPERAND (fun, 0)) == FUNCTION_DECL)
713 fun = TREE_OPERAND (fun, 0);
714 return fun;
717 /* Subroutine of check_constexpr_fundef. BODY is the body of a function
718 declared to be constexpr, or a sub-statement thereof. Returns the
719 return value if suitable, error_mark_node for a statement not allowed in
720 a constexpr function, or NULL_TREE if no return value was found. */
722 tree
723 constexpr_fn_retval (tree body)
725 switch (TREE_CODE (body))
727 case STATEMENT_LIST:
729 tree expr = NULL_TREE;
730 for (tree stmt : tsi_range (body))
732 tree s = constexpr_fn_retval (stmt);
733 if (s == error_mark_node)
734 return error_mark_node;
735 else if (s == NULL_TREE)
736 /* Keep iterating. */;
737 else if (expr)
738 /* Multiple return statements. */
739 return error_mark_node;
740 else
741 expr = s;
743 return expr;
746 case RETURN_EXPR:
747 return break_out_target_exprs (TREE_OPERAND (body, 0));
749 case DECL_EXPR:
751 tree decl = DECL_EXPR_DECL (body);
752 if (TREE_CODE (decl) == USING_DECL
753 /* Accept __func__, __FUNCTION__, and __PRETTY_FUNCTION__. */
754 || DECL_ARTIFICIAL (decl))
755 return NULL_TREE;
756 return error_mark_node;
759 case CLEANUP_POINT_EXPR:
760 return constexpr_fn_retval (TREE_OPERAND (body, 0));
762 case BIND_EXPR:
763 if (!check_constexpr_bind_expr_vars (body))
764 return error_mark_node;
765 return constexpr_fn_retval (BIND_EXPR_BODY (body));
767 case USING_STMT:
768 case DEBUG_BEGIN_STMT:
769 return NULL_TREE;
771 case CALL_EXPR:
773 tree fun = get_function_named_in_call (body);
774 if (fun != NULL_TREE
775 && fndecl_built_in_p (fun, BUILT_IN_UNREACHABLE))
776 return NULL_TREE;
778 /* Fallthru. */
780 default:
781 return error_mark_node;
785 /* Subroutine of check_constexpr_fundef. BODY is the DECL_SAVED_TREE of
786 FUN; do the necessary transformations to turn it into a single expression
787 that we can store in the hash table. */
789 static tree
790 massage_constexpr_body (tree fun, tree body)
792 if (DECL_CONSTRUCTOR_P (fun))
793 body = build_constexpr_constructor_member_initializers
794 (DECL_CONTEXT (fun), body);
795 else if (cxx_dialect < cxx14)
797 if (TREE_CODE (body) == EH_SPEC_BLOCK)
798 body = EH_SPEC_STMTS (body);
799 if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
800 body = TREE_OPERAND (body, 0);
801 body = constexpr_fn_retval (body);
803 return body;
806 /* CTYPE is a type constructed from BODY. Return true if some
807 bases/fields are uninitialized, and complain if COMPLAIN. */
809 static bool
810 cx_check_missing_mem_inits (tree ctype, tree body, bool complain)
812 /* We allow uninitialized bases/fields in C++20. */
813 if (cxx_dialect >= cxx20)
814 return false;
816 unsigned nelts = 0;
818 if (body)
820 if (TREE_CODE (body) != CONSTRUCTOR)
821 return false;
822 nelts = CONSTRUCTOR_NELTS (body);
824 tree field = TYPE_FIELDS (ctype);
826 if (TREE_CODE (ctype) == UNION_TYPE)
828 if (nelts == 0 && next_aggregate_field (field))
830 if (complain)
831 error ("%<constexpr%> constructor for union %qT must "
832 "initialize exactly one non-static data member", ctype);
833 return true;
835 return false;
838 /* Iterate over the CONSTRUCTOR, checking any missing fields don't
839 need an explicit initialization. */
840 bool bad = false;
841 for (unsigned i = 0; i <= nelts; ++i)
843 tree index = NULL_TREE;
844 if (i < nelts)
846 index = CONSTRUCTOR_ELT (body, i)->index;
847 /* Skip base and vtable inits. */
848 if (TREE_CODE (index) != FIELD_DECL
849 || DECL_ARTIFICIAL (index))
850 continue;
853 for (; field != index; field = DECL_CHAIN (field))
855 tree ftype;
856 if (TREE_CODE (field) != FIELD_DECL)
857 continue;
858 if (DECL_UNNAMED_BIT_FIELD (field))
859 continue;
860 if (DECL_ARTIFICIAL (field))
861 continue;
862 if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
864 /* Recurse to check the anonymous aggregate member. */
865 bad |= cx_check_missing_mem_inits
866 (TREE_TYPE (field), NULL_TREE, complain);
867 if (bad && !complain)
868 return true;
869 continue;
871 ftype = TREE_TYPE (field);
872 if (!ftype || !TYPE_P (ftype) || !COMPLETE_TYPE_P (ftype))
873 /* A flexible array can't be intialized here, so don't complain
874 that it isn't. */
875 continue;
876 if (is_empty_field (field))
877 /* An empty field doesn't need an initializer. */
878 continue;
879 ftype = strip_array_types (ftype);
880 if (type_has_constexpr_default_constructor (ftype))
882 /* It's OK to skip a member with a trivial constexpr ctor.
883 A constexpr ctor that isn't trivial should have been
884 added in by now. */
885 gcc_checking_assert (!TYPE_HAS_COMPLEX_DFLT (ftype)
886 || errorcount != 0);
887 continue;
889 if (!complain)
890 return true;
891 auto_diagnostic_group d;
892 error ("member %qD must be initialized by mem-initializer "
893 "in %<constexpr%> constructor", field);
894 inform (DECL_SOURCE_LOCATION (field), "declared here");
895 bad = true;
897 if (field == NULL_TREE)
898 break;
900 if (ANON_AGGR_TYPE_P (TREE_TYPE (index)))
902 /* Check the anonymous aggregate initializer is valid. */
903 bad |= cx_check_missing_mem_inits
904 (TREE_TYPE (index), CONSTRUCTOR_ELT (body, i)->value, complain);
905 if (bad && !complain)
906 return true;
908 field = DECL_CHAIN (field);
911 return bad;
914 /* We are processing the definition of the constexpr function FUN.
915 Check that its body fulfills the apropriate requirements and
916 enter it in the constexpr function definition table. */
918 void
919 maybe_save_constexpr_fundef (tree fun)
921 if (processing_template_decl
922 || cp_function_chain->invalid_constexpr
923 || (DECL_CLONED_FUNCTION_P (fun) && !DECL_DELETING_DESTRUCTOR_P (fun)))
924 return;
926 /* With -fimplicit-constexpr, try to make inlines constexpr. We'll
927 actually set DECL_DECLARED_CONSTEXPR_P below if the checks pass. */
928 bool implicit = false;
929 if (flag_implicit_constexpr)
931 if (DECL_DELETING_DESTRUCTOR_P (fun)
932 && decl_implicit_constexpr_p (DECL_CLONED_FUNCTION (fun)))
933 /* Don't inherit implicit constexpr from the non-deleting
934 destructor. */
935 DECL_DECLARED_CONSTEXPR_P (fun) = false;
937 if (!DECL_DECLARED_CONSTEXPR_P (fun)
938 && DECL_DECLARED_INLINE_P (fun)
939 && !lookup_attribute ("noinline", DECL_ATTRIBUTES (fun)))
940 implicit = true;
943 if (!DECL_DECLARED_CONSTEXPR_P (fun) && !implicit)
944 return;
946 bool complain = !DECL_GENERATED_P (fun) && !implicit;
948 if (!is_valid_constexpr_fn (fun, complain))
949 return;
951 tree massaged = massage_constexpr_body (fun, DECL_SAVED_TREE (fun));
952 if (massaged == NULL_TREE || massaged == error_mark_node)
954 if (!DECL_CONSTRUCTOR_P (fun) && complain)
955 error ("body of %<constexpr%> function %qD not a return-statement",
956 fun);
957 return;
960 bool potential = potential_rvalue_constant_expression (massaged);
961 if (!potential && complain)
962 require_potential_rvalue_constant_expression_fncheck (massaged);
964 if (DECL_CONSTRUCTOR_P (fun) && potential
965 && !DECL_DEFAULTED_FN (fun))
967 if (cx_check_missing_mem_inits (DECL_CONTEXT (fun),
968 massaged, complain))
969 potential = false;
970 else if (cxx_dialect > cxx11)
972 /* What we got from massage_constexpr_body is pretty much just the
973 ctor-initializer, also check the body. */
974 massaged = DECL_SAVED_TREE (fun);
975 potential = potential_rvalue_constant_expression (massaged);
976 if (!potential && complain)
977 require_potential_rvalue_constant_expression_fncheck (massaged);
981 if (!potential && complain
982 /* If -Wno-invalid-constexpr was specified, we haven't complained
983 about non-constant expressions yet. Register the function and
984 complain in explain_invalid_constexpr_fn if the function is
985 called. */
986 && warn_invalid_constexpr != 0)
987 return;
989 if (implicit)
991 if (potential)
993 DECL_DECLARED_CONSTEXPR_P (fun) = true;
994 DECL_LANG_SPECIFIC (fun)->u.fn.implicit_constexpr = true;
995 if (DECL_CONSTRUCTOR_P (fun))
996 TYPE_HAS_CONSTEXPR_CTOR (DECL_CONTEXT (fun)) = true;
998 else
999 /* Don't bother keeping the pre-generic body of unsuitable functions
1000 not explicitly declared constexpr. */
1001 return;
1004 constexpr_fundef entry = {fun, NULL_TREE, NULL_TREE, NULL_TREE};
1005 bool clear_ctx = false;
1006 if (DECL_RESULT (fun) && DECL_CONTEXT (DECL_RESULT (fun)) == NULL_TREE)
1008 clear_ctx = true;
1009 DECL_CONTEXT (DECL_RESULT (fun)) = fun;
1011 tree saved_fn = current_function_decl;
1012 current_function_decl = fun;
1013 entry.body = copy_fn (entry.decl, entry.parms, entry.result);
1014 current_function_decl = saved_fn;
1015 if (clear_ctx)
1016 DECL_CONTEXT (DECL_RESULT (entry.decl)) = NULL_TREE;
1017 if (!potential)
1018 /* For a template instantiation, we want to remember the pre-generic body
1019 for explain_invalid_constexpr_fn, but do tell cxx_eval_call_expression
1020 that it doesn't need to bother trying to expand the function. */
1021 entry.result = error_mark_node;
1023 register_constexpr_fundef (entry);
1026 /* BODY is a validated and massaged definition of a constexpr
1027 function. Register it in the hash table. */
1029 void
1030 register_constexpr_fundef (const constexpr_fundef &value)
1032 /* Create the constexpr function table if necessary. */
1033 if (constexpr_fundef_table == NULL)
1034 constexpr_fundef_table
1035 = hash_table<constexpr_fundef_hasher>::create_ggc (101);
1037 constexpr_fundef **slot = constexpr_fundef_table->find_slot
1038 (const_cast<constexpr_fundef *> (&value), INSERT);
1040 gcc_assert (*slot == NULL);
1041 *slot = ggc_alloc<constexpr_fundef> ();
1042 **slot = value;
1045 /* FUN is a non-constexpr (or, with -Wno-invalid-constexpr, a constexpr
1046 function called in a context that requires a constant expression).
1047 If it comes from a constexpr template, explain why the instantiation
1048 isn't constexpr. Otherwise, explain why the function cannot be used
1049 in a constexpr context. */
1051 void
1052 explain_invalid_constexpr_fn (tree fun)
1054 static hash_set<tree> *diagnosed;
1055 tree body;
1056 /* In C++23, a function marked 'constexpr' may not actually be a constant
1057 expression. We haven't diagnosed the problem yet: -Winvalid-constexpr
1058 wasn't enabled. The function was called, so diagnose why it cannot be
1059 used in a constant expression. */
1060 if (warn_invalid_constexpr == 0 && DECL_DECLARED_CONSTEXPR_P (fun))
1061 /* Go on. */;
1062 /* Only diagnose defaulted functions, lambdas, or instantiations. */
1063 else if (!DECL_DEFAULTED_FN (fun)
1064 && !LAMBDA_TYPE_P (CP_DECL_CONTEXT (fun))
1065 && !is_instantiation_of_constexpr (fun))
1067 inform (DECL_SOURCE_LOCATION (fun), "%qD declared here", fun);
1068 return;
1070 if (diagnosed == NULL)
1071 diagnosed = new hash_set<tree>;
1072 if (diagnosed->add (fun))
1073 /* Already explained. */
1074 return;
1076 iloc_sentinel ils = input_location;
1077 if (!lambda_static_thunk_p (fun))
1079 /* Diagnostics should completely ignore the static thunk, so leave
1080 input_location set to our caller's location. */
1081 input_location = DECL_SOURCE_LOCATION (fun);
1082 inform (input_location,
1083 "%qD is not usable as a %<constexpr%> function because:", fun);
1085 /* First check the declaration. */
1086 if (is_valid_constexpr_fn (fun, true))
1088 /* Then if it's OK, the body. */
1089 if (!DECL_DECLARED_CONSTEXPR_P (fun)
1090 && DECL_DEFAULTED_FN (fun))
1091 explain_implicit_non_constexpr (fun);
1092 else
1094 if (constexpr_fundef *fd = retrieve_constexpr_fundef (fun))
1095 body = fd->body;
1096 else
1097 body = DECL_SAVED_TREE (fun);
1098 body = massage_constexpr_body (fun, body);
1099 require_potential_rvalue_constant_expression (body);
1100 if (DECL_CONSTRUCTOR_P (fun))
1102 cx_check_missing_mem_inits (DECL_CONTEXT (fun), body, true);
1103 if (cxx_dialect > cxx11)
1105 /* Also check the body, not just the ctor-initializer. */
1106 body = DECL_SAVED_TREE (fun);
1107 require_potential_rvalue_constant_expression (body);
1114 /* Objects of this type represent calls to constexpr functions
1115 along with the bindings of parameters to their arguments, for
1116 the purpose of compile time evaluation. */
1118 struct GTY((for_user)) constexpr_call {
1119 /* Description of the constexpr function definition. */
1120 constexpr_fundef *fundef;
1121 /* Parameter bindings environment. A TREE_VEC of arguments. */
1122 tree bindings;
1123 /* Result of the call.
1124 NULL means the call is being evaluated.
1125 error_mark_node means that the evaluation was erroneous;
1126 otherwise, the actuall value of the call. */
1127 tree result;
1128 /* The hash of this call; we remember it here to avoid having to
1129 recalculate it when expanding the hash table. */
1130 hashval_t hash;
1131 /* The value of constexpr_ctx::manifestly_const_eval. */
1132 enum mce_value manifestly_const_eval;
1135 struct constexpr_call_hasher : ggc_ptr_hash<constexpr_call>
1137 static hashval_t hash (constexpr_call *);
1138 static bool equal (constexpr_call *, constexpr_call *);
1141 enum constexpr_switch_state {
1142 /* Used when processing a switch for the first time by cxx_eval_switch_expr
1143 and default: label for that switch has not been seen yet. */
1144 css_default_not_seen,
1145 /* Used when processing a switch for the first time by cxx_eval_switch_expr
1146 and default: label for that switch has been seen already. */
1147 css_default_seen,
1148 /* Used when processing a switch for the second time by
1149 cxx_eval_switch_expr, where default: label should match. */
1150 css_default_processing
1153 /* The constexpr expansion context part which needs one instance per
1154 cxx_eval_outermost_constant_expr invocation. VALUES is a map of values of
1155 variables initialized within the expression. */
1157 class constexpr_global_ctx {
1158 /* Values for any temporaries or local variables within the
1159 constant-expression. Objects outside their lifetime have
1160 value 'void_node'. */
1161 hash_map<tree,tree> values;
1162 public:
1163 /* Number of cxx_eval_constant_expression calls (except skipped ones,
1164 on simple constants or location wrappers) encountered during current
1165 cxx_eval_outermost_constant_expr call. */
1166 HOST_WIDE_INT constexpr_ops_count;
1167 /* Heap VAR_DECLs created during the evaluation of the outermost constant
1168 expression. */
1169 auto_vec<tree, 16> heap_vars;
1170 /* Cleanups that need to be evaluated at the end of CLEANUP_POINT_EXPR. */
1171 vec<tree> *cleanups;
1172 /* If non-null, only allow modification of existing values of the variables
1173 in this set. Set by modifiable_tracker, below. */
1174 hash_set<tree> *modifiable;
1175 /* Number of heap VAR_DECL deallocations. */
1176 unsigned heap_dealloc_count;
1177 /* Constructor. */
1178 constexpr_global_ctx ()
1179 : constexpr_ops_count (0), cleanups (NULL), modifiable (nullptr),
1180 heap_dealloc_count (0) {}
1182 bool is_outside_lifetime (tree t)
1184 if (tree *p = values.get (t))
1185 if (*p == void_node)
1186 return true;
1187 return false;
1189 tree get_value (tree t)
1191 if (tree *p = values.get (t))
1192 if (*p != void_node)
1193 return *p;
1194 return NULL_TREE;
1196 tree *get_value_ptr (tree t)
1198 if (modifiable && !modifiable->contains (t))
1199 return nullptr;
1200 if (tree *p = values.get (t))
1201 if (*p != void_node)
1202 return p;
1203 return nullptr;
1205 void put_value (tree t, tree v)
1207 bool already_in_map = values.put (t, v);
1208 if (!already_in_map && modifiable)
1209 modifiable->add (t);
1211 void remove_value (tree t)
1213 if (DECL_P (t))
1214 values.put (t, void_node);
1215 else
1216 values.remove (t);
1220 /* Helper class for constexpr_global_ctx. In some cases we want to avoid
1221 side-effects from evaluation of a particular subexpression of a
1222 constant-expression. In such cases we use modifiable_tracker to prevent
1223 modification of variables created outside of that subexpression.
1225 ??? We could change the hash_set to a hash_map, allow and track external
1226 modifications, and roll them back in the destructor. It's not clear to me
1227 that this would be worthwhile. */
1229 class modifiable_tracker
1231 hash_set<tree> set;
1232 constexpr_global_ctx *global;
1233 public:
1234 modifiable_tracker (constexpr_global_ctx *g): global(g)
1236 global->modifiable = &set;
1238 ~modifiable_tracker ()
1240 for (tree t: set)
1241 global->remove_value (t);
1242 global->modifiable = nullptr;
1246 /* The constexpr expansion context. CALL is the current function
1247 expansion, CTOR is the current aggregate initializer, OBJECT is the
1248 object being initialized by CTOR, either a VAR_DECL or a _REF. */
1250 struct constexpr_ctx {
1251 /* The part of the context that needs to be unique to the whole
1252 cxx_eval_outermost_constant_expr invocation. */
1253 constexpr_global_ctx *global;
1254 /* The innermost call we're evaluating. */
1255 constexpr_call *call;
1256 /* SAVE_EXPRs and TARGET_EXPR_SLOT vars of TARGET_EXPRs that we've seen
1257 within the current LOOP_EXPR. NULL if we aren't inside a loop. */
1258 vec<tree> *save_exprs;
1259 /* The CONSTRUCTOR we're currently building up for an aggregate
1260 initializer. */
1261 tree ctor;
1262 /* The object we're building the CONSTRUCTOR for. */
1263 tree object;
1264 /* If inside SWITCH_EXPR. */
1265 constexpr_switch_state *css_state;
1266 /* The aggregate initialization context inside which this one is nested. This
1267 is used by lookup_placeholder to resolve PLACEHOLDER_EXPRs. */
1268 const constexpr_ctx *parent;
1270 /* Whether we should error on a non-constant expression or fail quietly.
1271 This flag needs to be here, but some of the others could move to global
1272 if they get larger than a word. */
1273 bool quiet;
1274 /* Whether we are strictly conforming to constant expression rules or
1275 trying harder to get a constant value. */
1276 bool strict;
1277 /* Whether __builtin_is_constant_evaluated () should be true. */
1278 mce_value manifestly_const_eval;
1281 /* This internal flag controls whether we should avoid doing anything during
1282 constexpr evaluation that would cause extra DECL_UID generation, such as
1283 template instantiation and function body copying. */
1285 static bool uid_sensitive_constexpr_evaluation_value;
1287 /* An internal counter that keeps track of the number of times
1288 uid_sensitive_constexpr_evaluation_p returned true. */
1290 static unsigned uid_sensitive_constexpr_evaluation_true_counter;
1292 /* The accessor for uid_sensitive_constexpr_evaluation_value which also
1293 increments the corresponding counter. */
1295 static bool
1296 uid_sensitive_constexpr_evaluation_p ()
1298 if (uid_sensitive_constexpr_evaluation_value)
1300 ++uid_sensitive_constexpr_evaluation_true_counter;
1301 return true;
1303 else
1304 return false;
1307 /* The default constructor for uid_sensitive_constexpr_evaluation_sentinel
1308 enables the internal flag for uid_sensitive_constexpr_evaluation_p
1309 during the lifetime of the sentinel object. Upon its destruction, the
1310 previous value of uid_sensitive_constexpr_evaluation_p is restored. */
1312 uid_sensitive_constexpr_evaluation_sentinel
1313 ::uid_sensitive_constexpr_evaluation_sentinel ()
1314 : ovr (uid_sensitive_constexpr_evaluation_value, true)
1318 /* The default constructor for uid_sensitive_constexpr_evaluation_checker
1319 records the current number of times that uid_sensitive_constexpr_evaluation_p
1320 has been called and returned true. */
1322 uid_sensitive_constexpr_evaluation_checker
1323 ::uid_sensitive_constexpr_evaluation_checker ()
1324 : saved_counter (uid_sensitive_constexpr_evaluation_true_counter)
1328 /* Returns true iff uid_sensitive_constexpr_evaluation_p is true, and
1329 some constexpr evaluation was restricted due to u_s_c_e_p being called
1330 and returning true during the lifetime of this checker object. */
1332 bool
1333 uid_sensitive_constexpr_evaluation_checker::evaluation_restricted_p () const
1335 return (uid_sensitive_constexpr_evaluation_value
1336 && saved_counter != uid_sensitive_constexpr_evaluation_true_counter);
1340 /* A table of all constexpr calls that have been evaluated by the
1341 compiler in this translation unit. */
1343 static GTY (()) hash_table<constexpr_call_hasher> *constexpr_call_table;
1345 /* Compute a hash value for a constexpr call representation. */
1347 inline hashval_t
1348 constexpr_call_hasher::hash (constexpr_call *info)
1350 return info->hash;
1353 /* Return true if the objects pointed to by P and Q represent calls
1354 to the same constexpr function with the same arguments.
1355 Otherwise, return false. */
1357 bool
1358 constexpr_call_hasher::equal (constexpr_call *lhs, constexpr_call *rhs)
1360 if (lhs == rhs)
1361 return true;
1362 if (lhs->hash != rhs->hash)
1363 return false;
1364 if (lhs->manifestly_const_eval != rhs->manifestly_const_eval)
1365 return false;
1366 if (!constexpr_fundef_hasher::equal (lhs->fundef, rhs->fundef))
1367 return false;
1368 return cp_tree_equal (lhs->bindings, rhs->bindings);
1371 /* Initialize the constexpr call table, if needed. */
1373 static void
1374 maybe_initialize_constexpr_call_table (void)
1376 if (constexpr_call_table == NULL)
1377 constexpr_call_table = hash_table<constexpr_call_hasher>::create_ggc (101);
1380 /* During constexpr CALL_EXPR evaluation, to avoid issues with sharing when
1381 a function happens to get called recursively, we unshare the callee
1382 function's body and evaluate this unshared copy instead of evaluating the
1383 original body.
1385 FUNDEF_COPIES_TABLE is a per-function freelist of these unshared function
1386 copies. The underlying data structure of FUNDEF_COPIES_TABLE is a hash_map
1387 that's keyed off of the original FUNCTION_DECL and whose value is a
1388 TREE_LIST of this function's unused copies awaiting reuse.
1390 This is not GC-deletable to avoid GC affecting UID generation. */
1392 static GTY(()) decl_tree_map *fundef_copies_table;
1394 /* Reuse a copy or create a new unshared copy of the function FUN.
1395 Return this copy. We use a TREE_LIST whose PURPOSE is body, VALUE
1396 is parms, TYPE is result. */
1398 static tree
1399 get_fundef_copy (constexpr_fundef *fundef)
1401 tree copy;
1402 bool existed;
1403 tree *slot = &(hash_map_safe_get_or_insert<hm_ggc>
1404 (fundef_copies_table, fundef->decl, &existed, 127));
1406 if (!existed)
1408 /* There is no cached function available, or in use. We can use
1409 the function directly. That the slot is now created records
1410 that this function is now in use. */
1411 copy = build_tree_list (fundef->body, fundef->parms);
1412 TREE_TYPE (copy) = fundef->result;
1414 else if (*slot == NULL_TREE)
1416 if (uid_sensitive_constexpr_evaluation_p ())
1417 return NULL_TREE;
1419 /* We've already used the function itself, so make a copy. */
1420 copy = build_tree_list (NULL, NULL);
1421 tree saved_body = DECL_SAVED_TREE (fundef->decl);
1422 tree saved_parms = DECL_ARGUMENTS (fundef->decl);
1423 tree saved_result = DECL_RESULT (fundef->decl);
1424 tree saved_fn = current_function_decl;
1425 DECL_SAVED_TREE (fundef->decl) = fundef->body;
1426 DECL_ARGUMENTS (fundef->decl) = fundef->parms;
1427 DECL_RESULT (fundef->decl) = fundef->result;
1428 current_function_decl = fundef->decl;
1429 TREE_PURPOSE (copy) = copy_fn (fundef->decl, TREE_VALUE (copy),
1430 TREE_TYPE (copy));
1431 current_function_decl = saved_fn;
1432 DECL_RESULT (fundef->decl) = saved_result;
1433 DECL_ARGUMENTS (fundef->decl) = saved_parms;
1434 DECL_SAVED_TREE (fundef->decl) = saved_body;
1436 else
1438 /* We have a cached function available. */
1439 copy = *slot;
1440 *slot = TREE_CHAIN (copy);
1443 return copy;
1446 /* Save the copy COPY of function FUN for later reuse by
1447 get_fundef_copy(). By construction, there will always be an entry
1448 to find. */
1450 static void
1451 save_fundef_copy (tree fun, tree copy)
1453 tree *slot = fundef_copies_table->get (fun);
1454 TREE_CHAIN (copy) = *slot;
1455 *slot = copy;
1458 /* Whether our evaluation wants a prvalue (e.g. CONSTRUCTOR or _CST),
1459 a glvalue (e.g. VAR_DECL or _REF), or nothing. */
1461 enum value_cat {
1462 vc_prvalue = 0,
1463 vc_glvalue = 1,
1464 vc_discard = 2
1467 static tree cxx_eval_constant_expression (const constexpr_ctx *, tree,
1468 value_cat, bool *, bool *, tree * = NULL);
1469 static tree cxx_eval_bare_aggregate (const constexpr_ctx *, tree,
1470 value_cat, bool *, bool *);
1471 static tree cxx_fold_indirect_ref (const constexpr_ctx *, location_t, tree, tree,
1472 bool * = NULL);
1473 static tree find_heap_var_refs (tree *, int *, void *);
1475 /* Attempt to evaluate T which represents a call to a builtin function.
1476 We assume here that all builtin functions evaluate to scalar types
1477 represented by _CST nodes. */
1479 static tree
1480 cxx_eval_builtin_function_call (const constexpr_ctx *ctx, tree t, tree fun,
1481 value_cat lval,
1482 bool *non_constant_p, bool *overflow_p)
1484 const int nargs = call_expr_nargs (t);
1485 tree *args = (tree *) alloca (nargs * sizeof (tree));
1486 tree new_call;
1487 int i;
1489 /* Don't fold __builtin_constant_p within a constexpr function. */
1490 bool bi_const_p = DECL_IS_BUILTIN_CONSTANT_P (fun);
1492 /* If we aren't requiring a constant expression, defer __builtin_constant_p
1493 in a constexpr function until we have values for the parameters. */
1494 if (bi_const_p
1495 && ctx->manifestly_const_eval != mce_true
1496 && current_function_decl
1497 && DECL_DECLARED_CONSTEXPR_P (current_function_decl))
1499 *non_constant_p = true;
1500 return t;
1503 /* For __builtin_is_constant_evaluated, defer it if not
1504 ctx->manifestly_const_eval (as sometimes we try to constant evaluate
1505 without manifestly_const_eval even expressions or parts thereof which
1506 will later be manifestly const_eval evaluated), otherwise fold it to
1507 true. */
1508 if (fndecl_built_in_p (fun, CP_BUILT_IN_IS_CONSTANT_EVALUATED,
1509 BUILT_IN_FRONTEND))
1511 if (ctx->manifestly_const_eval == mce_unknown)
1513 *non_constant_p = true;
1514 return t;
1516 return constant_boolean_node (ctx->manifestly_const_eval == mce_true,
1517 boolean_type_node);
1520 if (fndecl_built_in_p (fun, CP_BUILT_IN_SOURCE_LOCATION, BUILT_IN_FRONTEND))
1522 temp_override<tree> ovr (current_function_decl);
1523 if (ctx->call && ctx->call->fundef)
1524 current_function_decl = ctx->call->fundef->decl;
1525 return fold_builtin_source_location (t);
1528 int strops = 0;
1529 int strret = 0;
1530 if (fndecl_built_in_p (fun, BUILT_IN_NORMAL))
1531 switch (DECL_FUNCTION_CODE (fun))
1533 case BUILT_IN_STRLEN:
1534 case BUILT_IN_STRNLEN:
1535 strops = 1;
1536 break;
1537 case BUILT_IN_MEMCHR:
1538 case BUILT_IN_STRCHR:
1539 case BUILT_IN_STRRCHR:
1540 strops = 1;
1541 strret = 1;
1542 break;
1543 case BUILT_IN_MEMCMP:
1544 case BUILT_IN_STRCMP:
1545 strops = 2;
1546 break;
1547 case BUILT_IN_STRSTR:
1548 strops = 2;
1549 strret = 1;
1550 break;
1551 case BUILT_IN_ASAN_POINTER_COMPARE:
1552 case BUILT_IN_ASAN_POINTER_SUBTRACT:
1553 /* These builtins shall be ignored during constant expression
1554 evaluation. */
1555 return void_node;
1556 case BUILT_IN_UNREACHABLE:
1557 case BUILT_IN_TRAP:
1558 if (!*non_constant_p && !ctx->quiet)
1560 /* Do not allow__builtin_unreachable in constexpr function.
1561 The __builtin_unreachable call with BUILTINS_LOCATION
1562 comes from cp_maybe_instrument_return. */
1563 if (EXPR_LOCATION (t) == BUILTINS_LOCATION)
1564 error ("%<constexpr%> call flows off the end of the function");
1565 else
1566 error ("%q+E is not a constant expression", t);
1568 *non_constant_p = true;
1569 return t;
1570 default:
1571 break;
1574 /* Be permissive for arguments to built-ins; __builtin_constant_p should
1575 return constant false for a non-constant argument. */
1576 constexpr_ctx new_ctx = *ctx;
1577 new_ctx.quiet = true;
1578 for (i = 0; i < nargs; ++i)
1580 tree arg = CALL_EXPR_ARG (t, i);
1581 tree oarg = arg;
1583 /* To handle string built-ins we need to pass ADDR_EXPR<STRING_CST> since
1584 expand_builtin doesn't know how to look in the values table. */
1585 bool strop = i < strops;
1586 if (strop)
1588 STRIP_NOPS (arg);
1589 if (TREE_CODE (arg) == ADDR_EXPR)
1590 arg = TREE_OPERAND (arg, 0);
1591 else
1592 strop = false;
1595 /* If builtin_valid_in_constant_expr_p is true,
1596 potential_constant_expression_1 has not recursed into the arguments
1597 of the builtin, verify it here. */
1598 if (!builtin_valid_in_constant_expr_p (fun)
1599 || potential_constant_expression (arg))
1601 bool dummy1 = false, dummy2 = false;
1602 arg = cxx_eval_constant_expression (&new_ctx, arg, vc_prvalue,
1603 &dummy1, &dummy2);
1606 if (bi_const_p)
1607 /* For __builtin_constant_p, fold all expressions with constant values
1608 even if they aren't C++ constant-expressions. */
1609 arg = cp_fold_rvalue (arg);
1610 else if (strop)
1612 if (TREE_CODE (arg) == CONSTRUCTOR)
1613 arg = braced_lists_to_strings (TREE_TYPE (arg), arg);
1614 if (TREE_CODE (arg) == STRING_CST)
1615 arg = build_address (arg);
1616 else
1617 arg = oarg;
1620 args[i] = arg;
1623 bool save_ffbcp = force_folding_builtin_constant_p;
1624 force_folding_builtin_constant_p |= ctx->manifestly_const_eval == mce_true;
1625 tree save_cur_fn = current_function_decl;
1626 /* Return name of ctx->call->fundef->decl for __builtin_FUNCTION (). */
1627 if (fndecl_built_in_p (fun, BUILT_IN_FUNCTION)
1628 && ctx->call
1629 && ctx->call->fundef)
1630 current_function_decl = ctx->call->fundef->decl;
1631 if (fndecl_built_in_p (fun,
1632 CP_BUILT_IN_IS_POINTER_INTERCONVERTIBLE_WITH_CLASS,
1633 BUILT_IN_FRONTEND))
1635 location_t loc = EXPR_LOCATION (t);
1636 if (nargs >= 1)
1637 VERIFY_CONSTANT (args[0]);
1638 new_call
1639 = fold_builtin_is_pointer_inverconvertible_with_class (loc, nargs,
1640 args);
1642 else if (fndecl_built_in_p (fun,
1643 CP_BUILT_IN_IS_CORRESPONDING_MEMBER,
1644 BUILT_IN_FRONTEND))
1646 location_t loc = EXPR_LOCATION (t);
1647 if (nargs >= 2)
1649 VERIFY_CONSTANT (args[0]);
1650 VERIFY_CONSTANT (args[1]);
1652 new_call = fold_builtin_is_corresponding_member (loc, nargs, args);
1654 else
1655 new_call = fold_builtin_call_array (EXPR_LOCATION (t), TREE_TYPE (t),
1656 CALL_EXPR_FN (t), nargs, args);
1657 current_function_decl = save_cur_fn;
1658 force_folding_builtin_constant_p = save_ffbcp;
1659 if (new_call == NULL)
1661 if (!*non_constant_p && !ctx->quiet)
1663 new_call = build_call_array_loc (EXPR_LOCATION (t), TREE_TYPE (t),
1664 CALL_EXPR_FN (t), nargs, args);
1665 error ("%q+E is not a constant expression", new_call);
1667 *non_constant_p = true;
1668 return t;
1671 if (!potential_constant_expression (new_call))
1673 if (!*non_constant_p && !ctx->quiet)
1674 error ("%q+E is not a constant expression", new_call);
1675 *non_constant_p = true;
1676 return t;
1679 if (strret)
1681 /* memchr returns a pointer into the first argument, but we replaced the
1682 argument above with a STRING_CST; put it back it now. */
1683 tree op = CALL_EXPR_ARG (t, strret-1);
1684 STRIP_NOPS (new_call);
1685 if (TREE_CODE (new_call) == POINTER_PLUS_EXPR)
1686 TREE_OPERAND (new_call, 0) = op;
1687 else if (TREE_CODE (new_call) == ADDR_EXPR)
1688 new_call = op;
1691 return cxx_eval_constant_expression (&new_ctx, new_call, lval,
1692 non_constant_p, overflow_p);
1695 /* TEMP is the constant value of a temporary object of type TYPE. Adjust
1696 the type of the value to match. */
1698 static tree
1699 adjust_temp_type (tree type, tree temp)
1701 if (same_type_p (TREE_TYPE (temp), type))
1702 return temp;
1703 /* Avoid wrapping an aggregate value in a NOP_EXPR. */
1704 if (TREE_CODE (temp) == CONSTRUCTOR)
1706 /* build_constructor wouldn't retain various CONSTRUCTOR flags. */
1707 tree t = copy_node (temp);
1708 TREE_TYPE (t) = type;
1709 return t;
1711 if (TREE_CODE (temp) == EMPTY_CLASS_EXPR)
1712 return build0 (EMPTY_CLASS_EXPR, type);
1713 gcc_assert (scalarish_type_p (type));
1714 /* Now we know we're dealing with a scalar, and a prvalue of non-class
1715 type is cv-unqualified. */
1716 return cp_fold_convert (cv_unqualified (type), temp);
1719 /* If T is a CONSTRUCTOR, return an unshared copy of T and any
1720 sub-CONSTRUCTORs. Otherwise return T.
1722 We use this whenever we initialize an object as a whole, whether it's a
1723 parameter, a local variable, or a subobject, so that subsequent
1724 modifications don't affect other places where it was used. */
1726 tree
1727 unshare_constructor (tree t MEM_STAT_DECL)
1729 if (!t || TREE_CODE (t) != CONSTRUCTOR)
1730 return t;
1731 auto_vec <tree*, 4> ptrs;
1732 ptrs.safe_push (&t);
1733 while (!ptrs.is_empty ())
1735 tree *p = ptrs.pop ();
1736 tree n = copy_node (*p PASS_MEM_STAT);
1737 CONSTRUCTOR_ELTS (n) = vec_safe_copy (CONSTRUCTOR_ELTS (*p) PASS_MEM_STAT);
1738 *p = n;
1739 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (n);
1740 constructor_elt *ce;
1741 for (HOST_WIDE_INT i = 0; vec_safe_iterate (v, i, &ce); ++i)
1742 if (ce->value && TREE_CODE (ce->value) == CONSTRUCTOR)
1743 ptrs.safe_push (&ce->value);
1745 return t;
1748 /* If T is a CONSTRUCTOR, ggc_free T and any sub-CONSTRUCTORs. */
1750 static void
1751 free_constructor (tree t)
1753 if (!t || TREE_CODE (t) != CONSTRUCTOR)
1754 return;
1755 releasing_vec ctors;
1756 vec_safe_push (ctors, t);
1757 while (!ctors->is_empty ())
1759 tree c = ctors->pop ();
1760 if (vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (c))
1762 constructor_elt *ce;
1763 for (HOST_WIDE_INT i = 0; vec_safe_iterate (elts, i, &ce); ++i)
1764 if (ce->value && TREE_CODE (ce->value) == CONSTRUCTOR)
1765 vec_safe_push (ctors, ce->value);
1766 ggc_free (elts);
1768 ggc_free (c);
1772 /* Helper function of cxx_bind_parameters_in_call. Return non-NULL
1773 if *TP is address of a static variable (or part of it) currently being
1774 constructed or of a heap artificial variable. */
1776 static tree
1777 addr_of_non_const_var (tree *tp, int *walk_subtrees, void *data)
1779 if (TREE_CODE (*tp) == ADDR_EXPR)
1780 if (tree var = get_base_address (TREE_OPERAND (*tp, 0)))
1781 if (VAR_P (var) && TREE_STATIC (var))
1783 if (DECL_NAME (var) == heap_uninit_identifier
1784 || DECL_NAME (var) == heap_identifier
1785 || DECL_NAME (var) == heap_vec_uninit_identifier
1786 || DECL_NAME (var) == heap_vec_identifier)
1787 return var;
1789 constexpr_global_ctx *global = (constexpr_global_ctx *) data;
1790 if (global->get_value (var))
1791 return var;
1793 if (TYPE_P (*tp))
1794 *walk_subtrees = false;
1795 return NULL_TREE;
1798 /* Subroutine of cxx_eval_call_expression.
1799 We are processing a call expression (either CALL_EXPR or
1800 AGGR_INIT_EXPR) in the context of CTX. Evaluate
1801 all arguments and bind their values to correspondings
1802 parameters, making up the NEW_CALL context. */
1804 static tree
1805 cxx_bind_parameters_in_call (const constexpr_ctx *ctx, tree t, tree fun,
1806 bool *non_constant_p, bool *overflow_p,
1807 bool *non_constant_args)
1809 const int nargs = call_expr_nargs (t);
1810 tree parms = DECL_ARGUMENTS (fun);
1811 int i;
1812 /* We don't record ellipsis args below. */
1813 int nparms = list_length (parms);
1814 int nbinds = nargs < nparms ? nargs : nparms;
1815 tree binds = make_tree_vec (nbinds);
1816 for (i = 0; i < nargs; ++i)
1818 tree x, arg;
1819 tree type = parms ? TREE_TYPE (parms) : void_type_node;
1820 if (parms && DECL_BY_REFERENCE (parms))
1821 type = TREE_TYPE (type);
1822 x = get_nth_callarg (t, i);
1823 /* For member function, the first argument is a pointer to the implied
1824 object. For a constructor, it might still be a dummy object, in
1825 which case we get the real argument from ctx. */
1826 if (i == 0 && DECL_CONSTRUCTOR_P (fun)
1827 && is_dummy_object (x))
1829 x = ctx->object;
1830 x = build_address (x);
1832 if (TREE_ADDRESSABLE (type))
1833 /* Undo convert_for_arg_passing work here. */
1834 x = convert_from_reference (x);
1835 /* Normally we would strip a TARGET_EXPR in an initialization context
1836 such as this, but here we do the elision differently: we keep the
1837 TARGET_EXPR, and use its CONSTRUCTOR as the value of the parm. */
1838 arg = cxx_eval_constant_expression (ctx, x, vc_prvalue,
1839 non_constant_p, overflow_p);
1840 /* Don't VERIFY_CONSTANT here. */
1841 if (*non_constant_p && ctx->quiet)
1842 break;
1843 /* Just discard ellipsis args after checking their constantitude. */
1844 if (!parms)
1845 continue;
1847 if (!*non_constant_p)
1849 /* Make sure the binding has the same type as the parm. But
1850 only for constant args. */
1851 if (!TYPE_REF_P (type))
1852 arg = adjust_temp_type (type, arg);
1853 if (!TREE_CONSTANT (arg))
1854 *non_constant_args = true;
1855 else if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
1856 /* The destructor needs to see any modifications the callee makes
1857 to the argument. */
1858 *non_constant_args = true;
1859 /* If arg is or contains address of a heap artificial variable or
1860 of a static variable being constructed, avoid caching the
1861 function call, as those variables might be modified by the
1862 function, or might be modified by the callers in between
1863 the cached function and just read by the function. */
1864 else if (!*non_constant_args
1865 && cp_walk_tree (&arg, addr_of_non_const_var, ctx->global,
1866 NULL))
1867 *non_constant_args = true;
1869 /* For virtual calls, adjust the this argument, so that it is
1870 the object on which the method is called, rather than
1871 one of its bases. */
1872 if (i == 0 && DECL_VIRTUAL_P (fun))
1874 tree addr = arg;
1875 STRIP_NOPS (addr);
1876 if (TREE_CODE (addr) == ADDR_EXPR)
1878 tree obj = TREE_OPERAND (addr, 0);
1879 while (TREE_CODE (obj) == COMPONENT_REF
1880 && DECL_FIELD_IS_BASE (TREE_OPERAND (obj, 1))
1881 && !same_type_ignoring_top_level_qualifiers_p
1882 (TREE_TYPE (obj), DECL_CONTEXT (fun)))
1883 obj = TREE_OPERAND (obj, 0);
1884 if (obj != TREE_OPERAND (addr, 0))
1885 arg = build_fold_addr_expr_with_type (obj,
1886 TREE_TYPE (arg));
1889 TREE_VEC_ELT (binds, i) = arg;
1891 parms = TREE_CHAIN (parms);
1894 return binds;
1897 /* Variables and functions to manage constexpr call expansion context.
1898 These do not need to be marked for PCH or GC. */
1900 /* FIXME remember and print actual constant arguments. */
1901 static vec<tree> call_stack;
1902 static int call_stack_tick;
1903 static int last_cx_error_tick;
1905 static int
1906 push_cx_call_context (tree call)
1908 ++call_stack_tick;
1909 if (!EXPR_HAS_LOCATION (call))
1910 SET_EXPR_LOCATION (call, input_location);
1911 call_stack.safe_push (call);
1912 int len = call_stack.length ();
1913 if (len > max_constexpr_depth)
1914 return false;
1915 return len;
1918 static void
1919 pop_cx_call_context (void)
1921 ++call_stack_tick;
1922 call_stack.pop ();
1925 vec<tree>
1926 cx_error_context (void)
1928 vec<tree> r = vNULL;
1929 if (call_stack_tick != last_cx_error_tick
1930 && !call_stack.is_empty ())
1931 r = call_stack;
1932 last_cx_error_tick = call_stack_tick;
1933 return r;
1936 /* E is an operand of a failed assertion, fold it either with or without
1937 constexpr context. */
1939 static tree
1940 fold_operand (tree e, const constexpr_ctx *ctx)
1942 if (ctx)
1944 bool new_non_constant_p = false, new_overflow_p = false;
1945 e = cxx_eval_constant_expression (ctx, e, vc_prvalue,
1946 &new_non_constant_p,
1947 &new_overflow_p);
1949 else
1950 e = fold_non_dependent_expr (e, tf_none, /*manifestly_const_eval=*/true);
1951 return e;
1954 /* If we have a condition in conjunctive normal form (CNF), find the first
1955 failing clause. In other words, given an expression like
1957 true && true && false && true && false
1959 return the first 'false'. EXPR is the expression. */
1961 static tree
1962 find_failing_clause_r (const constexpr_ctx *ctx, tree expr)
1964 if (TREE_CODE (expr) == TRUTH_ANDIF_EXPR)
1966 /* First check the left side... */
1967 tree e = find_failing_clause_r (ctx, TREE_OPERAND (expr, 0));
1968 if (e == NULL_TREE)
1969 /* ...if we didn't find a false clause, check the right side. */
1970 e = find_failing_clause_r (ctx, TREE_OPERAND (expr, 1));
1971 return e;
1973 tree e = contextual_conv_bool (expr, tf_none);
1974 e = fold_operand (e, ctx);
1975 if (integer_zerop (e))
1976 /* This is the failing clause. */
1977 return expr;
1978 return NULL_TREE;
1981 /* Wrapper for find_failing_clause_r. */
1983 tree
1984 find_failing_clause (const constexpr_ctx *ctx, tree expr)
1986 if (TREE_CODE (expr) == TRUTH_ANDIF_EXPR)
1987 if (tree e = find_failing_clause_r (ctx, expr))
1988 expr = e;
1989 return expr;
1992 /* Emit additional diagnostics for failing condition BAD.
1993 Used by finish_static_assert and IFN_ASSUME constexpr diagnostics.
1994 If SHOW_EXPR_P is true, print the condition (because it was
1995 instantiation-dependent). */
1997 void
1998 diagnose_failing_condition (tree bad, location_t cloc, bool show_expr_p,
1999 const constexpr_ctx *ctx /* = nullptr */)
2001 /* Nobody wants to see the artificial (bool) cast. */
2002 bad = tree_strip_nop_conversions (bad);
2003 if (TREE_CODE (bad) == CLEANUP_POINT_EXPR)
2004 bad = TREE_OPERAND (bad, 0);
2006 /* Actually explain the failure if this is a concept check or a
2007 requires-expression. */
2008 if (concept_check_p (bad) || TREE_CODE (bad) == REQUIRES_EXPR)
2009 diagnose_constraints (cloc, bad, NULL_TREE);
2010 else if (COMPARISON_CLASS_P (bad)
2011 && ARITHMETIC_TYPE_P (TREE_TYPE (TREE_OPERAND (bad, 0))))
2013 tree op0 = fold_operand (TREE_OPERAND (bad, 0), ctx);
2014 tree op1 = fold_operand (TREE_OPERAND (bad, 1), ctx);
2015 tree cond = build2 (TREE_CODE (bad), boolean_type_node, op0, op1);
2016 inform (cloc, "the comparison reduces to %qE", cond);
2018 else if (show_expr_p)
2019 inform (cloc, "%qE evaluates to false", bad);
2022 /* Process an assert/assume of ORIG_ARG. If it's not supposed to be evaluated,
2023 do it without changing the current evaluation state. If it evaluates to
2024 false, complain and return false; otherwise, return true. */
2026 static bool
2027 cxx_eval_assert (const constexpr_ctx *ctx, tree arg, const char *msg,
2028 location_t loc, bool evaluated,
2029 bool *non_constant_p, bool *overflow_p)
2031 if (*non_constant_p)
2032 return true;
2034 tree eval;
2035 if (!evaluated)
2037 if (!potential_rvalue_constant_expression (arg))
2038 return true;
2040 constexpr_ctx new_ctx = *ctx;
2041 new_ctx.quiet = true;
2042 bool new_non_constant_p = false, new_overflow_p = false;
2043 /* Avoid modification of existing values. */
2044 modifiable_tracker ms (new_ctx.global);
2045 eval = cxx_eval_constant_expression (&new_ctx, arg, vc_prvalue,
2046 &new_non_constant_p,
2047 &new_overflow_p);
2049 else
2050 eval = cxx_eval_constant_expression (ctx, arg, vc_prvalue,
2051 non_constant_p,
2052 overflow_p);
2053 if (!*non_constant_p && integer_zerop (eval))
2055 if (!ctx->quiet)
2057 /* See if we can find which clause was failing
2058 (for logical AND). */
2059 tree bad = find_failing_clause (ctx, arg);
2060 /* If not, or its location is unusable, fall back to the
2061 previous location. */
2062 location_t cloc = cp_expr_loc_or_loc (bad, loc);
2064 /* Report the error. */
2065 auto_diagnostic_group d;
2066 error_at (cloc, msg);
2067 diagnose_failing_condition (bad, cloc, true, ctx);
2068 return bad;
2070 *non_constant_p = true;
2071 return false;
2074 return true;
2077 /* Evaluate a call T to a GCC internal function when possible and return
2078 the evaluated result or, under the control of CTX, give an error, set
2079 NON_CONSTANT_P, and return the unevaluated call T otherwise. */
2081 static tree
2082 cxx_eval_internal_function (const constexpr_ctx *ctx, tree t,
2083 value_cat lval,
2084 bool *non_constant_p, bool *overflow_p)
2086 enum tree_code opcode = ERROR_MARK;
2088 switch (CALL_EXPR_IFN (t))
2090 case IFN_UBSAN_NULL:
2091 case IFN_UBSAN_BOUNDS:
2092 case IFN_UBSAN_VPTR:
2093 case IFN_FALLTHROUGH:
2094 return void_node;
2096 case IFN_ASSUME:
2097 if (!cxx_eval_assert (ctx, CALL_EXPR_ARG (t, 0),
2098 G_("failed %<assume%> attribute assumption"),
2099 EXPR_LOCATION (t), /*eval*/false,
2100 non_constant_p, overflow_p))
2101 return t;
2102 return void_node;
2104 case IFN_ADD_OVERFLOW:
2105 opcode = PLUS_EXPR;
2106 break;
2107 case IFN_SUB_OVERFLOW:
2108 opcode = MINUS_EXPR;
2109 break;
2110 case IFN_MUL_OVERFLOW:
2111 opcode = MULT_EXPR;
2112 break;
2114 case IFN_LAUNDER:
2115 return cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0),
2116 vc_prvalue, non_constant_p,
2117 overflow_p);
2119 case IFN_VEC_CONVERT:
2121 tree arg = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0),
2122 vc_prvalue, non_constant_p,
2123 overflow_p);
2124 if (TREE_CODE (arg) == VECTOR_CST)
2125 if (tree r = fold_const_call (CFN_VEC_CONVERT, TREE_TYPE (t), arg))
2126 return r;
2128 /* FALLTHRU */
2130 default:
2131 if (!ctx->quiet)
2132 error_at (cp_expr_loc_or_input_loc (t),
2133 "call to internal function %qE", t);
2134 *non_constant_p = true;
2135 return t;
2138 /* Evaluate constant arguments using OPCODE and return a complex
2139 number containing the result and the overflow bit. */
2140 tree arg0 = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0), lval,
2141 non_constant_p, overflow_p);
2142 tree arg1 = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 1), lval,
2143 non_constant_p, overflow_p);
2145 if (TREE_CODE (arg0) == INTEGER_CST && TREE_CODE (arg1) == INTEGER_CST)
2147 location_t loc = cp_expr_loc_or_input_loc (t);
2148 tree type = TREE_TYPE (TREE_TYPE (t));
2149 tree result = fold_binary_loc (loc, opcode, type,
2150 fold_convert_loc (loc, type, arg0),
2151 fold_convert_loc (loc, type, arg1));
2152 tree ovf
2153 = build_int_cst (type, arith_overflowed_p (opcode, type, arg0, arg1));
2154 /* Reset TREE_OVERFLOW to avoid warnings for the overflow. */
2155 if (TREE_OVERFLOW (result))
2156 TREE_OVERFLOW (result) = 0;
2158 return build_complex (TREE_TYPE (t), result, ovf);
2161 *non_constant_p = true;
2162 return t;
2165 /* Clean CONSTRUCTOR_NO_CLEARING from CTOR and its sub-aggregates. */
2167 static void
2168 clear_no_implicit_zero (tree ctor)
2170 if (CONSTRUCTOR_NO_CLEARING (ctor))
2172 CONSTRUCTOR_NO_CLEARING (ctor) = false;
2173 for (auto &e: CONSTRUCTOR_ELTS (ctor))
2174 if (TREE_CODE (e.value) == CONSTRUCTOR)
2175 clear_no_implicit_zero (e.value);
2179 /* Complain about a const object OBJ being modified in a constant expression.
2180 EXPR is the MODIFY_EXPR expression performing the modification. */
2182 static void
2183 modifying_const_object_error (tree expr, tree obj)
2185 location_t loc = cp_expr_loc_or_input_loc (expr);
2186 auto_diagnostic_group d;
2187 error_at (loc, "modifying a const object %qE is not allowed in "
2188 "a constant expression", TREE_OPERAND (expr, 0));
2190 /* Find the underlying object that was declared as const. */
2191 location_t decl_loc = UNKNOWN_LOCATION;
2192 for (tree probe = obj; decl_loc == UNKNOWN_LOCATION; )
2193 switch (TREE_CODE (probe))
2195 case BIT_FIELD_REF:
2196 case COMPONENT_REF:
2198 tree elt = TREE_OPERAND (probe, 1);
2199 if (CP_TYPE_CONST_P (TREE_TYPE (elt)))
2200 decl_loc = DECL_SOURCE_LOCATION (elt);
2201 probe = TREE_OPERAND (probe, 0);
2203 break;
2205 case ARRAY_REF:
2206 case REALPART_EXPR:
2207 case IMAGPART_EXPR:
2208 probe = TREE_OPERAND (probe, 0);
2209 break;
2211 default:
2212 decl_loc = location_of (probe);
2213 break;
2215 inform (decl_loc, "originally declared %<const%> here");
2218 /* Return true if FNDECL is a replaceable global allocation function that
2219 should be useable during constant expression evaluation. */
2221 static inline bool
2222 cxx_replaceable_global_alloc_fn (tree fndecl)
2224 return (cxx_dialect >= cxx20
2225 && IDENTIFIER_NEWDEL_OP_P (DECL_NAME (fndecl))
2226 && CP_DECL_CONTEXT (fndecl) == global_namespace
2227 && (DECL_IS_REPLACEABLE_OPERATOR_NEW_P (fndecl)
2228 || DECL_IS_OPERATOR_DELETE_P (fndecl)));
2231 /* Return true if FNDECL is a placement new function that should be
2232 useable during constant expression evaluation of std::construct_at. */
2234 static inline bool
2235 cxx_placement_new_fn (tree fndecl)
2237 if (cxx_dialect >= cxx20
2238 && IDENTIFIER_NEW_OP_P (DECL_NAME (fndecl))
2239 && CP_DECL_CONTEXT (fndecl) == global_namespace
2240 && !DECL_IS_REPLACEABLE_OPERATOR_NEW_P (fndecl)
2241 && TREE_CODE (TREE_TYPE (fndecl)) == FUNCTION_TYPE)
2243 tree first_arg = TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (fndecl)));
2244 if (TREE_VALUE (first_arg) == ptr_type_node
2245 && TREE_CHAIN (first_arg) == void_list_node)
2246 return true;
2248 return false;
2251 /* Return true if FNDECL is std::construct_at. */
2253 static inline bool
2254 is_std_construct_at (tree fndecl)
2256 if (!decl_in_std_namespace_p (fndecl))
2257 return false;
2259 tree name = DECL_NAME (fndecl);
2260 return name && id_equal (name, "construct_at");
2263 /* Overload for the above taking constexpr_call*. */
2265 static inline bool
2266 is_std_construct_at (const constexpr_call *call)
2268 return (call
2269 && call->fundef
2270 && is_std_construct_at (call->fundef->decl));
2273 /* True if CTX is an instance of std::allocator. */
2275 bool
2276 is_std_allocator (tree ctx)
2278 if (ctx == NULL_TREE || !CLASS_TYPE_P (ctx) || !TYPE_MAIN_DECL (ctx))
2279 return false;
2281 tree decl = TYPE_MAIN_DECL (ctx);
2282 tree name = DECL_NAME (decl);
2283 if (name == NULL_TREE || !id_equal (name, "allocator"))
2284 return false;
2286 return decl_in_std_namespace_p (decl);
2289 /* Return true if FNDECL is std::allocator<T>::{,de}allocate. */
2291 static inline bool
2292 is_std_allocator_allocate (tree fndecl)
2294 tree name = DECL_NAME (fndecl);
2295 if (name == NULL_TREE
2296 || !(id_equal (name, "allocate") || id_equal (name, "deallocate")))
2297 return false;
2299 return is_std_allocator (DECL_CONTEXT (fndecl));
2302 /* Overload for the above taking constexpr_call*. */
2304 static inline bool
2305 is_std_allocator_allocate (const constexpr_call *call)
2307 return (call
2308 && call->fundef
2309 && is_std_allocator_allocate (call->fundef->decl));
2312 /* Return true if FNDECL is std::source_location::current. */
2314 static inline bool
2315 is_std_source_location_current (tree fndecl)
2317 if (!decl_in_std_namespace_p (fndecl))
2318 return false;
2320 tree name = DECL_NAME (fndecl);
2321 if (name == NULL_TREE || !id_equal (name, "current"))
2322 return false;
2324 tree ctx = DECL_CONTEXT (fndecl);
2325 if (ctx == NULL_TREE || !CLASS_TYPE_P (ctx) || !TYPE_MAIN_DECL (ctx))
2326 return false;
2328 name = DECL_NAME (TYPE_MAIN_DECL (ctx));
2329 return name && id_equal (name, "source_location");
2332 /* Overload for the above taking constexpr_call*. */
2334 static inline bool
2335 is_std_source_location_current (const constexpr_call *call)
2337 return (call
2338 && call->fundef
2339 && is_std_source_location_current (call->fundef->decl));
2342 /* Return true if FNDECL is __dynamic_cast. */
2344 static inline bool
2345 cxx_dynamic_cast_fn_p (tree fndecl)
2347 return (cxx_dialect >= cxx20
2348 && id_equal (DECL_NAME (fndecl), "__dynamic_cast")
2349 && CP_DECL_CONTEXT (fndecl) == abi_node);
2352 /* Often, we have an expression in the form of address + offset, e.g.
2353 "&_ZTV1A + 16". Extract the object from it, i.e. "_ZTV1A". */
2355 static tree
2356 extract_obj_from_addr_offset (tree expr)
2358 if (TREE_CODE (expr) == POINTER_PLUS_EXPR)
2359 expr = TREE_OPERAND (expr, 0);
2360 STRIP_NOPS (expr);
2361 if (TREE_CODE (expr) == ADDR_EXPR)
2362 expr = TREE_OPERAND (expr, 0);
2363 return expr;
2366 /* Given a PATH like
2368 g.D.2181.D.2154.D.2102.D.2093
2370 find a component with type TYPE. Return NULL_TREE if not found, and
2371 error_mark_node if the component is not accessible. If STOP is non-null,
2372 this function will return NULL_TREE if STOP is found before TYPE. */
2374 static tree
2375 get_component_with_type (tree path, tree type, tree stop)
2377 while (true)
2379 if (same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (path), type))
2380 /* Found it. */
2381 return path;
2382 else if (stop
2383 && (same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (path),
2384 stop)))
2385 return NULL_TREE;
2386 else if (TREE_CODE (path) == COMPONENT_REF
2387 && DECL_FIELD_IS_BASE (TREE_OPERAND (path, 1)))
2389 /* We need to check that the component we're accessing is in fact
2390 accessible. */
2391 if (TREE_PRIVATE (TREE_OPERAND (path, 1))
2392 || TREE_PROTECTED (TREE_OPERAND (path, 1)))
2393 return error_mark_node;
2394 path = TREE_OPERAND (path, 0);
2396 else
2397 return NULL_TREE;
2401 /* Evaluate a call to __dynamic_cast (permitted by P1327R1).
2403 The declaration of __dynamic_cast is:
2405 void* __dynamic_cast (const void* __src_ptr,
2406 const __class_type_info* __src_type,
2407 const __class_type_info* __dst_type,
2408 ptrdiff_t __src2dst);
2410 where src2dst has the following possible values
2412 >-1: src_type is a unique public non-virtual base of dst_type
2413 dst_ptr + src2dst == src_ptr
2414 -1: unspecified relationship
2415 -2: src_type is not a public base of dst_type
2416 -3: src_type is a multiple public non-virtual base of dst_type
2418 Since literal types can't have virtual bases, we only expect hint >=0,
2419 -2, or -3. */
2421 static tree
2422 cxx_eval_dynamic_cast_fn (const constexpr_ctx *ctx, tree call,
2423 bool *non_constant_p, bool *overflow_p)
2425 /* T will be something like
2426 __dynamic_cast ((B*) b, &_ZTI1B, &_ZTI1D, 8)
2427 dismantle it. */
2428 gcc_assert (call_expr_nargs (call) == 4);
2429 tsubst_flags_t complain = ctx->quiet ? tf_none : tf_warning_or_error;
2430 tree obj = CALL_EXPR_ARG (call, 0);
2431 tree type = CALL_EXPR_ARG (call, 2);
2432 HOST_WIDE_INT hint = int_cst_value (CALL_EXPR_ARG (call, 3));
2433 location_t loc = cp_expr_loc_or_input_loc (call);
2435 /* Get the target type of the dynamic_cast. */
2436 gcc_assert (TREE_CODE (type) == ADDR_EXPR);
2437 type = TREE_OPERAND (type, 0);
2438 type = TREE_TYPE (DECL_NAME (type));
2440 /* TYPE can only be either T* or T&. We can't know which of these it
2441 is by looking at TYPE, but OBJ will be "(T*) x" in the first case,
2442 and something like "(T*)(T&)(T*) x" in the second case. */
2443 bool reference_p = false;
2444 while (CONVERT_EXPR_P (obj) || TREE_CODE (obj) == SAVE_EXPR)
2446 reference_p |= TYPE_REF_P (TREE_TYPE (obj));
2447 obj = TREE_OPERAND (obj, 0);
2450 /* Evaluate the object so that we know its dynamic type. */
2451 obj = cxx_eval_constant_expression (ctx, obj, vc_prvalue, non_constant_p,
2452 overflow_p);
2453 if (*non_constant_p)
2454 return call;
2456 /* We expect OBJ to be in form of &d.D.2102 when HINT == 0,
2457 but when HINT is > 0, it can also be something like
2458 &d.D.2102 + 18446744073709551608, which includes the BINFO_OFFSET. */
2459 obj = extract_obj_from_addr_offset (obj);
2460 const tree objtype = TREE_TYPE (obj);
2461 /* If OBJ doesn't refer to a base field, we're done. */
2462 if (tree t = (TREE_CODE (obj) == COMPONENT_REF
2463 ? TREE_OPERAND (obj, 1) : obj))
2464 if (TREE_CODE (t) != FIELD_DECL || !DECL_FIELD_IS_BASE (t))
2466 if (reference_p)
2468 if (!ctx->quiet)
2470 auto_diagnostic_group d;
2471 error_at (loc, "reference %<dynamic_cast%> failed");
2472 inform (loc, "dynamic type %qT of its operand does "
2473 "not have a base class of type %qT",
2474 objtype, type);
2476 *non_constant_p = true;
2478 return integer_zero_node;
2481 /* [class.cdtor] When a dynamic_cast is used in a constructor ...
2482 or in a destructor ... if the operand of the dynamic_cast refers
2483 to the object under construction or destruction, this object is
2484 considered to be a most derived object that has the type of the
2485 constructor or destructor's class. */
2486 tree vtable = build_vfield_ref (obj, objtype);
2487 vtable = cxx_eval_constant_expression (ctx, vtable, vc_prvalue,
2488 non_constant_p, overflow_p);
2489 if (*non_constant_p)
2490 return call;
2491 /* With -fsanitize=vptr, we initialize all vtable pointers to null,
2492 so it's possible that we got a null pointer now. */
2493 if (integer_zerop (vtable))
2495 if (!ctx->quiet)
2496 error_at (loc, "virtual table pointer is used uninitialized");
2497 *non_constant_p = true;
2498 return integer_zero_node;
2500 /* VTABLE will be &_ZTV1A + 16 or similar, get _ZTV1A. */
2501 vtable = extract_obj_from_addr_offset (vtable);
2502 const tree mdtype = DECL_CONTEXT (vtable);
2504 /* Given dynamic_cast<T>(v),
2506 [expr.dynamic.cast] If C is the class type to which T points or refers,
2507 the runtime check logically executes as follows:
2509 If, in the most derived object pointed (referred) to by v, v points
2510 (refers) to a public base class subobject of a C object, and if only
2511 one object of type C is derived from the subobject pointed (referred)
2512 to by v the result points (refers) to that C object.
2514 In this case, HINT >= 0 or -3. */
2515 if (hint >= 0 || hint == -3)
2517 /* Look for a component with type TYPE. */
2518 tree t = get_component_with_type (obj, type, mdtype);
2519 /* If not accessible, give an error. */
2520 if (t == error_mark_node)
2522 if (reference_p)
2524 if (!ctx->quiet)
2526 auto_diagnostic_group d;
2527 error_at (loc, "reference %<dynamic_cast%> failed");
2528 inform (loc, "static type %qT of its operand is a "
2529 "non-public base class of dynamic type %qT",
2530 objtype, type);
2533 *non_constant_p = true;
2535 return integer_zero_node;
2537 else if (t)
2538 /* The result points to the TYPE object. */
2539 return cp_build_addr_expr (t, complain);
2540 /* Else, TYPE was not found, because the HINT turned out to be wrong.
2541 Fall through to the normal processing. */
2544 /* Otherwise, if v points (refers) to a public base class subobject of the
2545 most derived object, and the type of the most derived object has a base
2546 class, of type C, that is unambiguous and public, the result points
2547 (refers) to the C subobject of the most derived object.
2549 But it can also be an invalid case. */
2551 /* Get the most derived object. */
2552 obj = get_component_with_type (obj, mdtype, NULL_TREE);
2553 if (obj == error_mark_node)
2555 if (reference_p)
2557 if (!ctx->quiet)
2559 auto_diagnostic_group d;
2560 error_at (loc, "reference %<dynamic_cast%> failed");
2561 inform (loc, "static type %qT of its operand is a non-public"
2562 " base class of dynamic type %qT", objtype, mdtype);
2564 *non_constant_p = true;
2566 return integer_zero_node;
2568 else
2569 gcc_assert (obj);
2571 /* Check that the type of the most derived object has a base class
2572 of type TYPE that is unambiguous and public. */
2573 base_kind b_kind;
2574 tree binfo = lookup_base (mdtype, type, ba_check, &b_kind, tf_none);
2575 if (!binfo || binfo == error_mark_node)
2577 if (reference_p)
2579 if (!ctx->quiet)
2581 auto_diagnostic_group d;
2582 error_at (loc, "reference %<dynamic_cast%> failed");
2583 if (b_kind == bk_ambig)
2584 inform (loc, "%qT is an ambiguous base class of dynamic "
2585 "type %qT of its operand", type, mdtype);
2586 else
2587 inform (loc, "dynamic type %qT of its operand does not "
2588 "have an unambiguous public base class %qT",
2589 mdtype, type);
2591 *non_constant_p = true;
2593 return integer_zero_node;
2595 /* If so, return the TYPE subobject of the most derived object. */
2596 obj = convert_to_base_statically (obj, binfo);
2597 return cp_build_addr_expr (obj, complain);
2600 /* Data structure used by replace_decl and replace_decl_r. */
2602 struct replace_decl_data
2604 /* The _DECL we want to replace. */
2605 tree decl;
2606 /* The replacement for DECL. */
2607 tree replacement;
2608 /* Trees we've visited. */
2609 hash_set<tree> *pset;
2610 /* Whether we've performed any replacements. */
2611 bool changed;
2614 /* Helper function for replace_decl, called through cp_walk_tree. */
2616 static tree
2617 replace_decl_r (tree *tp, int *walk_subtrees, void *data)
2619 replace_decl_data *d = (replace_decl_data *) data;
2621 if (*tp == d->decl)
2623 *tp = unshare_expr (d->replacement);
2624 d->changed = true;
2625 *walk_subtrees = 0;
2627 else if (TYPE_P (*tp)
2628 || d->pset->add (*tp))
2629 *walk_subtrees = 0;
2631 return NULL_TREE;
2634 /* Replace every occurrence of DECL with (an unshared copy of)
2635 REPLACEMENT within the expression *TP. Returns true iff a
2636 replacement was performed. */
2638 bool
2639 replace_decl (tree *tp, tree decl, tree replacement)
2641 gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
2642 (TREE_TYPE (decl), TREE_TYPE (replacement)));
2643 hash_set<tree> pset;
2644 replace_decl_data data = { decl, replacement, &pset, false };
2645 cp_walk_tree (tp, replace_decl_r, &data, NULL);
2646 return data.changed;
2649 /* Evaluate the call T to virtual function thunk THUNK_FNDECL. */
2651 static tree
2652 cxx_eval_thunk_call (const constexpr_ctx *ctx, tree t, tree thunk_fndecl,
2653 value_cat lval,
2654 bool *non_constant_p, bool *overflow_p)
2656 tree function = THUNK_TARGET (thunk_fndecl);
2658 if (THUNK_VIRTUAL_OFFSET (thunk_fndecl))
2660 if (!ctx->quiet)
2662 if (!DECL_DECLARED_CONSTEXPR_P (function))
2664 error ("call to non-%<constexpr%> function %qD", function);
2665 explain_invalid_constexpr_fn (function);
2667 else
2668 /* virtual_offset is only set for virtual bases, which make the
2669 class non-literal, so we don't need to handle it here. */
2670 error ("calling constexpr member function %qD through virtual "
2671 "base subobject", function);
2673 *non_constant_p = true;
2674 return t;
2677 tree new_call = copy_node (t);
2678 CALL_EXPR_FN (new_call) = function;
2679 TREE_TYPE (new_call) = TREE_TYPE (TREE_TYPE (function));
2681 tree offset = size_int (THUNK_FIXED_OFFSET (thunk_fndecl));
2683 if (DECL_THIS_THUNK_P (thunk_fndecl))
2685 /* 'this'-adjusting thunk. */
2686 tree this_arg = CALL_EXPR_ARG (t, 0);
2687 this_arg = build2 (POINTER_PLUS_EXPR, TREE_TYPE (this_arg),
2688 this_arg, offset);
2689 CALL_EXPR_ARG (new_call, 0) = this_arg;
2691 else
2692 /* Return-adjusting thunk. */
2693 new_call = build2 (POINTER_PLUS_EXPR, TREE_TYPE (new_call),
2694 new_call, offset);
2696 return cxx_eval_constant_expression (ctx, new_call, lval,
2697 non_constant_p, overflow_p);
2700 /* If OBJECT is of const class type, evaluate it to a CONSTRUCTOR and set
2701 its TREE_READONLY flag according to READONLY_P. Used for constexpr
2702 'tors to detect modifying const objects in a constexpr context. */
2704 static void
2705 cxx_set_object_constness (const constexpr_ctx *ctx, tree object,
2706 bool readonly_p, bool *non_constant_p,
2707 bool *overflow_p)
2709 if (CLASS_TYPE_P (TREE_TYPE (object))
2710 && CP_TYPE_CONST_P (TREE_TYPE (object)))
2712 /* Subobjects might not be stored in ctx->global->values but we
2713 can get its CONSTRUCTOR by evaluating *this. */
2714 tree e = cxx_eval_constant_expression (ctx, object, vc_prvalue,
2715 non_constant_p, overflow_p);
2716 if (TREE_CODE (e) == CONSTRUCTOR && !*non_constant_p)
2717 TREE_READONLY (e) = readonly_p;
2721 /* Subroutine of cxx_eval_constant_expression.
2722 Evaluate the call expression tree T in the context of OLD_CALL expression
2723 evaluation. */
2725 static tree
2726 cxx_eval_call_expression (const constexpr_ctx *ctx, tree t,
2727 value_cat lval,
2728 bool *non_constant_p, bool *overflow_p)
2730 /* Handle concept checks separately. */
2731 if (concept_check_p (t))
2732 return evaluate_concept_check (t);
2734 location_t loc = cp_expr_loc_or_input_loc (t);
2735 tree fun = get_function_named_in_call (t);
2736 constexpr_call new_call
2737 = { NULL, NULL, NULL, 0, ctx->manifestly_const_eval };
2738 int depth_ok;
2740 if (fun == NULL_TREE)
2741 return cxx_eval_internal_function (ctx, t, lval,
2742 non_constant_p, overflow_p);
2744 if (TREE_CODE (fun) != FUNCTION_DECL)
2746 /* Might be a constexpr function pointer. */
2747 fun = cxx_eval_constant_expression (ctx, fun, vc_prvalue,
2748 non_constant_p, overflow_p);
2749 STRIP_NOPS (fun);
2750 if (TREE_CODE (fun) == ADDR_EXPR)
2751 fun = TREE_OPERAND (fun, 0);
2752 /* For TARGET_VTABLE_USES_DESCRIPTORS targets, there is no
2753 indirection, the called expression is a pointer into the
2754 virtual table which should contain FDESC_EXPR. Extract the
2755 FUNCTION_DECL from there. */
2756 else if (TARGET_VTABLE_USES_DESCRIPTORS
2757 && TREE_CODE (fun) == POINTER_PLUS_EXPR
2758 && TREE_CODE (TREE_OPERAND (fun, 0)) == ADDR_EXPR
2759 && TREE_CODE (TREE_OPERAND (fun, 1)) == INTEGER_CST)
2761 tree d = TREE_OPERAND (TREE_OPERAND (fun, 0), 0);
2762 if (VAR_P (d)
2763 && DECL_VTABLE_OR_VTT_P (d)
2764 && TREE_CODE (TREE_TYPE (d)) == ARRAY_TYPE
2765 && TREE_TYPE (TREE_TYPE (d)) == vtable_entry_type
2766 && DECL_INITIAL (d)
2767 && TREE_CODE (DECL_INITIAL (d)) == CONSTRUCTOR)
2769 tree i = int_const_binop (TRUNC_DIV_EXPR, TREE_OPERAND (fun, 1),
2770 TYPE_SIZE_UNIT (vtable_entry_type));
2771 HOST_WIDE_INT idx = find_array_ctor_elt (DECL_INITIAL (d), i);
2772 if (idx >= 0)
2774 tree fdesc
2775 = (*CONSTRUCTOR_ELTS (DECL_INITIAL (d)))[idx].value;
2776 if (TREE_CODE (fdesc) == FDESC_EXPR
2777 && integer_zerop (TREE_OPERAND (fdesc, 1)))
2778 fun = TREE_OPERAND (fdesc, 0);
2783 if (TREE_CODE (fun) != FUNCTION_DECL)
2785 if (!ctx->quiet && !*non_constant_p)
2786 error_at (loc, "expression %qE does not designate a %<constexpr%> "
2787 "function", fun);
2788 *non_constant_p = true;
2789 return t;
2791 if (DECL_CLONED_FUNCTION_P (fun) && !DECL_DELETING_DESTRUCTOR_P (fun))
2792 fun = DECL_CLONED_FUNCTION (fun);
2794 if (is_ubsan_builtin_p (fun))
2795 return void_node;
2797 if (fndecl_built_in_p (fun))
2798 return cxx_eval_builtin_function_call (ctx, t, fun,
2799 lval, non_constant_p, overflow_p);
2800 if (DECL_THUNK_P (fun))
2801 return cxx_eval_thunk_call (ctx, t, fun, lval, non_constant_p, overflow_p);
2802 if (!maybe_constexpr_fn (fun))
2804 if (TREE_CODE (t) == CALL_EXPR
2805 && cxx_replaceable_global_alloc_fn (fun)
2806 && (CALL_FROM_NEW_OR_DELETE_P (t)
2807 || is_std_allocator_allocate (ctx->call)))
2809 const int nargs = call_expr_nargs (t);
2810 tree arg0 = NULL_TREE;
2811 for (int i = 0; i < nargs; ++i)
2813 tree arg = CALL_EXPR_ARG (t, i);
2814 arg = cxx_eval_constant_expression (ctx, arg, vc_prvalue,
2815 non_constant_p, overflow_p);
2816 VERIFY_CONSTANT (arg);
2817 if (i == 0)
2818 arg0 = arg;
2820 gcc_assert (arg0);
2821 if (IDENTIFIER_NEW_OP_P (DECL_NAME (fun)))
2823 tree type = build_array_type_nelts (char_type_node,
2824 tree_to_uhwi (arg0));
2825 tree var = build_decl (loc, VAR_DECL,
2826 (IDENTIFIER_OVL_OP_FLAGS (DECL_NAME (fun))
2827 & OVL_OP_FLAG_VEC)
2828 ? heap_vec_uninit_identifier
2829 : heap_uninit_identifier,
2830 type);
2831 DECL_ARTIFICIAL (var) = 1;
2832 TREE_STATIC (var) = 1;
2833 // Temporarily register the artificial var in varpool,
2834 // so that comparisons of its address against NULL are folded
2835 // through nonzero_address even with
2836 // -fno-delete-null-pointer-checks or that comparison of
2837 // addresses of different heap artificial vars is folded too.
2838 // See PR98988 and PR99031.
2839 varpool_node::finalize_decl (var);
2840 ctx->global->heap_vars.safe_push (var);
2841 ctx->global->put_value (var, NULL_TREE);
2842 return fold_convert (ptr_type_node, build_address (var));
2844 else
2846 STRIP_NOPS (arg0);
2847 if (TREE_CODE (arg0) == ADDR_EXPR
2848 && VAR_P (TREE_OPERAND (arg0, 0)))
2850 tree var = TREE_OPERAND (arg0, 0);
2851 if (DECL_NAME (var) == heap_uninit_identifier
2852 || DECL_NAME (var) == heap_identifier)
2854 if (IDENTIFIER_OVL_OP_FLAGS (DECL_NAME (fun))
2855 & OVL_OP_FLAG_VEC)
2857 if (!ctx->quiet)
2859 auto_diagnostic_group d;
2860 error_at (loc, "array deallocation of object "
2861 "allocated with non-array "
2862 "allocation");
2863 inform (DECL_SOURCE_LOCATION (var),
2864 "allocation performed here");
2866 *non_constant_p = true;
2867 return t;
2869 DECL_NAME (var) = heap_deleted_identifier;
2870 ctx->global->remove_value (var);
2871 ctx->global->heap_dealloc_count++;
2872 return void_node;
2874 else if (DECL_NAME (var) == heap_vec_uninit_identifier
2875 || DECL_NAME (var) == heap_vec_identifier)
2877 if ((IDENTIFIER_OVL_OP_FLAGS (DECL_NAME (fun))
2878 & OVL_OP_FLAG_VEC) == 0)
2880 if (!ctx->quiet)
2882 auto_diagnostic_group d;
2883 error_at (loc, "non-array deallocation of "
2884 "object allocated with array "
2885 "allocation");
2886 inform (DECL_SOURCE_LOCATION (var),
2887 "allocation performed here");
2889 *non_constant_p = true;
2890 return t;
2892 DECL_NAME (var) = heap_deleted_identifier;
2893 ctx->global->remove_value (var);
2894 ctx->global->heap_dealloc_count++;
2895 return void_node;
2897 else if (DECL_NAME (var) == heap_deleted_identifier)
2899 if (!ctx->quiet)
2900 error_at (loc, "deallocation of already deallocated "
2901 "storage");
2902 *non_constant_p = true;
2903 return t;
2906 if (!ctx->quiet)
2907 error_at (loc, "deallocation of storage that was "
2908 "not previously allocated");
2909 *non_constant_p = true;
2910 return t;
2913 /* Allow placement new in std::construct_at, just return the second
2914 argument. */
2915 if (TREE_CODE (t) == CALL_EXPR
2916 && cxx_placement_new_fn (fun)
2917 && is_std_construct_at (ctx->call))
2919 const int nargs = call_expr_nargs (t);
2920 tree arg1 = NULL_TREE;
2921 for (int i = 0; i < nargs; ++i)
2923 tree arg = CALL_EXPR_ARG (t, i);
2924 arg = cxx_eval_constant_expression (ctx, arg, vc_prvalue,
2925 non_constant_p, overflow_p);
2926 if (i == 1)
2927 arg1 = arg;
2928 else
2929 VERIFY_CONSTANT (arg);
2931 gcc_assert (arg1);
2932 return arg1;
2934 else if (cxx_dynamic_cast_fn_p (fun))
2935 return cxx_eval_dynamic_cast_fn (ctx, t, non_constant_p, overflow_p);
2937 if (!ctx->quiet)
2939 if (!lambda_static_thunk_p (fun))
2940 error_at (loc, "call to non-%<constexpr%> function %qD", fun);
2941 explain_invalid_constexpr_fn (fun);
2943 *non_constant_p = true;
2944 return t;
2947 constexpr_ctx new_ctx = *ctx;
2948 if (DECL_CONSTRUCTOR_P (fun) && !ctx->object
2949 && TREE_CODE (t) == AGGR_INIT_EXPR)
2951 /* We want to have an initialization target for an AGGR_INIT_EXPR.
2952 If we don't already have one in CTX, use the AGGR_INIT_EXPR_SLOT. */
2953 new_ctx.object = AGGR_INIT_EXPR_SLOT (t);
2954 tree ctor = new_ctx.ctor = build_constructor (DECL_CONTEXT (fun), NULL);
2955 CONSTRUCTOR_NO_CLEARING (ctor) = true;
2956 ctx->global->put_value (new_ctx.object, ctor);
2957 ctx = &new_ctx;
2960 /* We used to shortcut trivial constructor/op= here, but nowadays
2961 we can only get a trivial function here with -fno-elide-constructors. */
2962 gcc_checking_assert (!trivial_fn_p (fun)
2963 || !flag_elide_constructors
2964 /* We don't elide constructors when processing
2965 a noexcept-expression. */
2966 || cp_noexcept_operand);
2968 bool non_constant_args = false;
2969 new_call.bindings
2970 = cxx_bind_parameters_in_call (ctx, t, fun, non_constant_p,
2971 overflow_p, &non_constant_args);
2973 /* We build up the bindings list before we know whether we already have this
2974 call cached. If we don't end up saving these bindings, ggc_free them when
2975 this function exits. */
2976 class free_bindings
2978 tree *bindings;
2979 public:
2980 free_bindings (tree &b): bindings (&b) { }
2981 ~free_bindings () { if (bindings) ggc_free (*bindings); }
2982 void preserve () { bindings = NULL; }
2983 } fb (new_call.bindings);
2985 if (*non_constant_p)
2986 return t;
2988 /* We can't defer instantiating the function any longer. */
2989 if (!DECL_INITIAL (fun)
2990 && (DECL_TEMPLOID_INSTANTIATION (fun) || DECL_DEFAULTED_FN (fun))
2991 && !uid_sensitive_constexpr_evaluation_p ())
2993 location_t save_loc = input_location;
2994 input_location = loc;
2995 ++function_depth;
2996 if (ctx->manifestly_const_eval == mce_true)
2997 FNDECL_MANIFESTLY_CONST_EVALUATED (fun) = true;
2998 if (DECL_TEMPLOID_INSTANTIATION (fun))
2999 instantiate_decl (fun, /*defer_ok*/false, /*expl_inst*/false);
3000 else
3001 synthesize_method (fun);
3002 --function_depth;
3003 input_location = save_loc;
3006 /* If in direct recursive call, optimize definition search. */
3007 if (ctx && ctx->call && ctx->call->fundef && ctx->call->fundef->decl == fun)
3008 new_call.fundef = ctx->call->fundef;
3009 else
3011 new_call.fundef = retrieve_constexpr_fundef (fun);
3012 if (new_call.fundef == NULL || new_call.fundef->body == NULL
3013 || new_call.fundef->result == error_mark_node
3014 || fun == current_function_decl)
3016 if (!ctx->quiet)
3018 /* We need to check for current_function_decl here in case we're
3019 being called during cp_fold_function, because at that point
3020 DECL_INITIAL is set properly and we have a fundef but we
3021 haven't lowered invisirefs yet (c++/70344). */
3022 if (DECL_INITIAL (fun) == error_mark_node
3023 || fun == current_function_decl)
3024 error_at (loc, "%qD called in a constant expression before its "
3025 "definition is complete", fun);
3026 else if (DECL_INITIAL (fun))
3028 /* The definition of fun was somehow unsuitable. But pretend
3029 that lambda static thunks don't exist. */
3030 if (!lambda_static_thunk_p (fun))
3031 error_at (loc, "%qD called in a constant expression", fun);
3032 explain_invalid_constexpr_fn (fun);
3034 else
3035 error_at (loc, "%qD used before its definition", fun);
3037 *non_constant_p = true;
3038 return t;
3042 depth_ok = push_cx_call_context (t);
3044 /* Remember the object we are constructing or destructing. */
3045 tree new_obj = NULL_TREE;
3046 if (DECL_CONSTRUCTOR_P (fun) || DECL_DESTRUCTOR_P (fun))
3048 /* In a cdtor, it should be the first `this' argument.
3049 At this point it has already been evaluated in the call
3050 to cxx_bind_parameters_in_call. */
3051 new_obj = TREE_VEC_ELT (new_call.bindings, 0);
3052 new_obj = cxx_fold_indirect_ref (ctx, loc, DECL_CONTEXT (fun), new_obj);
3054 if (ctx->call && ctx->call->fundef
3055 && DECL_CONSTRUCTOR_P (ctx->call->fundef->decl))
3057 tree cur_obj = TREE_VEC_ELT (ctx->call->bindings, 0);
3058 STRIP_NOPS (cur_obj);
3059 if (TREE_CODE (cur_obj) == ADDR_EXPR)
3060 cur_obj = TREE_OPERAND (cur_obj, 0);
3061 if (new_obj == cur_obj)
3062 /* We're calling the target constructor of a delegating
3063 constructor, or accessing a base subobject through a
3064 NOP_EXPR as part of a call to a base constructor, so
3065 there is no new (sub)object. */
3066 new_obj = NULL_TREE;
3070 tree result = NULL_TREE;
3072 constexpr_call *entry = NULL;
3073 if (depth_ok && !non_constant_args && ctx->strict)
3075 new_call.hash = constexpr_fundef_hasher::hash (new_call.fundef);
3076 new_call.hash
3077 = iterative_hash_template_arg (new_call.bindings, new_call.hash);
3078 new_call.hash
3079 = iterative_hash_object (ctx->manifestly_const_eval, new_call.hash);
3081 /* If we have seen this call before, we are done. */
3082 maybe_initialize_constexpr_call_table ();
3083 bool insert = depth_ok < constexpr_cache_depth;
3084 constexpr_call **slot
3085 = constexpr_call_table->find_slot (&new_call,
3086 insert ? INSERT : NO_INSERT);
3087 entry = slot ? *slot : NULL;
3088 if (entry == NULL)
3090 /* Only cache up to constexpr_cache_depth to limit memory use. */
3091 if (insert)
3093 /* We need to keep a pointer to the entry, not just the slot, as
3094 the slot can move during evaluation of the body. */
3095 *slot = entry = ggc_alloc<constexpr_call> ();
3096 *entry = new_call;
3097 fb.preserve ();
3100 /* Calls that are in progress have their result set to NULL, so that we
3101 can detect circular dependencies. Now that we only cache up to
3102 constexpr_cache_depth this won't catch circular dependencies that
3103 start deeper, but they'll hit the recursion or ops limit. */
3104 else if (entry->result == NULL)
3106 if (!ctx->quiet)
3107 error ("call has circular dependency");
3108 *non_constant_p = true;
3109 entry->result = result = error_mark_node;
3111 else
3112 result = entry->result;
3115 if (!depth_ok)
3117 if (!ctx->quiet)
3118 error ("%<constexpr%> evaluation depth exceeds maximum of %d (use "
3119 "%<-fconstexpr-depth=%> to increase the maximum)",
3120 max_constexpr_depth);
3121 *non_constant_p = true;
3122 result = error_mark_node;
3124 else
3126 bool cacheable = !!entry;
3127 if (result && result != error_mark_node)
3128 /* OK */;
3129 else if (!DECL_SAVED_TREE (fun))
3131 /* When at_eof >= 3, cgraph has started throwing away
3132 DECL_SAVED_TREE, so fail quietly. FIXME we get here because of
3133 late code generation for VEC_INIT_EXPR, which needs to be
3134 completely reconsidered. */
3135 gcc_assert (at_eof >= 3 && ctx->quiet);
3136 *non_constant_p = true;
3138 else if (tree copy = get_fundef_copy (new_call.fundef))
3140 tree body, parms, res;
3141 releasing_vec ctors;
3143 /* Reuse or create a new unshared copy of this function's body. */
3144 body = TREE_PURPOSE (copy);
3145 parms = TREE_VALUE (copy);
3146 res = TREE_TYPE (copy);
3148 /* Associate the bindings with the remapped parms. */
3149 tree bound = new_call.bindings;
3150 tree remapped = parms;
3151 for (int i = 0; i < TREE_VEC_LENGTH (bound); ++i)
3153 tree arg = TREE_VEC_ELT (bound, i);
3154 if (entry)
3156 /* Unshare args going into the hash table to separate them
3157 from the caller's context, for better GC and to avoid
3158 problems with verify_gimple. */
3159 arg = unshare_expr_without_location (arg);
3160 TREE_VEC_ELT (bound, i) = arg;
3162 /* And then unshare again so the callee doesn't change the
3163 argument values in the hash table. XXX Could we unshare
3164 lazily in cxx_eval_store_expression? */
3165 arg = unshare_constructor (arg);
3166 if (TREE_CODE (arg) == CONSTRUCTOR)
3167 vec_safe_push (ctors, arg);
3169 ctx->global->put_value (remapped, arg);
3170 remapped = DECL_CHAIN (remapped);
3172 for (; remapped; remapped = TREE_CHAIN (remapped))
3173 if (DECL_NAME (remapped) == in_charge_identifier)
3175 /* FIXME destructors unnecessarily have in-charge parameters
3176 even in classes without vbases, map it to 0 for now. */
3177 gcc_assert (!CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fun)));
3178 ctx->global->put_value (remapped, integer_zero_node);
3180 else
3182 gcc_assert (seen_error ());
3183 *non_constant_p = true;
3185 /* Add the RESULT_DECL to the values map, too. */
3186 gcc_assert (!DECL_BY_REFERENCE (res));
3187 ctx->global->put_value (res, NULL_TREE);
3189 /* Remember the current call we're evaluating. */
3190 constexpr_ctx call_ctx = *ctx;
3191 call_ctx.call = &new_call;
3192 unsigned save_heap_alloc_count = ctx->global->heap_vars.length ();
3193 unsigned save_heap_dealloc_count = ctx->global->heap_dealloc_count;
3195 /* Make sure we fold std::is_constant_evaluated to true in an
3196 immediate function. */
3197 if (DECL_IMMEDIATE_FUNCTION_P (fun))
3198 call_ctx.manifestly_const_eval = mce_true;
3200 /* If this is a constexpr destructor, the object's const and volatile
3201 semantics are no longer in effect; see [class.dtor]p5. */
3202 if (new_obj && DECL_DESTRUCTOR_P (fun))
3203 cxx_set_object_constness (ctx, new_obj, /*readonly_p=*/false,
3204 non_constant_p, overflow_p);
3206 /* If this is a constructor, we are beginning the lifetime of the
3207 object we are initializing. */
3208 if (new_obj
3209 && DECL_CONSTRUCTOR_P (fun)
3210 && TREE_CODE (new_obj) == COMPONENT_REF
3211 && TREE_CODE (TREE_TYPE (TREE_OPERAND (new_obj, 0))) == UNION_TYPE)
3213 tree activate = build2 (INIT_EXPR, TREE_TYPE (new_obj),
3214 new_obj,
3215 build_constructor (TREE_TYPE (new_obj),
3216 NULL));
3217 cxx_eval_constant_expression (ctx, activate,
3218 lval, non_constant_p, overflow_p);
3219 ggc_free (activate);
3222 tree jump_target = NULL_TREE;
3223 cxx_eval_constant_expression (&call_ctx, body,
3224 vc_discard, non_constant_p, overflow_p,
3225 &jump_target);
3227 if (DECL_CONSTRUCTOR_P (fun))
3228 /* This can be null for a subobject constructor call, in
3229 which case what we care about is the initialization
3230 side-effects rather than the value. We could get at the
3231 value by evaluating *this, but we don't bother; there's
3232 no need to put such a call in the hash table. */
3233 result = lval ? ctx->object : ctx->ctor;
3234 else if (VOID_TYPE_P (TREE_TYPE (res)))
3235 result = void_node;
3236 else
3238 result = ctx->global->get_value (res);
3239 if (result == NULL_TREE && !*non_constant_p
3240 && !DECL_DESTRUCTOR_P (fun))
3242 if (!ctx->quiet)
3243 error ("%<constexpr%> call flows off the end "
3244 "of the function");
3245 *non_constant_p = true;
3249 /* At this point, the object's constructor will have run, so
3250 the object is no longer under construction, and its possible
3251 'const' semantics now apply. Make a note of this fact by
3252 marking the CONSTRUCTOR TREE_READONLY. */
3253 if (new_obj && DECL_CONSTRUCTOR_P (fun))
3254 cxx_set_object_constness (ctx, new_obj, /*readonly_p=*/true,
3255 non_constant_p, overflow_p);
3257 /* Remove the parms/result from the values map. */
3258 ctx->global->remove_value (res);
3259 for (tree parm = parms; parm; parm = TREE_CHAIN (parm))
3260 ctx->global->remove_value (parm);
3262 /* Free any parameter CONSTRUCTORs we aren't returning directly. */
3263 while (!ctors->is_empty ())
3265 tree c = ctors->pop ();
3266 if (c != result)
3267 free_constructor (c);
3270 /* Make the unshared function copy we used available for re-use. */
3271 save_fundef_copy (fun, copy);
3273 /* If the call allocated some heap object that hasn't been
3274 deallocated during the call, or if it deallocated some heap
3275 object it has not allocated, the call isn't really stateless
3276 for the constexpr evaluation and should not be cached.
3277 It is fine if the call allocates something and deallocates it
3278 too. */
3279 if (cacheable
3280 && (save_heap_alloc_count != ctx->global->heap_vars.length ()
3281 || (save_heap_dealloc_count
3282 != ctx->global->heap_dealloc_count)))
3284 tree heap_var;
3285 unsigned int i;
3286 if ((ctx->global->heap_vars.length ()
3287 - ctx->global->heap_dealloc_count)
3288 != save_heap_alloc_count - save_heap_dealloc_count)
3289 cacheable = false;
3290 else
3291 FOR_EACH_VEC_ELT_FROM (ctx->global->heap_vars, i, heap_var,
3292 save_heap_alloc_count)
3293 if (DECL_NAME (heap_var) != heap_deleted_identifier)
3295 cacheable = false;
3296 break;
3300 /* Rewrite all occurrences of the function's RESULT_DECL with the
3301 current object under construction. */
3302 if (!*non_constant_p && ctx->object
3303 && CLASS_TYPE_P (TREE_TYPE (res))
3304 && !is_empty_class (TREE_TYPE (res)))
3305 if (replace_decl (&result, res, ctx->object))
3306 cacheable = false;
3308 /* Only cache a permitted result of a constant expression. */
3309 if (cacheable && !reduced_constant_expression_p (result))
3310 cacheable = false;
3312 else
3313 /* Couldn't get a function copy to evaluate. */
3314 *non_constant_p = true;
3316 if (result == error_mark_node)
3317 *non_constant_p = true;
3318 if (*non_constant_p || *overflow_p)
3319 result = error_mark_node;
3320 else if (!result)
3321 result = void_node;
3322 if (entry)
3323 entry->result = cacheable ? result : error_mark_node;
3326 /* The result of a constexpr function must be completely initialized.
3328 However, in C++20, a constexpr constructor doesn't necessarily have
3329 to initialize all the fields, so we don't clear CONSTRUCTOR_NO_CLEARING
3330 in order to detect reading an unitialized object in constexpr instead
3331 of value-initializing it. (reduced_constant_expression_p is expected to
3332 take care of clearing the flag.) */
3333 if (TREE_CODE (result) == CONSTRUCTOR
3334 && (cxx_dialect < cxx20
3335 || !DECL_CONSTRUCTOR_P (fun)))
3336 clear_no_implicit_zero (result);
3338 pop_cx_call_context ();
3339 return result;
3342 /* Return true if T is a valid constant initializer. If a CONSTRUCTOR
3343 initializes all the members, the CONSTRUCTOR_NO_CLEARING flag will be
3344 cleared.
3345 FIXME speed this up, it's taking 16% of compile time on sieve testcase. */
3347 bool
3348 reduced_constant_expression_p (tree t)
3350 if (t == NULL_TREE)
3351 return false;
3353 switch (TREE_CODE (t))
3355 case PTRMEM_CST:
3356 /* Even if we can't lower this yet, it's constant. */
3357 return true;
3359 case CONSTRUCTOR:
3360 /* And we need to handle PTRMEM_CST wrapped in a CONSTRUCTOR. */
3361 tree field;
3362 if (!AGGREGATE_TYPE_P (TREE_TYPE (t)))
3363 /* A constant vector would be folded to VECTOR_CST.
3364 A CONSTRUCTOR of scalar type means uninitialized. */
3365 return false;
3366 if (CONSTRUCTOR_NO_CLEARING (t))
3368 if (TREE_CODE (TREE_TYPE (t)) == ARRAY_TYPE)
3370 /* There must be a valid constant initializer at every array
3371 index. */
3372 tree min = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (t)));
3373 tree max = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (t)));
3374 tree cursor = min;
3375 for (auto &e: CONSTRUCTOR_ELTS (t))
3377 if (!reduced_constant_expression_p (e.value))
3378 return false;
3379 if (array_index_cmp (cursor, e.index) != 0)
3380 return false;
3381 if (TREE_CODE (e.index) == RANGE_EXPR)
3382 cursor = TREE_OPERAND (e.index, 1);
3383 cursor = int_const_binop (PLUS_EXPR, cursor, size_one_node);
3385 if (find_array_ctor_elt (t, max) == -1)
3386 return false;
3387 goto ok;
3389 else if (cxx_dialect >= cxx20
3390 && TREE_CODE (TREE_TYPE (t)) == UNION_TYPE)
3392 if (CONSTRUCTOR_NELTS (t) == 0)
3393 /* An initialized union has a constructor element. */
3394 return false;
3395 /* And it only initializes one member. */
3396 field = NULL_TREE;
3398 else
3399 field = next_subobject_field (TYPE_FIELDS (TREE_TYPE (t)));
3401 else
3402 field = NULL_TREE;
3403 for (auto &e: CONSTRUCTOR_ELTS (t))
3405 /* If VAL is null, we're in the middle of initializing this
3406 element. */
3407 if (!reduced_constant_expression_p (e.value))
3408 return false;
3409 /* We want to remove initializers for empty fields in a struct to
3410 avoid confusing output_constructor. */
3411 if (is_empty_field (e.index)
3412 && TREE_CODE (TREE_TYPE (t)) == RECORD_TYPE)
3413 return false;
3414 /* Check for non-empty fields between initialized fields when
3415 CONSTRUCTOR_NO_CLEARING. */
3416 for (; field && e.index != field;
3417 field = next_subobject_field (DECL_CHAIN (field)))
3418 if (!is_really_empty_class (TREE_TYPE (field),
3419 /*ignore_vptr*/false))
3420 return false;
3421 if (field)
3422 field = next_subobject_field (DECL_CHAIN (field));
3424 /* There could be a non-empty field at the end. */
3425 for (; field; field = next_subobject_field (DECL_CHAIN (field)))
3426 if (!is_really_empty_class (TREE_TYPE (field), /*ignore_vptr*/false))
3427 return false;
3429 if (CONSTRUCTOR_NO_CLEARING (t))
3430 /* All the fields are initialized. */
3431 CONSTRUCTOR_NO_CLEARING (t) = false;
3432 return true;
3434 default:
3435 /* FIXME are we calling this too much? */
3436 return initializer_constant_valid_p (t, TREE_TYPE (t)) != NULL_TREE;
3440 /* *TP was not deemed constant by reduced_constant_expression_p. Explain
3441 why and suggest what could be done about it. */
3443 static tree
3444 verify_constant_explain_r (tree *tp, int *walk_subtrees, void *)
3446 bool ref_p = false;
3448 /* No need to look into types or unevaluated operands. */
3449 if (TYPE_P (*tp) || unevaluated_p (TREE_CODE (*tp)))
3451 *walk_subtrees = false;
3452 return NULL_TREE;
3455 switch (TREE_CODE (*tp))
3457 CASE_CONVERT:
3458 if (TREE_CODE (TREE_OPERAND (*tp, 0)) != ADDR_EXPR)
3459 break;
3460 ref_p = TYPE_REF_P (TREE_TYPE (*tp));
3461 *tp = TREE_OPERAND (*tp, 0);
3462 gcc_fallthrough ();
3463 case ADDR_EXPR:
3465 tree op = TREE_OPERAND (*tp, 0);
3466 if (VAR_P (op)
3467 && DECL_DECLARED_CONSTEXPR_P (op)
3468 && !TREE_STATIC (op)
3469 /* ??? We should also say something about temporaries. */
3470 && !DECL_ARTIFICIAL (op))
3472 if (ref_p)
3473 inform (location_of (*tp), "reference to %qD is not a constant "
3474 "expression", op);
3475 else
3476 inform (location_of (*tp), "pointer to %qD is not a constant "
3477 "expression", op);
3478 const location_t op_loc = DECL_SOURCE_LOCATION (op);
3479 rich_location richloc (line_table, op_loc);
3480 richloc.add_fixit_insert_before (op_loc, "static ");
3481 inform (&richloc,
3482 "address of non-static constexpr variable %qD may differ on "
3483 "each invocation of the enclosing function; add %<static%> "
3484 "to give it a constant address", op);
3486 break;
3488 default:
3489 break;
3492 return NULL_TREE;
3495 /* Some expressions may have constant operands but are not constant
3496 themselves, such as 1/0. Call this function to check for that
3497 condition.
3499 We only call this in places that require an arithmetic constant, not in
3500 places where we might have a non-constant expression that can be a
3501 component of a constant expression, such as the address of a constexpr
3502 variable that might be dereferenced later. */
3504 static bool
3505 verify_constant (tree t, bool allow_non_constant, bool *non_constant_p,
3506 bool *overflow_p)
3508 if (!*non_constant_p && !reduced_constant_expression_p (t)
3509 && t != void_node)
3511 if (!allow_non_constant)
3513 auto_diagnostic_group d;
3514 error_at (cp_expr_loc_or_input_loc (t),
3515 "%q+E is not a constant expression", t);
3516 cp_walk_tree_without_duplicates (&t, verify_constant_explain_r,
3517 nullptr);
3519 *non_constant_p = true;
3521 if (TREE_OVERFLOW_P (t))
3523 if (!allow_non_constant)
3525 permerror (input_location, "overflow in constant expression");
3526 /* If we're being permissive (and are in an enforcing
3527 context), ignore the overflow. */
3528 if (flag_permissive)
3529 return *non_constant_p;
3531 *overflow_p = true;
3533 return *non_constant_p;
3536 /* Check whether the shift operation with code CODE and type TYPE on LHS
3537 and RHS is undefined. If it is, give an error with an explanation,
3538 and return true; return false otherwise. */
3540 static bool
3541 cxx_eval_check_shift_p (location_t loc, const constexpr_ctx *ctx,
3542 enum tree_code code, tree type, tree lhs, tree rhs)
3544 if ((code != LSHIFT_EXPR && code != RSHIFT_EXPR)
3545 || TREE_CODE (lhs) != INTEGER_CST
3546 || TREE_CODE (rhs) != INTEGER_CST)
3547 return false;
3549 tree lhstype = TREE_TYPE (lhs);
3550 unsigned HOST_WIDE_INT uprec = TYPE_PRECISION (TREE_TYPE (lhs));
3552 /* [expr.shift] The behavior is undefined if the right operand
3553 is negative, or greater than or equal to the length in bits
3554 of the promoted left operand. */
3555 if (tree_int_cst_sgn (rhs) == -1)
3557 if (!ctx->quiet)
3558 permerror (loc, "right operand of shift expression %q+E is negative",
3559 build2_loc (loc, code, type, lhs, rhs));
3560 return (!flag_permissive || ctx->quiet);
3562 if (compare_tree_int (rhs, uprec) >= 0)
3564 if (!ctx->quiet)
3565 permerror (loc, "right operand of shift expression %q+E is greater "
3566 "than or equal to the precision %wu of the left operand",
3567 build2_loc (loc, code, type, lhs, rhs), uprec);
3568 return (!flag_permissive || ctx->quiet);
3571 /* The value of E1 << E2 is E1 left-shifted E2 bit positions; [...]
3572 if E1 has a signed type and non-negative value, and E1x2^E2 is
3573 representable in the corresponding unsigned type of the result type,
3574 then that value, converted to the result type, is the resulting value;
3575 otherwise, the behavior is undefined.
3576 For C++20:
3577 The value of E1 << E2 is the unique value congruent to E1 x 2^E2 modulo
3578 2^N, where N is the range exponent of the type of the result. */
3579 if (code == LSHIFT_EXPR
3580 && !TYPE_OVERFLOW_WRAPS (lhstype)
3581 && cxx_dialect >= cxx11
3582 && cxx_dialect < cxx20)
3584 if (tree_int_cst_sgn (lhs) == -1)
3586 if (!ctx->quiet)
3587 permerror (loc,
3588 "left operand of shift expression %q+E is negative",
3589 build2_loc (loc, code, type, lhs, rhs));
3590 return (!flag_permissive || ctx->quiet);
3592 /* For signed x << y the following:
3593 (unsigned) x >> ((prec (lhs) - 1) - y)
3594 if > 1, is undefined. The right-hand side of this formula
3595 is the highest bit of the LHS that can be set (starting from 0),
3596 so that the shift doesn't overflow. We then right-shift the LHS
3597 to see whether any other bit is set making the original shift
3598 undefined -- the result is not representable in the corresponding
3599 unsigned type. */
3600 tree t = build_int_cst (unsigned_type_node, uprec - 1);
3601 t = fold_build2 (MINUS_EXPR, unsigned_type_node, t, rhs);
3602 tree ulhs = fold_convert (unsigned_type_for (lhstype), lhs);
3603 t = fold_build2 (RSHIFT_EXPR, TREE_TYPE (ulhs), ulhs, t);
3604 if (tree_int_cst_lt (integer_one_node, t))
3606 if (!ctx->quiet)
3607 permerror (loc, "shift expression %q+E overflows",
3608 build2_loc (loc, code, type, lhs, rhs));
3609 return (!flag_permissive || ctx->quiet);
3612 return false;
3615 /* Subroutine of cxx_eval_constant_expression.
3616 Attempt to reduce the unary expression tree T to a compile time value.
3617 If successful, return the value. Otherwise issue a diagnostic
3618 and return error_mark_node. */
3620 static tree
3621 cxx_eval_unary_expression (const constexpr_ctx *ctx, tree t,
3622 bool /*lval*/,
3623 bool *non_constant_p, bool *overflow_p)
3625 tree r;
3626 tree orig_arg = TREE_OPERAND (t, 0);
3627 tree arg = cxx_eval_constant_expression (ctx, orig_arg, vc_prvalue,
3628 non_constant_p, overflow_p);
3629 VERIFY_CONSTANT (arg);
3630 location_t loc = EXPR_LOCATION (t);
3631 enum tree_code code = TREE_CODE (t);
3632 tree type = TREE_TYPE (t);
3633 r = fold_unary_loc (loc, code, type, arg);
3634 if (r == NULL_TREE)
3636 if (arg == orig_arg)
3637 r = t;
3638 else
3639 r = build1_loc (loc, code, type, arg);
3641 VERIFY_CONSTANT (r);
3642 return r;
3645 /* Helper function for cxx_eval_binary_expression. Try to optimize
3646 original POINTER_PLUS_EXPR T, LHS p+ RHS, return NULL_TREE if the
3647 generic folding should be used. */
3649 static tree
3650 cxx_fold_pointer_plus_expression (const constexpr_ctx *ctx, tree t,
3651 tree lhs, tree rhs, bool *non_constant_p,
3652 bool *overflow_p)
3654 STRIP_NOPS (lhs);
3655 if (TREE_CODE (lhs) != ADDR_EXPR)
3656 return NULL_TREE;
3658 lhs = TREE_OPERAND (lhs, 0);
3660 /* &A[i] p+ j => &A[i + j] */
3661 if (TREE_CODE (lhs) == ARRAY_REF
3662 && TREE_CODE (TREE_OPERAND (lhs, 1)) == INTEGER_CST
3663 && TREE_CODE (rhs) == INTEGER_CST
3664 && TYPE_SIZE_UNIT (TREE_TYPE (lhs))
3665 && TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (lhs))) == INTEGER_CST)
3667 tree orig_type = TREE_TYPE (t);
3668 location_t loc = EXPR_LOCATION (t);
3669 tree type = TREE_TYPE (lhs);
3671 t = fold_convert_loc (loc, ssizetype, TREE_OPERAND (lhs, 1));
3672 tree nelts = array_type_nelts_top (TREE_TYPE (TREE_OPERAND (lhs, 0)));
3673 nelts = cxx_eval_constant_expression (ctx, nelts, vc_prvalue,
3674 non_constant_p, overflow_p);
3675 if (*non_constant_p)
3676 return NULL_TREE;
3677 /* Don't fold an out-of-bound access. */
3678 if (!tree_int_cst_le (t, nelts))
3679 return NULL_TREE;
3680 rhs = cp_fold_convert (ssizetype, rhs);
3681 /* Don't fold if rhs can't be divided exactly by TYPE_SIZE_UNIT.
3682 constexpr int A[1]; ... (char *)&A[0] + 1 */
3683 if (!integer_zerop (fold_build2_loc (loc, TRUNC_MOD_EXPR, sizetype,
3684 rhs, TYPE_SIZE_UNIT (type))))
3685 return NULL_TREE;
3686 /* Make sure to treat the second operand of POINTER_PLUS_EXPR
3687 as signed. */
3688 rhs = fold_build2_loc (loc, EXACT_DIV_EXPR, ssizetype, rhs,
3689 TYPE_SIZE_UNIT (type));
3690 t = size_binop_loc (loc, PLUS_EXPR, rhs, t);
3691 t = build4_loc (loc, ARRAY_REF, type, TREE_OPERAND (lhs, 0),
3692 t, NULL_TREE, NULL_TREE);
3693 t = cp_build_addr_expr (t, tf_warning_or_error);
3694 t = cp_fold_convert (orig_type, t);
3695 return cxx_eval_constant_expression (ctx, t, vc_prvalue,
3696 non_constant_p, overflow_p);
3699 return NULL_TREE;
3702 /* Try to fold expressions like
3703 (struct S *) (&a[0].D.2378 + 12)
3704 into
3705 &MEM <struct T> [(void *)&a + 12B]
3706 This is something normally done by gimple_fold_stmt_to_constant_1
3707 on GIMPLE, but is undesirable on GENERIC if we are e.g. going to
3708 dereference the address because some details are lost.
3709 For pointer comparisons we want such folding though so that
3710 match.pd address_compare optimization works. */
3712 static tree
3713 cxx_maybe_fold_addr_pointer_plus (tree t)
3715 while (CONVERT_EXPR_P (t)
3716 && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (t, 0))))
3717 t = TREE_OPERAND (t, 0);
3718 if (TREE_CODE (t) != POINTER_PLUS_EXPR)
3719 return NULL_TREE;
3720 tree op0 = TREE_OPERAND (t, 0);
3721 tree op1 = TREE_OPERAND (t, 1);
3722 if (TREE_CODE (op1) != INTEGER_CST)
3723 return NULL_TREE;
3724 while (CONVERT_EXPR_P (op0)
3725 && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (op0, 0))))
3726 op0 = TREE_OPERAND (op0, 0);
3727 if (TREE_CODE (op0) != ADDR_EXPR)
3728 return NULL_TREE;
3729 op1 = fold_convert (ptr_type_node, op1);
3730 tree r = fold_build2 (MEM_REF, TREE_TYPE (TREE_TYPE (op0)), op0, op1);
3731 return build1_loc (EXPR_LOCATION (t), ADDR_EXPR, TREE_TYPE (op0), r);
3734 /* Subroutine of cxx_eval_constant_expression.
3735 Like cxx_eval_unary_expression, except for binary expressions. */
3737 static tree
3738 cxx_eval_binary_expression (const constexpr_ctx *ctx, tree t,
3739 value_cat lval,
3740 bool *non_constant_p, bool *overflow_p)
3742 tree r = NULL_TREE;
3743 tree orig_lhs = TREE_OPERAND (t, 0);
3744 tree orig_rhs = TREE_OPERAND (t, 1);
3745 tree lhs, rhs;
3746 lhs = cxx_eval_constant_expression (ctx, orig_lhs, vc_prvalue,
3747 non_constant_p, overflow_p);
3748 /* Don't VERIFY_CONSTANT here, it's unnecessary and will break pointer
3749 subtraction. */
3750 if (*non_constant_p)
3751 return t;
3752 rhs = cxx_eval_constant_expression (ctx, orig_rhs, vc_prvalue,
3753 non_constant_p, overflow_p);
3754 if (*non_constant_p)
3755 return t;
3757 location_t loc = EXPR_LOCATION (t);
3758 enum tree_code code = TREE_CODE (t);
3759 tree type = TREE_TYPE (t);
3761 if (code == EQ_EXPR || code == NE_EXPR)
3763 bool is_code_eq = (code == EQ_EXPR);
3765 if (TREE_CODE (lhs) == PTRMEM_CST
3766 && TREE_CODE (rhs) == PTRMEM_CST)
3768 tree lmem = PTRMEM_CST_MEMBER (lhs);
3769 tree rmem = PTRMEM_CST_MEMBER (rhs);
3770 bool eq;
3771 if (TREE_CODE (lmem) == TREE_CODE (rmem)
3772 && TREE_CODE (lmem) == FIELD_DECL
3773 && TREE_CODE (DECL_CONTEXT (lmem)) == UNION_TYPE
3774 && same_type_p (DECL_CONTEXT (lmem),
3775 DECL_CONTEXT (rmem)))
3776 /* If both refer to (possibly different) members of the same union
3777 (12.3), they compare equal. */
3778 eq = true;
3779 else
3780 eq = cp_tree_equal (lhs, rhs);
3781 r = constant_boolean_node (eq == is_code_eq, type);
3783 else if ((TREE_CODE (lhs) == PTRMEM_CST
3784 || TREE_CODE (rhs) == PTRMEM_CST)
3785 && (null_member_pointer_value_p (lhs)
3786 || null_member_pointer_value_p (rhs)))
3787 r = constant_boolean_node (!is_code_eq, type);
3788 else if (TREE_CODE (lhs) == PTRMEM_CST)
3789 lhs = cplus_expand_constant (lhs);
3790 else if (TREE_CODE (rhs) == PTRMEM_CST)
3791 rhs = cplus_expand_constant (rhs);
3793 if (r == NULL_TREE
3794 && TREE_CODE_CLASS (code) == tcc_comparison
3795 && POINTER_TYPE_P (TREE_TYPE (lhs)))
3797 if (tree lhso = cxx_maybe_fold_addr_pointer_plus (lhs))
3798 lhs = fold_convert (TREE_TYPE (lhs), lhso);
3799 if (tree rhso = cxx_maybe_fold_addr_pointer_plus (rhs))
3800 rhs = fold_convert (TREE_TYPE (rhs), rhso);
3802 if (code == POINTER_PLUS_EXPR && !*non_constant_p
3803 && integer_zerop (lhs) && !integer_zerop (rhs))
3805 if (!ctx->quiet)
3806 error ("arithmetic involving a null pointer in %qE", lhs);
3807 *non_constant_p = true;
3808 return t;
3810 else if (code == POINTER_PLUS_EXPR)
3811 r = cxx_fold_pointer_plus_expression (ctx, t, lhs, rhs, non_constant_p,
3812 overflow_p);
3813 else if (code == SPACESHIP_EXPR)
3815 r = genericize_spaceship (loc, type, lhs, rhs);
3816 return cxx_eval_constant_expression (ctx, r, lval, non_constant_p,
3817 overflow_p);
3820 if (r == NULL_TREE)
3822 if (ctx->manifestly_const_eval == mce_true
3823 && (flag_constexpr_fp_except
3824 || TREE_CODE (type) != REAL_TYPE))
3826 auto ofcc = make_temp_override (folding_cxx_constexpr, true);
3827 r = fold_binary_initializer_loc (loc, code, type, lhs, rhs);
3829 else
3830 r = fold_binary_loc (loc, code, type, lhs, rhs);
3833 if (r == NULL_TREE
3834 && (code == LSHIFT_EXPR || code == RSHIFT_EXPR)
3835 && TREE_CODE (lhs) == INTEGER_CST
3836 && TREE_CODE (rhs) == INTEGER_CST
3837 && wi::neg_p (wi::to_wide (rhs)))
3839 /* For diagnostics and -fpermissive emulate previous behavior of
3840 handling shifts by negative amount. */
3841 tree nrhs = const_unop (NEGATE_EXPR, TREE_TYPE (rhs), rhs);
3842 if (nrhs)
3843 r = fold_binary_loc (loc,
3844 code == LSHIFT_EXPR ? RSHIFT_EXPR : LSHIFT_EXPR,
3845 type, lhs, nrhs);
3848 if (r == NULL_TREE)
3850 if (lhs == orig_lhs && rhs == orig_rhs)
3851 r = t;
3852 else
3853 r = build2_loc (loc, code, type, lhs, rhs);
3855 else if (cxx_eval_check_shift_p (loc, ctx, code, type, lhs, rhs))
3856 *non_constant_p = true;
3857 /* Don't VERIFY_CONSTANT if this might be dealing with a pointer to
3858 a local array in a constexpr function. */
3859 bool ptr = INDIRECT_TYPE_P (TREE_TYPE (lhs));
3860 if (!ptr)
3861 VERIFY_CONSTANT (r);
3862 return r;
3865 /* Subroutine of cxx_eval_constant_expression.
3866 Attempt to evaluate condition expressions. */
3868 static tree
3869 cxx_eval_conditional_expression (const constexpr_ctx *ctx, tree t,
3870 value_cat lval,
3871 bool *non_constant_p, bool *overflow_p,
3872 tree *jump_target)
3874 tree val = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
3875 vc_prvalue,
3876 non_constant_p, overflow_p);
3877 VERIFY_CONSTANT (val);
3878 if (TREE_CODE (t) == IF_STMT && IF_STMT_CONSTEVAL_P (t))
3880 /* Evaluate the condition as if it was
3881 if (__builtin_is_constant_evaluated ()), i.e. defer it if not
3882 ctx->manifestly_const_eval (as sometimes we try to constant evaluate
3883 without manifestly_const_eval even expressions or parts thereof which
3884 will later be manifestly const_eval evaluated), otherwise fold it to
3885 true. */
3886 if (ctx->manifestly_const_eval == mce_unknown)
3888 *non_constant_p = true;
3889 return t;
3891 val = constant_boolean_node (ctx->manifestly_const_eval == mce_true,
3892 boolean_type_node);
3894 /* Don't VERIFY_CONSTANT the other operands. */
3895 const bool zero_p = integer_zerop (val);
3896 if (zero_p)
3897 val = TREE_OPERAND (t, 2);
3898 else
3899 val = TREE_OPERAND (t, 1);
3900 if (TREE_CODE (t) == IF_STMT && !val)
3901 val = void_node;
3903 /* P2564: a subexpression of a manifestly constant-evaluated expression
3904 or conversion is an immediate function context. */
3905 if (ctx->manifestly_const_eval != mce_true
3906 && !in_immediate_context ()
3907 && cp_fold_immediate (&TREE_OPERAND (t, zero_p ? 1 : 2),
3908 ctx->manifestly_const_eval))
3910 *non_constant_p = true;
3911 return t;
3914 /* A TARGET_EXPR may be nested inside another TARGET_EXPR, but still
3915 serve as the initializer for the same object as the outer TARGET_EXPR,
3916 as in
3917 A a = true ? A{} : A{};
3918 so strip the inner TARGET_EXPR so we don't materialize a temporary. */
3919 if (TREE_CODE (val) == TARGET_EXPR)
3920 val = TARGET_EXPR_INITIAL (val);
3921 return cxx_eval_constant_expression (ctx, val, lval, non_constant_p,
3922 overflow_p, jump_target);
3925 /* Subroutine of cxx_eval_constant_expression.
3926 Attempt to evaluate vector condition expressions. Unlike
3927 cxx_eval_conditional_expression, VEC_COND_EXPR acts like a normal
3928 ternary arithmetics operation, where all 3 arguments have to be
3929 evaluated as constants and then folding computes the result from
3930 them. */
3932 static tree
3933 cxx_eval_vector_conditional_expression (const constexpr_ctx *ctx, tree t,
3934 bool *non_constant_p, bool *overflow_p)
3936 tree arg1 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
3937 vc_prvalue,
3938 non_constant_p, overflow_p);
3939 VERIFY_CONSTANT (arg1);
3940 tree arg2 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
3941 vc_prvalue,
3942 non_constant_p, overflow_p);
3943 VERIFY_CONSTANT (arg2);
3944 tree arg3 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 2),
3945 vc_prvalue,
3946 non_constant_p, overflow_p);
3947 VERIFY_CONSTANT (arg3);
3948 location_t loc = EXPR_LOCATION (t);
3949 tree type = TREE_TYPE (t);
3950 tree r = fold_ternary_loc (loc, VEC_COND_EXPR, type, arg1, arg2, arg3);
3951 if (r == NULL_TREE)
3953 if (arg1 == TREE_OPERAND (t, 0)
3954 && arg2 == TREE_OPERAND (t, 1)
3955 && arg3 == TREE_OPERAND (t, 2))
3956 r = t;
3957 else
3958 r = build3_loc (loc, VEC_COND_EXPR, type, arg1, arg2, arg3);
3960 VERIFY_CONSTANT (r);
3961 return r;
3964 /* Returns less than, equal to, or greater than zero if KEY is found to be
3965 less than, to match, or to be greater than the constructor_elt's INDEX. */
3967 static int
3968 array_index_cmp (tree key, tree index)
3970 gcc_assert (TREE_CODE (key) == INTEGER_CST);
3972 switch (TREE_CODE (index))
3974 case INTEGER_CST:
3975 return tree_int_cst_compare (key, index);
3976 case RANGE_EXPR:
3978 tree lo = TREE_OPERAND (index, 0);
3979 tree hi = TREE_OPERAND (index, 1);
3980 if (tree_int_cst_lt (key, lo))
3981 return -1;
3982 else if (tree_int_cst_lt (hi, key))
3983 return 1;
3984 else
3985 return 0;
3987 default:
3988 gcc_unreachable ();
3992 /* Returns the index of the constructor_elt of ARY which matches DINDEX, or -1
3993 if none. If INSERT is true, insert a matching element rather than fail. */
3995 static HOST_WIDE_INT
3996 find_array_ctor_elt (tree ary, tree dindex, bool insert)
3998 if (tree_int_cst_sgn (dindex) < 0)
3999 return -1;
4001 unsigned HOST_WIDE_INT i = tree_to_uhwi (dindex);
4002 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ary);
4003 unsigned HOST_WIDE_INT len = vec_safe_length (elts);
4005 unsigned HOST_WIDE_INT end = len;
4006 unsigned HOST_WIDE_INT begin = 0;
4008 /* If the last element of the CONSTRUCTOR has its own index, we can assume
4009 that the same is true of the other elements and index directly. */
4010 if (end > 0)
4012 tree cindex = (*elts)[end - 1].index;
4013 if (cindex == NULL_TREE)
4015 /* Verify that if the last index is missing, all indexes
4016 are missing. */
4017 if (flag_checking)
4018 for (unsigned int j = 0; j < len - 1; ++j)
4019 gcc_assert ((*elts)[j].index == NULL_TREE);
4020 if (i < end)
4021 return i;
4022 else
4024 begin = end;
4025 if (i == end)
4026 /* If the element is to be added right at the end,
4027 make sure it is added with cleared index too. */
4028 dindex = NULL_TREE;
4029 else if (insert)
4030 /* Otherwise, in order not to break the assumption
4031 that CONSTRUCTOR either has all indexes or none,
4032 we need to add indexes to all elements. */
4033 for (unsigned int j = 0; j < len; ++j)
4034 (*elts)[j].index = build_int_cst (TREE_TYPE (dindex), j);
4037 else if (TREE_CODE (cindex) == INTEGER_CST
4038 && compare_tree_int (cindex, end - 1) == 0)
4040 if (i < end)
4041 return i;
4042 else
4043 begin = end;
4047 /* Otherwise, find a matching index by means of a binary search. */
4048 while (begin != end)
4050 unsigned HOST_WIDE_INT middle = (begin + end) / 2;
4051 constructor_elt &elt = (*elts)[middle];
4052 tree idx = elt.index;
4054 int cmp = array_index_cmp (dindex, idx);
4055 if (cmp < 0)
4056 end = middle;
4057 else if (cmp > 0)
4058 begin = middle + 1;
4059 else
4061 if (insert && TREE_CODE (idx) == RANGE_EXPR)
4063 /* We need to split the range. */
4064 constructor_elt e;
4065 tree lo = TREE_OPERAND (idx, 0);
4066 tree hi = TREE_OPERAND (idx, 1);
4067 tree value = elt.value;
4068 dindex = fold_convert (sizetype, dindex);
4069 if (tree_int_cst_lt (lo, dindex))
4071 /* There are still some lower elts; shorten the range. */
4072 tree new_hi = int_const_binop (MINUS_EXPR, dindex,
4073 size_one_node);
4074 if (tree_int_cst_equal (lo, new_hi))
4075 /* Only one element left, no longer a range. */
4076 elt.index = lo;
4077 else
4078 TREE_OPERAND (idx, 1) = new_hi;
4079 /* Append the element we want to insert. */
4080 ++middle;
4081 e.index = dindex;
4082 e.value = unshare_constructor (value);
4083 vec_safe_insert (CONSTRUCTOR_ELTS (ary), middle, e);
4085 else
4086 /* No lower elts, the range elt is now ours. */
4087 elt.index = dindex;
4089 if (tree_int_cst_lt (dindex, hi))
4091 /* There are still some higher elts; append a range. */
4092 tree new_lo = int_const_binop (PLUS_EXPR, dindex,
4093 size_one_node);
4094 if (tree_int_cst_equal (new_lo, hi))
4095 e.index = hi;
4096 else
4097 e.index = build2 (RANGE_EXPR, sizetype, new_lo, hi);
4098 e.value = unshare_constructor (value);
4099 vec_safe_insert (CONSTRUCTOR_ELTS (ary), middle + 1, e);
4102 return middle;
4106 if (insert)
4108 constructor_elt e = { dindex, NULL_TREE };
4109 vec_safe_insert (CONSTRUCTOR_ELTS (ary), end, e);
4110 return end;
4113 return -1;
4116 /* Return a pointer to the constructor_elt of CTOR which matches INDEX. If no
4117 matching constructor_elt exists, then add one to CTOR.
4119 As an optimization, if POS_HINT is non-negative then it is used as a guess
4120 for the (integer) index of the matching constructor_elt within CTOR. */
4122 static constructor_elt *
4123 get_or_insert_ctor_field (tree ctor, tree index, int pos_hint = -1)
4125 /* Check the hint first. */
4126 if (pos_hint >= 0 && (unsigned)pos_hint < CONSTRUCTOR_NELTS (ctor)
4127 && CONSTRUCTOR_ELT (ctor, pos_hint)->index == index)
4128 return CONSTRUCTOR_ELT (ctor, pos_hint);
4130 tree type = TREE_TYPE (ctor);
4131 if (TREE_CODE (type) == VECTOR_TYPE && index == NULL_TREE)
4133 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (ctor), index, NULL_TREE);
4134 return &CONSTRUCTOR_ELTS (ctor)->last();
4136 else if (TREE_CODE (type) == ARRAY_TYPE || TREE_CODE (type) == VECTOR_TYPE)
4138 if (TREE_CODE (index) == RANGE_EXPR)
4140 /* Support for RANGE_EXPR index lookups is currently limited to
4141 accessing an existing element via POS_HINT, or appending a new
4142 element to the end of CTOR. ??? Support for other access
4143 patterns may also be needed. */
4144 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ctor);
4145 if (vec_safe_length (elts))
4147 tree lo = TREE_OPERAND (index, 0);
4148 gcc_assert (array_index_cmp (elts->last().index, lo) < 0);
4150 CONSTRUCTOR_APPEND_ELT (elts, index, NULL_TREE);
4151 return &elts->last();
4154 HOST_WIDE_INT i = find_array_ctor_elt (ctor, index, /*insert*/true);
4155 gcc_assert (i >= 0);
4156 constructor_elt *cep = CONSTRUCTOR_ELT (ctor, i);
4157 gcc_assert (cep->index == NULL_TREE
4158 || TREE_CODE (cep->index) != RANGE_EXPR);
4159 return cep;
4161 else
4163 gcc_assert (TREE_CODE (index) == FIELD_DECL
4164 && (same_type_ignoring_top_level_qualifiers_p
4165 (DECL_CONTEXT (index), TREE_TYPE (ctor))));
4167 /* We must keep the CONSTRUCTOR's ELTS in FIELD order.
4168 Usually we meet initializers in that order, but it is
4169 possible for base types to be placed not in program
4170 order. */
4171 tree fields = TYPE_FIELDS (DECL_CONTEXT (index));
4172 unsigned HOST_WIDE_INT idx = 0;
4173 constructor_elt *cep = NULL;
4175 /* Check if we're changing the active member of a union. */
4176 if (TREE_CODE (type) == UNION_TYPE && CONSTRUCTOR_NELTS (ctor)
4177 && CONSTRUCTOR_ELT (ctor, 0)->index != index)
4178 vec_safe_truncate (CONSTRUCTOR_ELTS (ctor), 0);
4179 /* If the bit offset of INDEX is larger than that of the last
4180 constructor_elt, then we can just immediately append a new
4181 constructor_elt to the end of CTOR. */
4182 else if (CONSTRUCTOR_NELTS (ctor)
4183 && tree_int_cst_compare (bit_position (index),
4184 bit_position (CONSTRUCTOR_ELTS (ctor)
4185 ->last().index)) > 0)
4187 idx = CONSTRUCTOR_NELTS (ctor);
4188 goto insert;
4191 /* Otherwise, we need to iterate over CTOR to find or insert INDEX
4192 appropriately. */
4194 for (; vec_safe_iterate (CONSTRUCTOR_ELTS (ctor), idx, &cep);
4195 idx++, fields = DECL_CHAIN (fields))
4197 if (index == cep->index)
4198 goto found;
4200 /* The field we're initializing must be on the field
4201 list. Look to see if it is present before the
4202 field the current ELT initializes. */
4203 for (; fields != cep->index; fields = DECL_CHAIN (fields))
4204 if (index == fields)
4205 goto insert;
4207 /* We fell off the end of the CONSTRUCTOR, so insert a new
4208 entry at the end. */
4210 insert:
4212 constructor_elt ce = { index, NULL_TREE };
4214 vec_safe_insert (CONSTRUCTOR_ELTS (ctor), idx, ce);
4215 cep = CONSTRUCTOR_ELT (ctor, idx);
4217 found:;
4219 return cep;
4223 /* Under the control of CTX, issue a detailed diagnostic for
4224 an out-of-bounds subscript INDEX into the expression ARRAY. */
4226 static void
4227 diag_array_subscript (location_t loc, const constexpr_ctx *ctx, tree array, tree index)
4229 if (!ctx->quiet)
4231 tree arraytype = TREE_TYPE (array);
4233 /* Convert the unsigned array subscript to a signed integer to avoid
4234 printing huge numbers for small negative values. */
4235 tree sidx = fold_convert (ssizetype, index);
4236 STRIP_ANY_LOCATION_WRAPPER (array);
4237 if (DECL_P (array))
4239 auto_diagnostic_group d;
4240 if (TYPE_DOMAIN (arraytype))
4241 error_at (loc, "array subscript value %qE is outside the bounds "
4242 "of array %qD of type %qT", sidx, array, arraytype);
4243 else
4244 error_at (loc, "nonzero array subscript %qE is used with array %qD of "
4245 "type %qT with unknown bounds", sidx, array, arraytype);
4246 inform (DECL_SOURCE_LOCATION (array), "declared here");
4248 else if (TYPE_DOMAIN (arraytype))
4249 error_at (loc, "array subscript value %qE is outside the bounds "
4250 "of array type %qT", sidx, arraytype);
4251 else
4252 error_at (loc, "nonzero array subscript %qE is used with array of type %qT "
4253 "with unknown bounds", sidx, arraytype);
4257 /* Return the number of elements for TYPE (which is an ARRAY_TYPE or
4258 a VECTOR_TYPE). */
4260 static tree
4261 get_array_or_vector_nelts (const constexpr_ctx *ctx, tree type,
4262 bool *non_constant_p, bool *overflow_p)
4264 tree nelts;
4265 if (TREE_CODE (type) == ARRAY_TYPE)
4267 if (TYPE_DOMAIN (type))
4268 nelts = array_type_nelts_top (type);
4269 else
4270 nelts = size_zero_node;
4272 else if (VECTOR_TYPE_P (type))
4273 nelts = size_int (TYPE_VECTOR_SUBPARTS (type));
4274 else
4275 gcc_unreachable ();
4277 /* For VLAs, the number of elements won't be an integer constant. */
4278 nelts = cxx_eval_constant_expression (ctx, nelts, vc_prvalue,
4279 non_constant_p, overflow_p);
4280 return nelts;
4283 /* Extract element INDEX consisting of CHARS_PER_ELT chars from
4284 STRING_CST STRING. */
4286 static tree
4287 extract_string_elt (tree string, unsigned chars_per_elt, unsigned index)
4289 tree type = cv_unqualified (TREE_TYPE (TREE_TYPE (string)));
4290 tree r;
4292 if (chars_per_elt == 1)
4293 r = build_int_cst (type, TREE_STRING_POINTER (string)[index]);
4294 else
4296 const unsigned char *ptr
4297 = ((const unsigned char *)TREE_STRING_POINTER (string)
4298 + index * chars_per_elt);
4299 r = native_interpret_expr (type, ptr, chars_per_elt);
4301 return r;
4304 /* Subroutine of cxx_eval_array_reference. T is an ARRAY_REF; evaluate the
4305 subscript, diagnose any problems with it, and return the result. */
4307 static tree
4308 eval_and_check_array_index (const constexpr_ctx *ctx,
4309 tree t, bool allow_one_past,
4310 bool *non_constant_p, bool *overflow_p)
4312 location_t loc = cp_expr_loc_or_input_loc (t);
4313 tree ary = TREE_OPERAND (t, 0);
4314 t = TREE_OPERAND (t, 1);
4315 tree index = cxx_eval_constant_expression (ctx, t, vc_prvalue,
4316 non_constant_p, overflow_p);
4317 VERIFY_CONSTANT (index);
4319 if (!tree_fits_shwi_p (index)
4320 || tree_int_cst_sgn (index) < 0)
4322 diag_array_subscript (loc, ctx, ary, index);
4323 *non_constant_p = true;
4324 return t;
4327 tree nelts = get_array_or_vector_nelts (ctx, TREE_TYPE (ary), non_constant_p,
4328 overflow_p);
4329 VERIFY_CONSTANT (nelts);
4330 if (allow_one_past
4331 ? !tree_int_cst_le (index, nelts)
4332 : !tree_int_cst_lt (index, nelts))
4334 diag_array_subscript (loc, ctx, ary, index);
4335 *non_constant_p = true;
4336 return t;
4339 return index;
4342 /* Subroutine of cxx_eval_constant_expression.
4343 Attempt to reduce a reference to an array slot. */
4345 static tree
4346 cxx_eval_array_reference (const constexpr_ctx *ctx, tree t,
4347 value_cat lval,
4348 bool *non_constant_p, bool *overflow_p)
4350 tree oldary = TREE_OPERAND (t, 0);
4351 tree ary = cxx_eval_constant_expression (ctx, oldary,
4352 lval,
4353 non_constant_p, overflow_p);
4354 if (*non_constant_p)
4355 return t;
4356 if (!lval
4357 && TREE_CODE (ary) == VIEW_CONVERT_EXPR
4358 && VECTOR_TYPE_P (TREE_TYPE (TREE_OPERAND (ary, 0)))
4359 && TREE_TYPE (t) == TREE_TYPE (TREE_TYPE (TREE_OPERAND (ary, 0))))
4360 ary = TREE_OPERAND (ary, 0);
4362 tree oldidx = TREE_OPERAND (t, 1);
4363 tree index = eval_and_check_array_index (ctx, t, lval,
4364 non_constant_p, overflow_p);
4365 if (*non_constant_p)
4366 return t;
4368 if (lval && ary == oldary && index == oldidx)
4369 return t;
4370 else if (lval == vc_discard)
4371 return t;
4372 else if (lval)
4373 return build4 (ARRAY_REF, TREE_TYPE (t), ary, index, NULL, NULL);
4375 unsigned len = 0, elem_nchars = 1;
4376 tree elem_type = TREE_TYPE (TREE_TYPE (ary));
4377 if (TREE_CODE (ary) == CONSTRUCTOR)
4378 len = CONSTRUCTOR_NELTS (ary);
4379 else if (TREE_CODE (ary) == STRING_CST)
4381 elem_nchars = (TYPE_PRECISION (elem_type)
4382 / TYPE_PRECISION (char_type_node));
4383 len = (unsigned) TREE_STRING_LENGTH (ary) / elem_nchars;
4385 else if (TREE_CODE (ary) == VECTOR_CST)
4386 /* We don't create variable-length VECTOR_CSTs. */
4387 len = VECTOR_CST_NELTS (ary).to_constant ();
4388 else
4390 /* We can't do anything with other tree codes, so use
4391 VERIFY_CONSTANT to complain and fail. */
4392 VERIFY_CONSTANT (ary);
4393 gcc_unreachable ();
4396 bool found;
4397 HOST_WIDE_INT i = 0;
4398 if (TREE_CODE (ary) == CONSTRUCTOR)
4400 HOST_WIDE_INT ix = find_array_ctor_elt (ary, index);
4401 found = (ix >= 0);
4402 if (found)
4403 i = ix;
4405 else
4407 i = tree_to_shwi (index);
4408 found = (i < len);
4411 if (found)
4413 tree r;
4414 if (TREE_CODE (ary) == CONSTRUCTOR)
4415 r = (*CONSTRUCTOR_ELTS (ary))[i].value;
4416 else if (TREE_CODE (ary) == VECTOR_CST)
4417 r = VECTOR_CST_ELT (ary, i);
4418 else
4419 r = extract_string_elt (ary, elem_nchars, i);
4421 if (r)
4422 /* Don't VERIFY_CONSTANT here. */
4423 return r;
4425 /* Otherwise the element doesn't have a value yet. */
4428 /* Not found. */
4430 if (is_really_empty_class (elem_type, /*ignore_vptr*/false))
4431 return build_constructor (elem_type, NULL);
4433 if (TREE_CODE (ary) == CONSTRUCTOR
4434 && CONSTRUCTOR_NO_CLEARING (ary))
4436 /* 'ary' is part of the aggregate initializer we're currently
4437 building; if there's no initializer for this element yet,
4438 that's an error. */
4439 if (!ctx->quiet)
4440 error ("accessing uninitialized array element");
4441 *non_constant_p = true;
4442 return t;
4445 /* If it's within the array bounds but doesn't have an explicit
4446 initializer, it's initialized from {}. But use build_value_init
4447 directly for non-aggregates to avoid creating a garbage CONSTRUCTOR. */
4448 tree val;
4449 constexpr_ctx new_ctx;
4450 if (CP_AGGREGATE_TYPE_P (elem_type))
4452 tree empty_ctor = build_constructor (init_list_type_node, NULL);
4453 val = digest_init (elem_type, empty_ctor, tf_warning_or_error);
4455 else
4456 val = build_value_init (elem_type, tf_warning_or_error);
4458 /* Create a new constructor only if we don't already have a suitable one. */
4459 const bool new_ctor = (!SCALAR_TYPE_P (elem_type)
4460 && (!ctx->ctor
4461 || !same_type_ignoring_top_level_qualifiers_p
4462 (elem_type, TREE_TYPE (ctx->ctor))));
4463 if (new_ctor)
4465 new_ctx = *ctx;
4466 /* We clear the object here. We used to replace it with T, but that
4467 caused problems (101371, 108158); and anyway, T is the initializer,
4468 not the target object. */
4469 new_ctx.object = NULL_TREE;
4470 new_ctx.ctor = build_constructor (elem_type, NULL);
4471 ctx = &new_ctx;
4473 t = cxx_eval_constant_expression (ctx, val, lval, non_constant_p,
4474 overflow_p);
4475 if (new_ctor && t != ctx->ctor)
4476 free_constructor (ctx->ctor);
4477 return t;
4480 /* Subroutine of cxx_eval_constant_expression.
4481 Attempt to reduce a field access of a value of class type. */
4483 static tree
4484 cxx_eval_component_reference (const constexpr_ctx *ctx, tree t,
4485 value_cat lval,
4486 bool *non_constant_p, bool *overflow_p)
4488 unsigned HOST_WIDE_INT i;
4489 tree field;
4490 tree value;
4491 tree part = TREE_OPERAND (t, 1);
4492 tree orig_whole = TREE_OPERAND (t, 0);
4493 tree whole = cxx_eval_constant_expression (ctx, orig_whole,
4494 lval,
4495 non_constant_p, overflow_p);
4496 if (*non_constant_p)
4497 return t;
4498 if (INDIRECT_REF_P (whole)
4499 && integer_zerop (TREE_OPERAND (whole, 0)))
4501 if (!ctx->quiet)
4502 error ("dereferencing a null pointer in %qE", orig_whole);
4503 *non_constant_p = true;
4504 return t;
4507 if (TREE_CODE (whole) == PTRMEM_CST)
4508 whole = cplus_expand_constant (whole);
4509 if (whole == orig_whole)
4510 return t;
4511 if (lval == vc_discard)
4512 return t;
4513 if (lval)
4514 return fold_build3 (COMPONENT_REF, TREE_TYPE (t),
4515 whole, part, NULL_TREE);
4516 /* Don't VERIFY_CONSTANT here; we only want to check that we got a
4517 CONSTRUCTOR. */
4518 if (TREE_CODE (whole) != CONSTRUCTOR)
4520 if (!ctx->quiet)
4521 error ("%qE is not a constant expression", orig_whole);
4522 *non_constant_p = true;
4523 return t;
4525 if ((cxx_dialect < cxx14 || CONSTRUCTOR_MUTABLE_POISON (whole))
4526 && DECL_MUTABLE_P (part))
4528 if (!ctx->quiet)
4529 error ("mutable %qD is not usable in a constant expression", part);
4530 *non_constant_p = true;
4531 return t;
4534 bool pmf = TYPE_PTRMEMFUNC_P (TREE_TYPE (whole));
4535 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
4537 /* Use name match for PMF fields, as a variant will have a
4538 different FIELD_DECL with a different type. */
4539 if (pmf ? DECL_NAME (field) == DECL_NAME (part)
4540 : field == part)
4542 if (value)
4544 STRIP_ANY_LOCATION_WRAPPER (value);
4545 return value;
4547 else
4548 /* We're in the middle of initializing it. */
4549 break;
4552 if (TREE_CODE (TREE_TYPE (whole)) == UNION_TYPE)
4554 if (CONSTRUCTOR_NELTS (whole) > 0)
4556 /* DR 1188 says we don't have to deal with this. */
4557 if (!ctx->quiet)
4559 constructor_elt *cep = CONSTRUCTOR_ELT (whole, 0);
4560 if (cep->value == NULL_TREE)
4561 error ("accessing uninitialized member %qD", part);
4562 else
4563 error ("accessing %qD member instead of initialized %qD member "
4564 "in constant expression", part, cep->index);
4566 *non_constant_p = true;
4567 return t;
4569 else if (!CONSTRUCTOR_NO_CLEARING (whole))
4571 /* Value-initialized union, check if looking at the first member. */
4572 tree first = next_aggregate_field (TYPE_FIELDS (TREE_TYPE (whole)));
4573 if (first != part)
4575 if (!ctx->quiet)
4576 error ("accessing %qD member instead of initialized %qD "
4577 "member in constant expression", part, first);
4578 *non_constant_p = true;
4579 return t;
4584 /* We only create a CONSTRUCTOR for a subobject when we modify it, so empty
4585 classes never get represented; throw together a value now. */
4586 if (is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
4587 return build_constructor (TREE_TYPE (t), NULL);
4589 gcc_assert (DECL_CONTEXT (part) == TYPE_MAIN_VARIANT (TREE_TYPE (whole)));
4591 if (CONSTRUCTOR_NO_CLEARING (whole))
4593 /* 'whole' is part of the aggregate initializer we're currently
4594 building; if there's no initializer for this member yet, that's an
4595 error. */
4596 if (!ctx->quiet)
4597 error ("accessing uninitialized member %qD", part);
4598 *non_constant_p = true;
4599 return t;
4602 /* If there's no explicit init for this field, it's value-initialized. */
4603 value = build_value_init (TREE_TYPE (t), tf_warning_or_error);
4604 return cxx_eval_constant_expression (ctx, value,
4605 lval,
4606 non_constant_p, overflow_p);
4609 /* Subroutine of cxx_eval_constant_expression.
4610 Attempt to reduce a field access of a value of class type that is
4611 expressed as a BIT_FIELD_REF. */
4613 static tree
4614 cxx_eval_bit_field_ref (const constexpr_ctx *ctx, tree t,
4615 value_cat lval,
4616 bool *non_constant_p, bool *overflow_p)
4618 tree orig_whole = TREE_OPERAND (t, 0);
4619 tree retval, fldval, utype, mask;
4620 bool fld_seen = false;
4621 HOST_WIDE_INT istart, isize;
4622 tree whole = cxx_eval_constant_expression (ctx, orig_whole,
4623 lval,
4624 non_constant_p, overflow_p);
4625 tree start, field, value;
4626 unsigned HOST_WIDE_INT i;
4628 if (whole == orig_whole)
4629 return t;
4630 /* Don't VERIFY_CONSTANT here; we only want to check that we got a
4631 CONSTRUCTOR. */
4632 if (!*non_constant_p
4633 && TREE_CODE (whole) != VECTOR_CST
4634 && TREE_CODE (whole) != CONSTRUCTOR)
4636 if (!ctx->quiet)
4637 error ("%qE is not a constant expression", orig_whole);
4638 *non_constant_p = true;
4640 if (*non_constant_p)
4641 return t;
4643 if (TREE_CODE (whole) == VECTOR_CST || !INTEGRAL_TYPE_P (TREE_TYPE (t)))
4645 if (tree r = fold_ternary (BIT_FIELD_REF, TREE_TYPE (t), whole,
4646 TREE_OPERAND (t, 1), TREE_OPERAND (t, 2)))
4647 return r;
4648 if (!ctx->quiet)
4649 error ("%qE is not a constant expression", orig_whole);
4650 *non_constant_p = true;
4651 return t;
4654 start = TREE_OPERAND (t, 2);
4655 istart = tree_to_shwi (start);
4656 isize = tree_to_shwi (TREE_OPERAND (t, 1));
4657 utype = TREE_TYPE (t);
4658 if (!TYPE_UNSIGNED (utype))
4659 utype = build_nonstandard_integer_type (TYPE_PRECISION (utype), 1);
4660 retval = build_int_cst (utype, 0);
4661 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
4663 tree bitpos = bit_position (field);
4664 STRIP_ANY_LOCATION_WRAPPER (value);
4665 if (bitpos == start && DECL_SIZE (field) == TREE_OPERAND (t, 1))
4666 return value;
4667 if (TREE_CODE (TREE_TYPE (field)) == INTEGER_TYPE
4668 && TREE_CODE (value) == INTEGER_CST
4669 && tree_fits_shwi_p (bitpos)
4670 && tree_fits_shwi_p (DECL_SIZE (field)))
4672 HOST_WIDE_INT bit = tree_to_shwi (bitpos);
4673 HOST_WIDE_INT sz = tree_to_shwi (DECL_SIZE (field));
4674 HOST_WIDE_INT shift;
4675 if (bit >= istart && bit + sz <= istart + isize)
4677 fldval = fold_convert (utype, value);
4678 mask = build_int_cst_type (utype, -1);
4679 mask = fold_build2 (LSHIFT_EXPR, utype, mask,
4680 size_int (TYPE_PRECISION (utype) - sz));
4681 mask = fold_build2 (RSHIFT_EXPR, utype, mask,
4682 size_int (TYPE_PRECISION (utype) - sz));
4683 fldval = fold_build2 (BIT_AND_EXPR, utype, fldval, mask);
4684 shift = bit - istart;
4685 if (BYTES_BIG_ENDIAN)
4686 shift = TYPE_PRECISION (utype) - shift - sz;
4687 fldval = fold_build2 (LSHIFT_EXPR, utype, fldval,
4688 size_int (shift));
4689 retval = fold_build2 (BIT_IOR_EXPR, utype, retval, fldval);
4690 fld_seen = true;
4694 if (fld_seen)
4695 return fold_convert (TREE_TYPE (t), retval);
4696 gcc_unreachable ();
4697 return error_mark_node;
4700 /* Helper for cxx_eval_bit_cast.
4701 Check [bit.cast]/3 rules, bit_cast is constexpr only if the To and From
4702 types and types of all subobjects have is_union_v<T>, is_pointer_v<T>,
4703 is_member_pointer_v<T>, is_volatile_v<T> false and has no non-static
4704 data members of reference type. */
4706 static bool
4707 check_bit_cast_type (const constexpr_ctx *ctx, location_t loc, tree type,
4708 tree orig_type)
4710 if (TREE_CODE (type) == UNION_TYPE)
4712 if (!ctx->quiet)
4714 if (type == orig_type)
4715 error_at (loc, "%qs is not a constant expression because %qT is "
4716 "a union type", "__builtin_bit_cast", type);
4717 else
4718 error_at (loc, "%qs is not a constant expression because %qT "
4719 "contains a union type", "__builtin_bit_cast",
4720 orig_type);
4722 return true;
4724 if (TREE_CODE (type) == POINTER_TYPE)
4726 if (!ctx->quiet)
4728 if (type == orig_type)
4729 error_at (loc, "%qs is not a constant expression because %qT is "
4730 "a pointer type", "__builtin_bit_cast", type);
4731 else
4732 error_at (loc, "%qs is not a constant expression because %qT "
4733 "contains a pointer type", "__builtin_bit_cast",
4734 orig_type);
4736 return true;
4738 if (TREE_CODE (type) == REFERENCE_TYPE)
4740 if (!ctx->quiet)
4742 if (type == orig_type)
4743 error_at (loc, "%qs is not a constant expression because %qT is "
4744 "a reference type", "__builtin_bit_cast", type);
4745 else
4746 error_at (loc, "%qs is not a constant expression because %qT "
4747 "contains a reference type", "__builtin_bit_cast",
4748 orig_type);
4750 return true;
4752 if (TYPE_PTRMEM_P (type))
4754 if (!ctx->quiet)
4756 if (type == orig_type)
4757 error_at (loc, "%qs is not a constant expression because %qT is "
4758 "a pointer to member type", "__builtin_bit_cast",
4759 type);
4760 else
4761 error_at (loc, "%qs is not a constant expression because %qT "
4762 "contains a pointer to member type",
4763 "__builtin_bit_cast", orig_type);
4765 return true;
4767 if (TYPE_VOLATILE (type))
4769 if (!ctx->quiet)
4771 if (type == orig_type)
4772 error_at (loc, "%qs is not a constant expression because %qT is "
4773 "volatile", "__builtin_bit_cast", type);
4774 else
4775 error_at (loc, "%qs is not a constant expression because %qT "
4776 "contains a volatile subobject",
4777 "__builtin_bit_cast", orig_type);
4779 return true;
4781 if (TREE_CODE (type) == RECORD_TYPE)
4782 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
4783 if (TREE_CODE (field) == FIELD_DECL
4784 && check_bit_cast_type (ctx, loc, TREE_TYPE (field), orig_type))
4785 return true;
4786 return false;
4789 /* Helper function for cxx_eval_bit_cast. For unsigned char or
4790 std::byte members of CONSTRUCTOR (recursively) if they contain
4791 some indeterminate bits (as set in MASK), remove the ctor elts,
4792 mark the CONSTRUCTOR as CONSTRUCTOR_NO_CLEARING and clear the
4793 bits in MASK. */
4795 static void
4796 clear_uchar_or_std_byte_in_mask (location_t loc, tree t, unsigned char *mask)
4798 if (TREE_CODE (t) != CONSTRUCTOR)
4799 return;
4801 unsigned i, j = 0;
4802 tree index, value;
4803 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (t), i, index, value)
4805 tree type = TREE_TYPE (value);
4806 if (TREE_CODE (TREE_TYPE (t)) != ARRAY_TYPE
4807 && DECL_BIT_FIELD_TYPE (index) != NULL_TREE)
4809 if (is_byte_access_type_not_plain_char (DECL_BIT_FIELD_TYPE (index)))
4811 HOST_WIDE_INT fldsz = TYPE_PRECISION (TREE_TYPE (index));
4812 gcc_assert (fldsz != 0);
4813 HOST_WIDE_INT pos = int_byte_position (index);
4814 HOST_WIDE_INT bpos
4815 = tree_to_uhwi (DECL_FIELD_BIT_OFFSET (index));
4816 bpos %= BITS_PER_UNIT;
4817 HOST_WIDE_INT end
4818 = ROUND_UP (bpos + fldsz, BITS_PER_UNIT) / BITS_PER_UNIT;
4819 gcc_assert (end == 1 || end == 2);
4820 unsigned char *p = mask + pos;
4821 unsigned char mask_save[2];
4822 mask_save[0] = mask[pos];
4823 mask_save[1] = end == 2 ? mask[pos + 1] : 0;
4824 if (BYTES_BIG_ENDIAN != WORDS_BIG_ENDIAN)
4825 sorry_at (loc, "PDP11 bit-field handling unsupported"
4826 " in %qs", "__builtin_bit_cast");
4827 else if (BYTES_BIG_ENDIAN)
4829 /* Big endian. */
4830 if (bpos + fldsz <= BITS_PER_UNIT)
4831 *p &= ~(((1 << fldsz) - 1)
4832 << (BITS_PER_UNIT - bpos - fldsz));
4833 else
4835 gcc_assert (bpos);
4836 *p &= ~(((1U << BITS_PER_UNIT) - 1) >> bpos);
4837 p++;
4838 fldsz -= BITS_PER_UNIT - bpos;
4839 gcc_assert (fldsz && fldsz < BITS_PER_UNIT);
4840 *p &= ((1U << BITS_PER_UNIT) - 1) >> fldsz;
4843 else
4845 /* Little endian. */
4846 if (bpos + fldsz <= BITS_PER_UNIT)
4847 *p &= ~(((1 << fldsz) - 1) << bpos);
4848 else
4850 gcc_assert (bpos);
4851 *p &= ~(((1 << BITS_PER_UNIT) - 1) << bpos);
4852 p++;
4853 fldsz -= BITS_PER_UNIT - bpos;
4854 gcc_assert (fldsz && fldsz < BITS_PER_UNIT);
4855 *p &= ~((1 << fldsz) - 1);
4858 if (mask_save[0] != mask[pos]
4859 || (end == 2 && mask_save[1] != mask[pos + 1]))
4861 CONSTRUCTOR_NO_CLEARING (t) = 1;
4862 continue;
4866 else if (is_byte_access_type_not_plain_char (type))
4868 HOST_WIDE_INT pos;
4869 if (TREE_CODE (TREE_TYPE (t)) == ARRAY_TYPE)
4870 pos = tree_to_shwi (index);
4871 else
4872 pos = int_byte_position (index);
4873 if (mask[pos])
4875 CONSTRUCTOR_NO_CLEARING (t) = 1;
4876 mask[pos] = 0;
4877 continue;
4880 if (TREE_CODE (value) == CONSTRUCTOR)
4882 HOST_WIDE_INT pos;
4883 if (TREE_CODE (TREE_TYPE (t)) == ARRAY_TYPE)
4884 pos = tree_to_shwi (index)
4885 * tree_to_shwi (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (t))));
4886 else
4887 pos = int_byte_position (index);
4888 clear_uchar_or_std_byte_in_mask (loc, value, mask + pos);
4890 if (i != j)
4892 CONSTRUCTOR_ELT (t, j)->index = index;
4893 CONSTRUCTOR_ELT (t, j)->value = value;
4895 ++j;
4897 if (CONSTRUCTOR_NELTS (t) != j)
4898 vec_safe_truncate (CONSTRUCTOR_ELTS (t), j);
4901 /* Subroutine of cxx_eval_constant_expression.
4902 Attempt to evaluate a BIT_CAST_EXPR. */
4904 static tree
4905 cxx_eval_bit_cast (const constexpr_ctx *ctx, tree t, bool *non_constant_p,
4906 bool *overflow_p)
4908 if (check_bit_cast_type (ctx, EXPR_LOCATION (t), TREE_TYPE (t),
4909 TREE_TYPE (t))
4910 || check_bit_cast_type (ctx, cp_expr_loc_or_loc (TREE_OPERAND (t, 0),
4911 EXPR_LOCATION (t)),
4912 TREE_TYPE (TREE_OPERAND (t, 0)),
4913 TREE_TYPE (TREE_OPERAND (t, 0))))
4915 *non_constant_p = true;
4916 return t;
4919 tree op = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), vc_prvalue,
4920 non_constant_p, overflow_p);
4921 if (*non_constant_p)
4922 return t;
4924 location_t loc = EXPR_LOCATION (t);
4925 if (BITS_PER_UNIT != 8 || CHAR_BIT != 8)
4927 if (!ctx->quiet)
4928 sorry_at (loc, "%qs cannot be constant evaluated on the target",
4929 "__builtin_bit_cast");
4930 *non_constant_p = true;
4931 return t;
4934 if (!tree_fits_shwi_p (TYPE_SIZE_UNIT (TREE_TYPE (t))))
4936 if (!ctx->quiet)
4937 sorry_at (loc, "%qs cannot be constant evaluated because the "
4938 "type is too large", "__builtin_bit_cast");
4939 *non_constant_p = true;
4940 return t;
4943 HOST_WIDE_INT len = tree_to_shwi (TYPE_SIZE_UNIT (TREE_TYPE (t)));
4944 if (len < 0 || (int) len != len)
4946 if (!ctx->quiet)
4947 sorry_at (loc, "%qs cannot be constant evaluated because the "
4948 "type is too large", "__builtin_bit_cast");
4949 *non_constant_p = true;
4950 return t;
4953 unsigned char buf[64];
4954 unsigned char *ptr, *mask;
4955 size_t alen = (size_t) len * 2;
4956 if (alen <= sizeof (buf))
4957 ptr = buf;
4958 else
4959 ptr = XNEWVEC (unsigned char, alen);
4960 mask = ptr + (size_t) len;
4961 /* At the beginning consider everything indeterminate. */
4962 memset (mask, ~0, (size_t) len);
4964 if (native_encode_initializer (op, ptr, len, 0, mask) != len)
4966 if (!ctx->quiet)
4967 sorry_at (loc, "%qs cannot be constant evaluated because the "
4968 "argument cannot be encoded", "__builtin_bit_cast");
4969 *non_constant_p = true;
4970 if (ptr != buf)
4971 XDELETE (ptr);
4972 return t;
4975 tree r = NULL_TREE;
4976 if (can_native_interpret_type_p (TREE_TYPE (t)))
4978 r = native_interpret_expr (TREE_TYPE (t), ptr, len);
4979 if (is_byte_access_type_not_plain_char (TREE_TYPE (t)))
4981 gcc_assert (len == 1);
4982 if (mask[0])
4984 memset (mask, 0, len);
4985 r = build_constructor (TREE_TYPE (r), NULL);
4986 CONSTRUCTOR_NO_CLEARING (r) = 1;
4990 else if (TREE_CODE (TREE_TYPE (t)) == RECORD_TYPE)
4992 r = native_interpret_aggregate (TREE_TYPE (t), ptr, 0, len);
4993 if (r != NULL_TREE)
4995 clear_type_padding_in_mask (TREE_TYPE (t), mask);
4996 clear_uchar_or_std_byte_in_mask (loc, r, mask);
4997 if (CHECKING_P)
4999 tree e = cxx_eval_bare_aggregate (ctx, r, vc_prvalue,
5000 non_constant_p, overflow_p);
5001 gcc_checking_assert (e == r);
5002 r = e;
5007 if (r != NULL_TREE)
5009 for (int i = 0; i < len; i++)
5010 if (mask[i])
5012 if (!ctx->quiet)
5013 error_at (loc, "%qs accessing uninitialized byte at offset %d",
5014 "__builtin_bit_cast", i);
5015 *non_constant_p = true;
5016 r = t;
5017 break;
5019 if (ptr != buf)
5020 XDELETE (ptr);
5021 return r;
5024 if (!ctx->quiet)
5025 sorry_at (loc, "%qs cannot be constant evaluated because the "
5026 "argument cannot be interpreted", "__builtin_bit_cast");
5027 *non_constant_p = true;
5028 if (ptr != buf)
5029 XDELETE (ptr);
5030 return t;
5033 /* Subroutine of cxx_eval_constant_expression.
5034 Evaluate a short-circuited logical expression T in the context
5035 of a given constexpr CALL. BAILOUT_VALUE is the value for
5036 early return. CONTINUE_VALUE is used here purely for
5037 sanity check purposes. */
5039 static tree
5040 cxx_eval_logical_expression (const constexpr_ctx *ctx, tree t,
5041 tree bailout_value, tree continue_value,
5042 bool *non_constant_p, bool *overflow_p)
5044 tree r;
5045 tree lhs = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
5046 vc_prvalue, non_constant_p,
5047 overflow_p);
5048 VERIFY_CONSTANT (lhs);
5049 if (tree_int_cst_equal (lhs, bailout_value))
5050 return lhs;
5051 gcc_assert (tree_int_cst_equal (lhs, continue_value));
5052 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
5053 vc_prvalue, non_constant_p,
5054 overflow_p);
5055 VERIFY_CONSTANT (r);
5056 return r;
5059 /* REF is a COMPONENT_REF designating a particular field. V is a vector of
5060 CONSTRUCTOR elements to initialize (part of) an object containing that
5061 field. Return a pointer to the constructor_elt corresponding to the
5062 initialization of the field. */
5064 static constructor_elt *
5065 base_field_constructor_elt (vec<constructor_elt, va_gc> *v, tree ref)
5067 tree aggr = TREE_OPERAND (ref, 0);
5068 tree field = TREE_OPERAND (ref, 1);
5069 HOST_WIDE_INT i;
5070 constructor_elt *ce;
5072 gcc_assert (TREE_CODE (ref) == COMPONENT_REF);
5074 if (TREE_CODE (aggr) == COMPONENT_REF)
5076 constructor_elt *base_ce
5077 = base_field_constructor_elt (v, aggr);
5078 v = CONSTRUCTOR_ELTS (base_ce->value);
5081 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
5082 if (ce->index == field)
5083 return ce;
5085 gcc_unreachable ();
5086 return NULL;
5089 /* Some of the expressions fed to the constexpr mechanism are calls to
5090 constructors, which have type void. In that case, return the type being
5091 initialized by the constructor. */
5093 static tree
5094 initialized_type (tree t)
5096 if (TYPE_P (t))
5097 return t;
5098 tree type = TREE_TYPE (t);
5099 if (TREE_CODE (t) == CALL_EXPR)
5101 /* A constructor call has void type, so we need to look deeper. */
5102 tree fn = get_function_named_in_call (t);
5103 if (fn && TREE_CODE (fn) == FUNCTION_DECL
5104 && DECL_CXX_CONSTRUCTOR_P (fn))
5105 type = DECL_CONTEXT (fn);
5107 else if (TREE_CODE (t) == COMPOUND_EXPR)
5108 return initialized_type (TREE_OPERAND (t, 1));
5109 else if (TREE_CODE (t) == AGGR_INIT_EXPR)
5110 type = TREE_TYPE (AGGR_INIT_EXPR_SLOT (t));
5111 return cv_unqualified (type);
5114 /* We're about to initialize element INDEX of an array or class from VALUE.
5115 Set up NEW_CTX appropriately by adjusting .object to refer to the
5116 subobject and creating a new CONSTRUCTOR if the element is itself
5117 a class or array. */
5119 static void
5120 init_subob_ctx (const constexpr_ctx *ctx, constexpr_ctx &new_ctx,
5121 tree index, tree &value)
5123 new_ctx = *ctx;
5125 if (index && TREE_CODE (index) != INTEGER_CST
5126 && TREE_CODE (index) != FIELD_DECL
5127 && TREE_CODE (index) != RANGE_EXPR)
5128 /* This won't have an element in the new CONSTRUCTOR. */
5129 return;
5131 tree type = initialized_type (value);
5132 if (!AGGREGATE_TYPE_P (type) && !VECTOR_TYPE_P (type))
5133 /* A non-aggregate member doesn't get its own CONSTRUCTOR. */
5134 return;
5135 if (VECTOR_TYPE_P (type)
5136 && VECTOR_TYPE_P (TREE_TYPE (ctx->ctor))
5137 && index == NULL_TREE)
5138 /* A vector inside of a vector CONSTRUCTOR, e.g. when a larger
5139 vector is constructed from smaller vectors, doesn't get its own
5140 CONSTRUCTOR either. */
5141 return;
5143 /* The sub-aggregate initializer might contain a placeholder;
5144 update object to refer to the subobject and ctor to refer to
5145 the (newly created) sub-initializer. */
5146 if (ctx->object)
5148 if (index == NULL_TREE || TREE_CODE (index) == RANGE_EXPR)
5149 /* There's no well-defined subobject for this index. */
5150 new_ctx.object = NULL_TREE;
5151 else
5152 new_ctx.object = build_ctor_subob_ref (index, type, ctx->object);
5155 if (is_empty_class (type))
5156 /* Leave ctor null for an empty subobject, they aren't represented in the
5157 result of evaluation. */
5158 new_ctx.ctor = NULL_TREE;
5159 else
5161 tree elt = build_constructor (type, NULL);
5162 CONSTRUCTOR_NO_CLEARING (elt) = true;
5163 new_ctx.ctor = elt;
5166 if (TREE_CODE (value) == TARGET_EXPR)
5167 /* Avoid creating another CONSTRUCTOR when we expand the TARGET_EXPR. */
5168 value = TARGET_EXPR_INITIAL (value);
5171 /* We're about to process an initializer for a class or array TYPE. Make
5172 sure that CTX is set up appropriately. */
5174 static void
5175 verify_ctor_sanity (const constexpr_ctx *ctx, tree type)
5177 /* We don't bother building a ctor for an empty base subobject. */
5178 if (is_empty_class (type))
5179 return;
5181 /* We're in the middle of an initializer that might involve placeholders;
5182 our caller should have created a CONSTRUCTOR for us to put the
5183 initializer into. We will either return that constructor or T. */
5184 gcc_assert (ctx->ctor);
5185 gcc_assert (same_type_ignoring_top_level_qualifiers_p
5186 (type, TREE_TYPE (ctx->ctor)));
5187 /* We used to check that ctx->ctor was empty, but that isn't the case when
5188 the object is zero-initialized before calling the constructor. */
5189 if (ctx->object)
5191 tree otype = TREE_TYPE (ctx->object);
5192 gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, otype)
5193 /* Handle flexible array members. */
5194 || (TREE_CODE (otype) == ARRAY_TYPE
5195 && TYPE_DOMAIN (otype) == NULL_TREE
5196 && TREE_CODE (type) == ARRAY_TYPE
5197 && (same_type_ignoring_top_level_qualifiers_p
5198 (TREE_TYPE (type), TREE_TYPE (otype)))));
5200 gcc_assert (!ctx->object || !DECL_P (ctx->object)
5201 || ctx->global->get_value (ctx->object) == ctx->ctor);
5204 /* Subroutine of cxx_eval_constant_expression.
5205 The expression tree T denotes a C-style array or a C-style
5206 aggregate. Reduce it to a constant expression. */
5208 static tree
5209 cxx_eval_bare_aggregate (const constexpr_ctx *ctx, tree t,
5210 value_cat lval,
5211 bool *non_constant_p, bool *overflow_p)
5213 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
5214 bool changed = false;
5215 gcc_assert (!BRACE_ENCLOSED_INITIALIZER_P (t));
5216 tree type = TREE_TYPE (t);
5218 constexpr_ctx new_ctx;
5219 if (TYPE_PTRMEMFUNC_P (type) || VECTOR_TYPE_P (type))
5221 /* We don't really need the ctx->ctor business for a PMF or
5222 vector, but it's simpler to use the same code. */
5223 new_ctx = *ctx;
5224 new_ctx.ctor = build_constructor (type, NULL);
5225 new_ctx.object = NULL_TREE;
5226 ctx = &new_ctx;
5228 verify_ctor_sanity (ctx, type);
5229 vec<constructor_elt, va_gc> **p = nullptr;
5230 if (ctx->ctor)
5232 p = &CONSTRUCTOR_ELTS (ctx->ctor);
5233 vec_alloc (*p, vec_safe_length (v));
5234 if (CONSTRUCTOR_PLACEHOLDER_BOUNDARY (t))
5235 CONSTRUCTOR_PLACEHOLDER_BOUNDARY (ctx->ctor) = 1;
5238 unsigned i;
5239 tree index, value;
5240 bool constant_p = true;
5241 bool side_effects_p = false;
5242 FOR_EACH_CONSTRUCTOR_ELT (v, i, index, value)
5244 tree orig_value = value;
5245 init_subob_ctx (ctx, new_ctx, index, value);
5246 /* Like in cxx_eval_store_expression, omit entries for empty fields. */
5247 bool no_slot = new_ctx.ctor == NULL_TREE;
5248 int pos_hint = -1;
5249 if (new_ctx.ctor != ctx->ctor && !no_slot)
5251 /* If we built a new CONSTRUCTOR, attach it now so that other
5252 initializers can refer to it. */
5253 constructor_elt *cep = get_or_insert_ctor_field (ctx->ctor, index);
5254 cep->value = new_ctx.ctor;
5255 pos_hint = cep - (*p)->begin();
5257 else if (TREE_CODE (type) == UNION_TYPE)
5258 /* Otherwise if we're constructing a non-aggregate union member, set
5259 the active union member now so that we can later detect and diagnose
5260 if its initializer attempts to activate another member. */
5261 get_or_insert_ctor_field (ctx->ctor, index);
5262 tree elt = cxx_eval_constant_expression (&new_ctx, value,
5263 lval,
5264 non_constant_p, overflow_p);
5265 /* Don't VERIFY_CONSTANT here. */
5266 if (ctx->quiet && *non_constant_p)
5267 break;
5268 if (elt != orig_value)
5269 changed = true;
5271 if (!TREE_CONSTANT (elt))
5272 constant_p = false;
5273 if (TREE_SIDE_EFFECTS (elt))
5274 side_effects_p = true;
5275 if (index && TREE_CODE (index) == COMPONENT_REF)
5277 /* This is an initialization of a vfield inside a base
5278 subaggregate that we already initialized; push this
5279 initialization into the previous initialization. */
5280 constructor_elt *inner = base_field_constructor_elt (*p, index);
5281 inner->value = elt;
5282 changed = true;
5284 else if (no_slot)
5285 /* This is an initializer for an empty field; now that we've
5286 checked that it's constant, we can ignore it. */
5287 changed = true;
5288 else if (index
5289 && (TREE_CODE (index) == NOP_EXPR
5290 || TREE_CODE (index) == POINTER_PLUS_EXPR))
5292 /* Old representation of empty bases. FIXME remove. */
5293 gcc_checking_assert (false);
5294 gcc_assert (is_empty_class (TREE_TYPE (TREE_TYPE (index))));
5295 changed = true;
5297 else
5299 if (TREE_CODE (type) == UNION_TYPE
5300 && (*p)->last().index != index)
5301 /* The initializer erroneously changed the active union member that
5302 we're initializing. */
5303 gcc_assert (*non_constant_p);
5304 else
5306 /* The initializer might have mutated the underlying CONSTRUCTOR,
5307 so recompute the location of the target constructer_elt. */
5308 constructor_elt *cep
5309 = get_or_insert_ctor_field (ctx->ctor, index, pos_hint);
5310 cep->value = elt;
5313 /* Adding or replacing an element might change the ctor's flags. */
5314 TREE_CONSTANT (ctx->ctor) = constant_p;
5315 TREE_SIDE_EFFECTS (ctx->ctor) = side_effects_p;
5318 if (*non_constant_p)
5319 return t;
5320 if (!changed)
5322 if (VECTOR_TYPE_P (type))
5323 t = fold (t);
5324 return t;
5326 t = ctx->ctor;
5327 if (!t)
5328 t = build_constructor (type, NULL);
5329 /* We're done building this CONSTRUCTOR, so now we can interpret an
5330 element without an explicit initializer as value-initialized. */
5331 CONSTRUCTOR_NO_CLEARING (t) = false;
5332 TREE_CONSTANT (t) = constant_p;
5333 TREE_SIDE_EFFECTS (t) = side_effects_p;
5334 if (VECTOR_TYPE_P (type))
5335 t = fold (t);
5336 return t;
5339 /* Subroutine of cxx_eval_constant_expression.
5340 The expression tree T is a VEC_INIT_EXPR which denotes the desired
5341 initialization of a non-static data member of array type. Reduce it to a
5342 CONSTRUCTOR.
5344 Note that apart from value-initialization (when VALUE_INIT is true),
5345 this is only intended to support value-initialization and the
5346 initializations done by defaulted constructors for classes with
5347 non-static data members of array type. In this case, VEC_INIT_EXPR_INIT
5348 will either be NULL_TREE for the default constructor, or a COMPONENT_REF
5349 for the copy/move constructor. */
5351 static tree
5352 cxx_eval_vec_init_1 (const constexpr_ctx *ctx, tree atype, tree init,
5353 bool value_init, value_cat lval,
5354 bool *non_constant_p, bool *overflow_p)
5356 tree elttype = TREE_TYPE (atype);
5357 verify_ctor_sanity (ctx, atype);
5358 vec<constructor_elt, va_gc> **p = &CONSTRUCTOR_ELTS (ctx->ctor);
5359 bool pre_init = false;
5360 unsigned HOST_WIDE_INT i;
5361 tsubst_flags_t complain = ctx->quiet ? tf_none : tf_warning_or_error;
5363 if (init && TREE_CODE (init) == CONSTRUCTOR)
5364 return cxx_eval_bare_aggregate (ctx, init, lval,
5365 non_constant_p, overflow_p);
5367 /* For the default constructor, build up a call to the default
5368 constructor of the element type. We only need to handle class types
5369 here, as for a constructor to be constexpr, all members must be
5370 initialized, which for a defaulted default constructor means they must
5371 be of a class type with a constexpr default constructor. */
5372 if (TREE_CODE (elttype) == ARRAY_TYPE)
5373 /* We only do this at the lowest level. */;
5374 else if (value_init)
5376 init = build_value_init (elttype, complain);
5377 pre_init = true;
5379 else if (!init)
5381 releasing_vec argvec;
5382 init = build_special_member_call (NULL_TREE, complete_ctor_identifier,
5383 &argvec, elttype, LOOKUP_NORMAL,
5384 complain);
5385 init = build_aggr_init_expr (elttype, init);
5386 pre_init = true;
5389 bool zeroed_out = false;
5390 if (!CONSTRUCTOR_NO_CLEARING (ctx->ctor))
5392 /* We're initializing an array object that had been zero-initialized
5393 earlier. Truncate ctx->ctor, and propagate its zeroed state by
5394 clearing CONSTRUCTOR_NO_CLEARING on each of the aggregate element
5395 initializers we append to it. */
5396 gcc_checking_assert (initializer_zerop (ctx->ctor));
5397 zeroed_out = true;
5398 vec_safe_truncate (*p, 0);
5401 tree nelts = get_array_or_vector_nelts (ctx, atype, non_constant_p,
5402 overflow_p);
5403 unsigned HOST_WIDE_INT max = tree_to_uhwi (nelts);
5404 for (i = 0; i < max; ++i)
5406 tree idx = build_int_cst (size_type_node, i);
5407 tree eltinit;
5408 bool reuse = false;
5409 constexpr_ctx new_ctx;
5410 init_subob_ctx (ctx, new_ctx, idx, pre_init ? init : elttype);
5411 bool no_slot = new_ctx.ctor == NULL_TREE;
5412 if (new_ctx.ctor != ctx->ctor && !no_slot)
5414 if (zeroed_out)
5415 CONSTRUCTOR_NO_CLEARING (new_ctx.ctor) = false;
5416 CONSTRUCTOR_APPEND_ELT (*p, idx, new_ctx.ctor);
5418 if (TREE_CODE (elttype) == ARRAY_TYPE)
5420 /* A multidimensional array; recurse. */
5421 if (value_init || init == NULL_TREE)
5423 eltinit = NULL_TREE;
5424 reuse = i == 0;
5426 else
5427 eltinit = cp_build_array_ref (input_location, init, idx, complain);
5428 eltinit = cxx_eval_vec_init_1 (&new_ctx, elttype, eltinit, value_init,
5429 lval,
5430 non_constant_p, overflow_p);
5432 else if (pre_init)
5434 /* Initializing an element using value or default initialization
5435 we just pre-built above. */
5436 if (init == void_node)
5437 /* Trivial default-init, don't do anything to the CONSTRUCTOR. */
5438 return ctx->ctor;
5439 eltinit = cxx_eval_constant_expression (&new_ctx, init, lval,
5440 non_constant_p, overflow_p);
5441 reuse = i == 0;
5443 else
5445 /* Copying an element. */
5446 eltinit = cp_build_array_ref (input_location, init, idx, complain);
5447 if (!lvalue_p (init))
5448 eltinit = move (eltinit);
5449 eltinit = (perform_implicit_conversion_flags
5450 (elttype, eltinit, complain,
5451 LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING));
5452 eltinit = cxx_eval_constant_expression (&new_ctx, eltinit, lval,
5453 non_constant_p, overflow_p);
5455 if (*non_constant_p)
5456 break;
5457 if (no_slot)
5459 /* This is an initializer for an empty subobject; now that we've
5460 checked that it's constant, we can ignore it. */
5461 gcc_checking_assert (i == 0);
5462 break;
5464 else if (new_ctx.ctor != ctx->ctor)
5466 /* We appended this element above; update the value. */
5467 gcc_assert ((*p)->last().index == idx);
5468 (*p)->last().value = eltinit;
5470 else
5471 CONSTRUCTOR_APPEND_ELT (*p, idx, eltinit);
5472 /* Reuse the result of cxx_eval_constant_expression call
5473 from the first iteration to all others if it is a constant
5474 initializer that doesn't require relocations. */
5475 if (reuse
5476 && max > 1
5477 && (eltinit == NULL_TREE
5478 || (initializer_constant_valid_p (eltinit, TREE_TYPE (eltinit))
5479 == null_pointer_node)))
5481 if (new_ctx.ctor != ctx->ctor)
5482 eltinit = new_ctx.ctor;
5483 tree range = build2 (RANGE_EXPR, size_type_node,
5484 build_int_cst (size_type_node, 1),
5485 build_int_cst (size_type_node, max - 1));
5486 CONSTRUCTOR_APPEND_ELT (*p, range, unshare_constructor (eltinit));
5487 break;
5489 else if (i == 0)
5490 vec_safe_reserve (*p, max);
5493 if (!*non_constant_p)
5495 init = ctx->ctor;
5496 CONSTRUCTOR_NO_CLEARING (init) = false;
5498 return init;
5501 static tree
5502 cxx_eval_vec_init (const constexpr_ctx *ctx, tree t,
5503 value_cat lval,
5504 bool *non_constant_p, bool *overflow_p)
5506 tree atype = TREE_TYPE (t);
5507 tree init = VEC_INIT_EXPR_INIT (t);
5508 bool value_init = VEC_INIT_EXPR_VALUE_INIT (t);
5509 if (!init || !BRACE_ENCLOSED_INITIALIZER_P (init))
5511 else if (CONSTRUCTOR_NELTS (init) == 0
5512 && !CP_AGGREGATE_TYPE_P (strip_array_types (atype)))
5514 /* Handle {} as value-init. */
5515 init = NULL_TREE;
5516 value_init = true;
5518 else
5520 /* This is a more complicated case, like needing to loop over trailing
5521 elements; call build_vec_init and evaluate the result. */
5522 tsubst_flags_t complain = ctx->quiet ? tf_none : tf_warning_or_error;
5523 constexpr_ctx new_ctx = *ctx;
5524 if (!ctx->object)
5526 /* We want to have an initialization target for an VEC_INIT_EXPR.
5527 If we don't already have one in CTX, use the VEC_INIT_EXPR_SLOT. */
5528 new_ctx.object = VEC_INIT_EXPR_SLOT (t);
5529 tree ctor = new_ctx.ctor = build_constructor (atype, NULL);
5530 CONSTRUCTOR_NO_CLEARING (ctor) = true;
5531 ctx->global->put_value (new_ctx.object, ctor);
5532 ctx = &new_ctx;
5534 init = expand_vec_init_expr (ctx->object, t, complain);
5535 return cxx_eval_constant_expression (ctx, init, lval, non_constant_p,
5536 overflow_p);
5538 tree r = cxx_eval_vec_init_1 (ctx, atype, init, value_init,
5539 lval, non_constant_p, overflow_p);
5540 if (*non_constant_p)
5541 return t;
5542 else
5543 return r;
5546 /* Like same_type_ignoring_top_level_qualifiers_p, but also handle the case
5547 where the desired type is an array of unknown bounds because the variable
5548 has had its bounds deduced since the wrapping expression was created. */
5550 static bool
5551 same_type_ignoring_tlq_and_bounds_p (tree type1, tree type2)
5553 while (TREE_CODE (type1) == ARRAY_TYPE
5554 && TREE_CODE (type2) == ARRAY_TYPE
5555 && (!TYPE_DOMAIN (type1) || !TYPE_DOMAIN (type2)))
5557 type1 = TREE_TYPE (type1);
5558 type2 = TREE_TYPE (type2);
5560 return same_type_ignoring_top_level_qualifiers_p (type1, type2);
5563 /* Try to determine the currently active union member for an expression
5564 with UNION_TYPE. If it can be determined, return the FIELD_DECL,
5565 otherwise return NULL_TREE. */
5567 static tree
5568 cxx_union_active_member (const constexpr_ctx *ctx, tree t)
5570 constexpr_ctx new_ctx = *ctx;
5571 new_ctx.quiet = true;
5572 bool non_constant_p = false, overflow_p = false;
5573 tree ctor = cxx_eval_constant_expression (&new_ctx, t, vc_prvalue,
5574 &non_constant_p,
5575 &overflow_p);
5576 if (TREE_CODE (ctor) == CONSTRUCTOR
5577 && CONSTRUCTOR_NELTS (ctor) == 1
5578 && CONSTRUCTOR_ELT (ctor, 0)->index
5579 && TREE_CODE (CONSTRUCTOR_ELT (ctor, 0)->index) == FIELD_DECL)
5580 return CONSTRUCTOR_ELT (ctor, 0)->index;
5581 return NULL_TREE;
5584 /* Helper function for cxx_fold_indirect_ref_1, called recursively. */
5586 static tree
5587 cxx_fold_indirect_ref_1 (const constexpr_ctx *ctx, location_t loc, tree type,
5588 tree op, unsigned HOST_WIDE_INT off, bool *empty_base)
5590 tree optype = TREE_TYPE (op);
5591 unsigned HOST_WIDE_INT const_nunits;
5592 if (off == 0 && similar_type_p (optype, type))
5593 return op;
5594 else if (TREE_CODE (optype) == COMPLEX_TYPE
5595 && similar_type_p (type, TREE_TYPE (optype)))
5597 /* *(foo *)&complexfoo => __real__ complexfoo */
5598 if (off == 0)
5599 return build1_loc (loc, REALPART_EXPR, type, op);
5600 /* ((foo*)&complexfoo)[1] => __imag__ complexfoo */
5601 else if (tree_to_uhwi (TYPE_SIZE_UNIT (type)) == off)
5602 return build1_loc (loc, IMAGPART_EXPR, type, op);
5604 /* ((foo*)&vectorfoo)[x] => BIT_FIELD_REF<vectorfoo,...> */
5605 else if (VECTOR_TYPE_P (optype)
5606 && similar_type_p (type, TREE_TYPE (optype))
5607 && TYPE_VECTOR_SUBPARTS (optype).is_constant (&const_nunits))
5609 unsigned HOST_WIDE_INT part_width = tree_to_uhwi (TYPE_SIZE_UNIT (type));
5610 unsigned HOST_WIDE_INT max_offset = part_width * const_nunits;
5611 if (off < max_offset && off % part_width == 0)
5613 tree index = bitsize_int (off * BITS_PER_UNIT);
5614 return build3_loc (loc, BIT_FIELD_REF, type, op,
5615 TYPE_SIZE (type), index);
5618 /* ((foo *)&fooarray)[x] => fooarray[x] */
5619 else if (TREE_CODE (optype) == ARRAY_TYPE
5620 && tree_fits_uhwi_p (TYPE_SIZE_UNIT (TREE_TYPE (optype)))
5621 && !integer_zerop (TYPE_SIZE_UNIT (TREE_TYPE (optype))))
5623 tree type_domain = TYPE_DOMAIN (optype);
5624 tree min_val = size_zero_node;
5625 if (type_domain && TYPE_MIN_VALUE (type_domain))
5626 min_val = TYPE_MIN_VALUE (type_domain);
5627 unsigned HOST_WIDE_INT el_sz
5628 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (optype)));
5629 unsigned HOST_WIDE_INT idx = off / el_sz;
5630 unsigned HOST_WIDE_INT rem = off % el_sz;
5631 if (tree_fits_uhwi_p (min_val))
5633 tree index = size_int (idx + tree_to_uhwi (min_val));
5634 op = build4_loc (loc, ARRAY_REF, TREE_TYPE (optype), op, index,
5635 NULL_TREE, NULL_TREE);
5636 return cxx_fold_indirect_ref_1 (ctx, loc, type, op, rem,
5637 empty_base);
5640 /* ((foo *)&struct_with_foo_field)[x] => COMPONENT_REF */
5641 else if (TREE_CODE (optype) == RECORD_TYPE
5642 || TREE_CODE (optype) == UNION_TYPE)
5644 if (TREE_CODE (optype) == UNION_TYPE)
5645 /* For unions prefer the currently active member. */
5646 if (tree field = cxx_union_active_member (ctx, op))
5648 unsigned HOST_WIDE_INT el_sz
5649 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (field)));
5650 if (off < el_sz)
5652 tree cop = build3 (COMPONENT_REF, TREE_TYPE (field),
5653 op, field, NULL_TREE);
5654 if (tree ret = cxx_fold_indirect_ref_1 (ctx, loc, type, cop,
5655 off, empty_base))
5656 return ret;
5660 /* Handle conversion to an empty base class, which is represented with a
5661 NOP_EXPR. Do this before spelunking into the non-empty subobjects,
5662 which is likely to be a waste of time (109678). */
5663 if (is_empty_class (type)
5664 && CLASS_TYPE_P (optype)
5665 && lookup_base (optype, type, ba_any, NULL, tf_none, off))
5667 if (empty_base)
5668 *empty_base = true;
5669 return op;
5672 for (tree field = TYPE_FIELDS (optype);
5673 field; field = DECL_CHAIN (field))
5674 if (TREE_CODE (field) == FIELD_DECL
5675 && TREE_TYPE (field) != error_mark_node
5676 && tree_fits_uhwi_p (TYPE_SIZE_UNIT (TREE_TYPE (field))))
5678 tree pos = byte_position (field);
5679 if (!tree_fits_uhwi_p (pos))
5680 continue;
5681 unsigned HOST_WIDE_INT upos = tree_to_uhwi (pos);
5682 unsigned HOST_WIDE_INT el_sz
5683 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (field)));
5684 if (upos <= off && off < upos + el_sz)
5686 tree cop = build3 (COMPONENT_REF, TREE_TYPE (field),
5687 op, field, NULL_TREE);
5688 if (tree ret = cxx_fold_indirect_ref_1 (ctx, loc, type, cop,
5689 off - upos,
5690 empty_base))
5691 return ret;
5696 return NULL_TREE;
5699 /* A less strict version of fold_indirect_ref_1, which requires cv-quals to
5700 match. We want to be less strict for simple *& folding; if we have a
5701 non-const temporary that we access through a const pointer, that should
5702 work. We handle this here rather than change fold_indirect_ref_1
5703 because we're dealing with things like ADDR_EXPR of INTEGER_CST which
5704 don't really make sense outside of constant expression evaluation. Also
5705 we want to allow folding to COMPONENT_REF, which could cause trouble
5706 with TBAA in fold_indirect_ref_1. */
5708 static tree
5709 cxx_fold_indirect_ref (const constexpr_ctx *ctx, location_t loc, tree type,
5710 tree op0, bool *empty_base /* = NULL*/)
5712 tree sub = op0;
5713 tree subtype;
5715 /* STRIP_NOPS, but stop if REINTERPRET_CAST_P. */
5716 while (CONVERT_EXPR_P (sub) || TREE_CODE (sub) == NON_LVALUE_EXPR
5717 || TREE_CODE (sub) == VIEW_CONVERT_EXPR)
5719 if (TREE_CODE (sub) == NOP_EXPR
5720 && REINTERPRET_CAST_P (sub))
5721 return NULL_TREE;
5722 sub = TREE_OPERAND (sub, 0);
5725 subtype = TREE_TYPE (sub);
5726 if (!INDIRECT_TYPE_P (subtype))
5727 return NULL_TREE;
5729 /* Canonicalizes the given OBJ/OFF pair by iteratively absorbing
5730 the innermost component into the offset until it would make the
5731 offset positive, so that cxx_fold_indirect_ref_1 can identify
5732 more folding opportunities. */
5733 auto canonicalize_obj_off = [] (tree& obj, tree& off) {
5734 while (TREE_CODE (obj) == COMPONENT_REF
5735 && (tree_int_cst_sign_bit (off) || integer_zerop (off)))
5737 tree field = TREE_OPERAND (obj, 1);
5738 tree pos = byte_position (field);
5739 if (integer_zerop (off) && integer_nonzerop (pos))
5740 /* If the offset is already 0, keep going as long as the
5741 component is at position 0. */
5742 break;
5743 off = int_const_binop (PLUS_EXPR, off, pos);
5744 obj = TREE_OPERAND (obj, 0);
5748 if (TREE_CODE (sub) == ADDR_EXPR)
5750 tree op = TREE_OPERAND (sub, 0);
5751 tree optype = TREE_TYPE (op);
5753 /* *&CONST_DECL -> to the value of the const decl. */
5754 if (TREE_CODE (op) == CONST_DECL)
5755 return DECL_INITIAL (op);
5756 /* *&p => p; make sure to handle *&"str"[cst] here. */
5757 if (similar_type_p (optype, type))
5759 tree fop = fold_read_from_constant_string (op);
5760 if (fop)
5761 return fop;
5762 else
5763 return op;
5765 else
5767 tree off = integer_zero_node;
5768 canonicalize_obj_off (op, off);
5769 gcc_assert (integer_zerop (off));
5770 return cxx_fold_indirect_ref_1 (ctx, loc, type, op, 0, empty_base);
5773 else if (TREE_CODE (sub) == POINTER_PLUS_EXPR
5774 && tree_fits_uhwi_p (TREE_OPERAND (sub, 1)))
5776 tree op00 = TREE_OPERAND (sub, 0);
5777 tree off = TREE_OPERAND (sub, 1);
5779 STRIP_NOPS (op00);
5780 if (TREE_CODE (op00) == ADDR_EXPR)
5782 tree obj = TREE_OPERAND (op00, 0);
5783 canonicalize_obj_off (obj, off);
5784 return cxx_fold_indirect_ref_1 (ctx, loc, type, obj,
5785 tree_to_uhwi (off), empty_base);
5788 /* *(foo *)fooarrptr => (*fooarrptr)[0] */
5789 else if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
5790 && similar_type_p (type, TREE_TYPE (TREE_TYPE (subtype))))
5792 tree type_domain;
5793 tree min_val = size_zero_node;
5794 tree newsub
5795 = cxx_fold_indirect_ref (ctx, loc, TREE_TYPE (subtype), sub, NULL);
5796 if (newsub)
5797 sub = newsub;
5798 else
5799 sub = build1_loc (loc, INDIRECT_REF, TREE_TYPE (subtype), sub);
5800 type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
5801 if (type_domain && TYPE_MIN_VALUE (type_domain))
5802 min_val = TYPE_MIN_VALUE (type_domain);
5803 return build4_loc (loc, ARRAY_REF, type, sub, min_val, NULL_TREE,
5804 NULL_TREE);
5807 return NULL_TREE;
5810 static tree
5811 cxx_eval_indirect_ref (const constexpr_ctx *ctx, tree t,
5812 value_cat lval,
5813 bool *non_constant_p, bool *overflow_p)
5815 tree orig_op0 = TREE_OPERAND (t, 0);
5816 bool empty_base = false;
5818 /* We can handle a MEM_REF like an INDIRECT_REF, if MEM_REF's second
5819 operand is an integer-zero. Otherwise reject the MEM_REF for now. */
5821 if (TREE_CODE (t) == MEM_REF
5822 && (!TREE_OPERAND (t, 1) || !integer_zerop (TREE_OPERAND (t, 1))))
5824 gcc_assert (ctx->quiet);
5825 *non_constant_p = true;
5826 return t;
5829 /* First try to simplify it directly. */
5830 tree r = cxx_fold_indirect_ref (ctx, EXPR_LOCATION (t), TREE_TYPE (t),
5831 orig_op0, &empty_base);
5832 if (!r)
5834 /* If that didn't work, evaluate the operand first. */
5835 tree op0 = cxx_eval_constant_expression (ctx, orig_op0,
5836 vc_prvalue, non_constant_p,
5837 overflow_p);
5838 /* Don't VERIFY_CONSTANT here. */
5839 if (*non_constant_p)
5840 return t;
5842 if (!lval && integer_zerop (op0))
5844 if (!ctx->quiet)
5845 error ("dereferencing a null pointer");
5846 *non_constant_p = true;
5847 return t;
5850 r = cxx_fold_indirect_ref (ctx, EXPR_LOCATION (t), TREE_TYPE (t), op0,
5851 &empty_base);
5852 if (r == NULL_TREE)
5854 /* We couldn't fold to a constant value. Make sure it's not
5855 something we should have been able to fold. */
5856 tree sub = op0;
5857 STRIP_NOPS (sub);
5858 if (TREE_CODE (sub) == ADDR_EXPR)
5860 gcc_assert (!similar_type_p
5861 (TREE_TYPE (TREE_TYPE (sub)), TREE_TYPE (t)));
5862 /* DR 1188 says we don't have to deal with this. */
5863 if (!ctx->quiet)
5864 error_at (cp_expr_loc_or_input_loc (t),
5865 "accessing value of %qE through a %qT glvalue in a "
5866 "constant expression", build_fold_indirect_ref (sub),
5867 TREE_TYPE (t));
5868 *non_constant_p = true;
5869 return t;
5872 if (lval == vc_glvalue && op0 != orig_op0)
5873 return build1 (INDIRECT_REF, TREE_TYPE (t), op0);
5874 if (!lval)
5875 VERIFY_CONSTANT (t);
5876 return t;
5880 r = cxx_eval_constant_expression (ctx, r,
5881 lval, non_constant_p, overflow_p);
5882 if (*non_constant_p)
5883 return t;
5885 /* If we're pulling out the value of an empty base, just return an empty
5886 CONSTRUCTOR. */
5887 if (empty_base && !lval)
5889 r = build_constructor (TREE_TYPE (t), NULL);
5890 TREE_CONSTANT (r) = true;
5893 return r;
5896 /* Complain about R, a DECL that is accessed outside its lifetime. */
5898 static void
5899 outside_lifetime_error (location_t loc, tree r)
5901 auto_diagnostic_group d;
5902 if (DECL_NAME (r) == heap_deleted_identifier)
5904 /* Provide a more accurate message for deleted variables. */
5905 error_at (loc, "use of allocated storage after deallocation "
5906 "in a constant expression");
5907 inform (DECL_SOURCE_LOCATION (r), "allocated here");
5909 else
5911 error_at (loc, "accessing object outside its lifetime");
5912 inform (DECL_SOURCE_LOCATION (r), "declared here");
5916 /* Complain about R, a VAR_DECL, not being usable in a constant expression.
5917 FUNDEF_P is true if we're checking a constexpr function body.
5918 Shared between potential_constant_expression and
5919 cxx_eval_constant_expression. */
5921 static void
5922 non_const_var_error (location_t loc, tree r, bool fundef_p)
5924 auto_diagnostic_group d;
5925 tree type = TREE_TYPE (r);
5926 if (DECL_NAME (r) == heap_uninit_identifier
5927 || DECL_NAME (r) == heap_identifier
5928 || DECL_NAME (r) == heap_vec_uninit_identifier
5929 || DECL_NAME (r) == heap_vec_identifier)
5931 if (constexpr_error (loc, fundef_p, "the content of uninitialized "
5932 "storage is not usable in a constant expression"))
5933 inform (DECL_SOURCE_LOCATION (r), "allocated here");
5934 return;
5936 if (DECL_NAME (r) == heap_deleted_identifier)
5938 if (constexpr_error (loc, fundef_p, "use of allocated storage after "
5939 "deallocation in a constant expression"))
5940 inform (DECL_SOURCE_LOCATION (r), "allocated here");
5941 return;
5943 if (!constexpr_error (loc, fundef_p, "the value of %qD is not usable in "
5944 "a constant expression", r))
5945 return;
5946 /* Avoid error cascade. */
5947 if (DECL_INITIAL (r) == error_mark_node)
5948 return;
5949 if (DECL_DECLARED_CONSTEXPR_P (r))
5950 inform (DECL_SOURCE_LOCATION (r),
5951 "%qD used in its own initializer", r);
5952 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5954 if (!CP_TYPE_CONST_P (type))
5955 inform (DECL_SOURCE_LOCATION (r),
5956 "%q#D is not const", r);
5957 else if (CP_TYPE_VOLATILE_P (type))
5958 inform (DECL_SOURCE_LOCATION (r),
5959 "%q#D is volatile", r);
5960 else if (!DECL_INITIAL (r)
5961 || !TREE_CONSTANT (DECL_INITIAL (r))
5962 || !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r))
5963 inform (DECL_SOURCE_LOCATION (r),
5964 "%qD was not initialized with a constant "
5965 "expression", r);
5966 else
5967 gcc_unreachable ();
5969 else if (TYPE_REF_P (type))
5970 inform (DECL_SOURCE_LOCATION (r),
5971 "%qD was not initialized with a constant "
5972 "expression", r);
5973 else
5975 if (cxx_dialect >= cxx11 && !DECL_DECLARED_CONSTEXPR_P (r))
5976 inform (DECL_SOURCE_LOCATION (r),
5977 "%qD was not declared %<constexpr%>", r);
5978 else
5979 inform (DECL_SOURCE_LOCATION (r),
5980 "%qD does not have integral or enumeration type",
5985 /* Subroutine of cxx_eval_constant_expression.
5986 Like cxx_eval_unary_expression, except for trinary expressions. */
5988 static tree
5989 cxx_eval_trinary_expression (const constexpr_ctx *ctx, tree t,
5990 value_cat lval,
5991 bool *non_constant_p, bool *overflow_p)
5993 int i;
5994 tree args[3];
5995 tree val;
5997 for (i = 0; i < 3; i++)
5999 args[i] = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, i),
6000 lval,
6001 non_constant_p, overflow_p);
6002 VERIFY_CONSTANT (args[i]);
6005 val = fold_ternary_loc (EXPR_LOCATION (t), TREE_CODE (t), TREE_TYPE (t),
6006 args[0], args[1], args[2]);
6007 if (val == NULL_TREE)
6008 return t;
6009 VERIFY_CONSTANT (val);
6010 return val;
6013 /* True if T was declared in a function declared to be constexpr, and
6014 therefore potentially constant in C++14. */
6016 bool
6017 var_in_constexpr_fn (tree t)
6019 tree ctx = DECL_CONTEXT (t);
6020 return (ctx && TREE_CODE (ctx) == FUNCTION_DECL
6021 && DECL_DECLARED_CONSTEXPR_P (ctx));
6024 /* True if a function might be constexpr: either a function that was
6025 declared constexpr, or a C++17 lambda op(). */
6027 bool
6028 maybe_constexpr_fn (tree t)
6030 return (DECL_DECLARED_CONSTEXPR_P (t)
6031 || (cxx_dialect >= cxx17 && LAMBDA_FUNCTION_P (t))
6032 || (flag_implicit_constexpr
6033 && DECL_DECLARED_INLINE_P (STRIP_TEMPLATE (t))));
6036 /* True if T was declared in a function that might be constexpr: either a
6037 function that was declared constexpr, or a C++17 lambda op(). */
6039 bool
6040 var_in_maybe_constexpr_fn (tree t)
6042 return (DECL_FUNCTION_SCOPE_P (t)
6043 && maybe_constexpr_fn (DECL_CONTEXT (t)));
6046 /* We're assigning INIT to TARGET. In do_build_copy_constructor and
6047 build_over_call we implement trivial copy of a class with tail padding using
6048 assignment of character arrays, which is valid in normal code, but not in
6049 constexpr evaluation. We don't need to worry about clobbering tail padding
6050 in constexpr evaluation, so strip the type punning. */
6052 static void
6053 maybe_simplify_trivial_copy (tree &target, tree &init)
6055 if (TREE_CODE (target) == MEM_REF
6056 && TREE_CODE (init) == MEM_REF
6057 && TREE_TYPE (target) == TREE_TYPE (init)
6058 && TREE_CODE (TREE_TYPE (target)) == ARRAY_TYPE
6059 && TREE_TYPE (TREE_TYPE (target)) == unsigned_char_type_node)
6061 target = build_fold_indirect_ref (TREE_OPERAND (target, 0));
6062 init = build_fold_indirect_ref (TREE_OPERAND (init, 0));
6066 /* Returns true if REF, which is a COMPONENT_REF, has any fields
6067 of constant type. This does not check for 'mutable', so the
6068 caller is expected to be mindful of that. */
6070 static bool
6071 cref_has_const_field (tree ref)
6073 while (TREE_CODE (ref) == COMPONENT_REF)
6075 if (CP_TYPE_CONST_P (TREE_TYPE (TREE_OPERAND (ref, 1))))
6076 return true;
6077 ref = TREE_OPERAND (ref, 0);
6079 return false;
6082 /* Return true if we are modifying something that is const during constant
6083 expression evaluation. CODE is the code of the statement, OBJ is the
6084 object in question, MUTABLE_P is true if one of the subobjects were
6085 declared mutable. */
6087 static bool
6088 modifying_const_object_p (tree_code code, tree obj, bool mutable_p)
6090 /* If this is initialization, there's no problem. */
6091 if (code != MODIFY_EXPR)
6092 return false;
6094 /* [basic.type.qualifier] "A const object is an object of type
6095 const T or a non-mutable subobject of a const object." */
6096 if (mutable_p)
6097 return false;
6099 if (TREE_READONLY (obj))
6100 return true;
6102 if (CP_TYPE_CONST_P (TREE_TYPE (obj)))
6104 /* Although a COMPONENT_REF may have a const type, we should
6105 only consider it modifying a const object when any of the
6106 field components is const. This can happen when using
6107 constructs such as const_cast<const T &>(m), making something
6108 const even though it wasn't declared const. */
6109 if (TREE_CODE (obj) == COMPONENT_REF)
6110 return cref_has_const_field (obj);
6111 else
6112 return true;
6115 return false;
6118 /* Evaluate an INIT_EXPR or MODIFY_EXPR. */
6120 static tree
6121 cxx_eval_store_expression (const constexpr_ctx *ctx, tree t,
6122 value_cat lval,
6123 bool *non_constant_p, bool *overflow_p)
6125 constexpr_ctx new_ctx = *ctx;
6127 tree init = TREE_OPERAND (t, 1);
6128 if (TREE_CLOBBER_P (init))
6129 /* Just ignore clobbers. */
6130 return void_node;
6132 /* First we figure out where we're storing to. */
6133 tree target = TREE_OPERAND (t, 0);
6135 maybe_simplify_trivial_copy (target, init);
6137 tree type = TREE_TYPE (target);
6138 bool preeval = SCALAR_TYPE_P (type) || TREE_CODE (t) == MODIFY_EXPR;
6139 if (preeval)
6141 /* Evaluate the value to be stored without knowing what object it will be
6142 stored in, so that any side-effects happen first. */
6143 if (!SCALAR_TYPE_P (type))
6144 new_ctx.ctor = new_ctx.object = NULL_TREE;
6145 init = cxx_eval_constant_expression (&new_ctx, init, vc_prvalue,
6146 non_constant_p, overflow_p);
6147 if (*non_constant_p)
6148 return t;
6151 bool evaluated = false;
6152 if (lval == vc_glvalue)
6154 /* If we want to return a reference to the target, we need to evaluate it
6155 as a whole; otherwise, only evaluate the innermost piece to avoid
6156 building up unnecessary *_REFs. */
6157 target = cxx_eval_constant_expression (ctx, target, lval,
6158 non_constant_p, overflow_p);
6159 evaluated = true;
6160 if (*non_constant_p)
6161 return t;
6164 /* Find the underlying variable. */
6165 releasing_vec refs;
6166 tree object = NULL_TREE;
6167 /* If we're modifying a const object, save it. */
6168 tree const_object_being_modified = NULL_TREE;
6169 bool mutable_p = false;
6170 for (tree probe = target; object == NULL_TREE; )
6172 switch (TREE_CODE (probe))
6174 case BIT_FIELD_REF:
6175 case COMPONENT_REF:
6176 case ARRAY_REF:
6178 tree ob = TREE_OPERAND (probe, 0);
6179 tree elt = TREE_OPERAND (probe, 1);
6180 if (TREE_CODE (elt) == FIELD_DECL && DECL_MUTABLE_P (elt))
6181 mutable_p = true;
6182 if (TREE_CODE (probe) == ARRAY_REF)
6184 elt = eval_and_check_array_index (ctx, probe, false,
6185 non_constant_p, overflow_p);
6186 if (*non_constant_p)
6187 return t;
6189 /* We don't check modifying_const_object_p for ARRAY_REFs. Given
6190 "int a[10]", an ARRAY_REF "a[2]" can be "const int", even though
6191 the array isn't const. Instead, check "a" in the next iteration;
6192 that will detect modifying "const int a[10]". */
6193 else if (evaluated
6194 && modifying_const_object_p (TREE_CODE (t), probe,
6195 mutable_p)
6196 && const_object_being_modified == NULL_TREE)
6197 const_object_being_modified = probe;
6199 /* Track named member accesses for unions to validate modifications
6200 that change active member. */
6201 if (!evaluated && TREE_CODE (probe) == COMPONENT_REF)
6202 vec_safe_push (refs, probe);
6203 else
6204 vec_safe_push (refs, NULL_TREE);
6206 vec_safe_push (refs, elt);
6207 vec_safe_push (refs, TREE_TYPE (probe));
6208 probe = ob;
6210 break;
6212 case REALPART_EXPR:
6213 gcc_assert (probe == target);
6214 vec_safe_push (refs, NULL_TREE);
6215 vec_safe_push (refs, probe);
6216 vec_safe_push (refs, TREE_TYPE (probe));
6217 probe = TREE_OPERAND (probe, 0);
6218 break;
6220 case IMAGPART_EXPR:
6221 gcc_assert (probe == target);
6222 vec_safe_push (refs, NULL_TREE);
6223 vec_safe_push (refs, probe);
6224 vec_safe_push (refs, TREE_TYPE (probe));
6225 probe = TREE_OPERAND (probe, 0);
6226 break;
6228 default:
6229 if (evaluated)
6230 object = probe;
6231 else
6233 probe = cxx_eval_constant_expression (ctx, probe, vc_glvalue,
6234 non_constant_p, overflow_p);
6235 evaluated = true;
6236 if (*non_constant_p)
6237 return t;
6239 break;
6243 if (modifying_const_object_p (TREE_CODE (t), object, mutable_p)
6244 && const_object_being_modified == NULL_TREE)
6245 const_object_being_modified = object;
6247 /* And then find/build up our initializer for the path to the subobject
6248 we're initializing. */
6249 tree *valp;
6250 if (DECL_P (object))
6251 valp = ctx->global->get_value_ptr (object);
6252 else
6253 valp = NULL;
6254 if (!valp)
6256 /* A constant-expression cannot modify objects from outside the
6257 constant-expression. */
6258 if (!ctx->quiet)
6259 error ("modification of %qE is not a constant expression", object);
6260 *non_constant_p = true;
6261 return t;
6263 type = TREE_TYPE (object);
6264 bool no_zero_init = true;
6266 auto_vec<tree *> ctors;
6267 releasing_vec indexes;
6268 auto_vec<int> index_pos_hints;
6269 bool activated_union_member_p = false;
6270 bool empty_base = false;
6271 while (!refs->is_empty ())
6273 if (*valp == NULL_TREE)
6275 *valp = build_constructor (type, NULL);
6276 CONSTRUCTOR_NO_CLEARING (*valp) = no_zero_init;
6278 else if (STRIP_ANY_LOCATION_WRAPPER (*valp),
6279 TREE_CODE (*valp) == STRING_CST)
6281 /* An array was initialized with a string constant, and now
6282 we're writing into one of its elements. Explode the
6283 single initialization into a set of element
6284 initializations. */
6285 gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
6287 tree string = *valp;
6288 tree elt_type = TREE_TYPE (type);
6289 unsigned chars_per_elt = (TYPE_PRECISION (elt_type)
6290 / TYPE_PRECISION (char_type_node));
6291 unsigned num_elts = TREE_STRING_LENGTH (string) / chars_per_elt;
6292 tree ary_ctor = build_constructor (type, NULL);
6294 vec_safe_reserve (CONSTRUCTOR_ELTS (ary_ctor), num_elts);
6295 for (unsigned ix = 0; ix != num_elts; ix++)
6297 constructor_elt elt =
6299 build_int_cst (size_type_node, ix),
6300 extract_string_elt (string, chars_per_elt, ix)
6302 CONSTRUCTOR_ELTS (ary_ctor)->quick_push (elt);
6305 *valp = ary_ctor;
6308 enum tree_code code = TREE_CODE (type);
6309 tree reftype = refs->pop();
6310 tree index = refs->pop();
6311 bool is_access_expr = refs->pop() != NULL_TREE;
6313 if (code == COMPLEX_TYPE)
6315 if (TREE_CODE (*valp) == COMPLEX_CST)
6316 *valp = build2 (COMPLEX_EXPR, type, TREE_REALPART (*valp),
6317 TREE_IMAGPART (*valp));
6318 else if (TREE_CODE (*valp) == CONSTRUCTOR
6319 && CONSTRUCTOR_NELTS (*valp) == 0
6320 && CONSTRUCTOR_NO_CLEARING (*valp))
6322 tree r = build_constructor (reftype, NULL);
6323 CONSTRUCTOR_NO_CLEARING (r) = 1;
6324 *valp = build2 (COMPLEX_EXPR, type, r, r);
6326 gcc_assert (TREE_CODE (*valp) == COMPLEX_EXPR);
6327 ctors.safe_push (valp);
6328 vec_safe_push (indexes, index);
6329 valp = &TREE_OPERAND (*valp, TREE_CODE (index) == IMAGPART_EXPR);
6330 gcc_checking_assert (refs->is_empty ());
6331 type = reftype;
6332 break;
6335 /* If the value of object is already zero-initialized, any new ctors for
6336 subobjects will also be zero-initialized. */
6337 no_zero_init = CONSTRUCTOR_NO_CLEARING (*valp);
6339 if (code == RECORD_TYPE && is_empty_field (index))
6340 /* Don't build a sub-CONSTRUCTOR for an empty base or field, as they
6341 have no data and might have an offset lower than previously declared
6342 fields, which confuses the middle-end. The code below will notice
6343 that we don't have a CONSTRUCTOR for our inner target and just
6344 return init. */
6346 empty_base = true;
6347 break;
6350 /* If a union is zero-initialized, its first non-static named data member
6351 is zero-initialized (and therefore active). */
6352 if (code == UNION_TYPE
6353 && !no_zero_init
6354 && CONSTRUCTOR_NELTS (*valp) == 0)
6355 if (tree first = next_aggregate_field (TYPE_FIELDS (type)))
6356 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (*valp), first, NULL_TREE);
6358 /* Check for implicit change of active member for a union. */
6359 if (code == UNION_TYPE
6360 && (CONSTRUCTOR_NELTS (*valp) == 0
6361 || CONSTRUCTOR_ELT (*valp, 0)->index != index)
6362 /* An INIT_EXPR of the last member in an access chain is always OK,
6363 but still check implicit change of members earlier on; see
6364 cpp2a/constexpr-union6.C. */
6365 && !(TREE_CODE (t) == INIT_EXPR && refs->is_empty ()))
6367 bool has_active_member = CONSTRUCTOR_NELTS (*valp) != 0;
6368 tree inner = strip_array_types (reftype);
6370 if (has_active_member && cxx_dialect < cxx20)
6372 if (!ctx->quiet)
6373 error_at (cp_expr_loc_or_input_loc (t),
6374 "change of the active member of a union "
6375 "from %qD to %qD is not a constant expression "
6376 "before C++20",
6377 CONSTRUCTOR_ELT (*valp, 0)->index,
6378 index);
6379 *non_constant_p = true;
6381 else if (!is_access_expr
6382 || (TREE_CODE (t) == MODIFY_EXPR
6383 && CLASS_TYPE_P (inner)
6384 && !type_has_non_deleted_trivial_default_ctor (inner)))
6386 /* Diagnose changing active union member after initialization
6387 without a valid member access expression, as described in
6388 [class.union.general] p5. */
6389 if (!ctx->quiet)
6391 auto_diagnostic_group d;
6392 if (has_active_member)
6393 error_at (cp_expr_loc_or_input_loc (t),
6394 "accessing %qD member instead of initialized "
6395 "%qD member in constant expression",
6396 index, CONSTRUCTOR_ELT (*valp, 0)->index);
6397 else
6398 error_at (cp_expr_loc_or_input_loc (t),
6399 "accessing uninitialized member %qD",
6400 index);
6401 if (is_access_expr)
6402 inform (DECL_SOURCE_LOCATION (index),
6403 "%qD does not implicitly begin its lifetime "
6404 "because %qT does not have a non-deleted "
6405 "trivial default constructor, use "
6406 "%<std::construct_at%> instead",
6407 index, inner);
6408 else
6409 inform (DECL_SOURCE_LOCATION (index),
6410 "initializing %qD requires a member access "
6411 "expression as the left operand of the assignment",
6412 index);
6414 *non_constant_p = true;
6416 else if (has_active_member && CONSTRUCTOR_NO_CLEARING (*valp))
6418 /* Diagnose changing the active union member while the union
6419 is in the process of being initialized. */
6420 if (!ctx->quiet)
6421 error_at (cp_expr_loc_or_input_loc (t),
6422 "change of the active member of a union "
6423 "from %qD to %qD during initialization",
6424 CONSTRUCTOR_ELT (*valp, 0)->index,
6425 index);
6426 *non_constant_p = true;
6428 no_zero_init = true;
6431 ctors.safe_push (valp);
6432 vec_safe_push (indexes, index);
6434 constructor_elt *cep
6435 = get_or_insert_ctor_field (*valp, index);
6436 index_pos_hints.safe_push (cep - CONSTRUCTOR_ELTS (*valp)->begin());
6438 if (code == UNION_TYPE)
6439 activated_union_member_p = true;
6441 valp = &cep->value;
6442 type = reftype;
6445 /* For initialization of an empty base, the original target will be
6446 *(base*)this, evaluation of which resolves to the object
6447 argument, which has the derived type rather than the base type. */
6448 if (!empty_base && !(same_type_ignoring_top_level_qualifiers_p
6449 (initialized_type (init), type)))
6451 gcc_assert (is_empty_class (TREE_TYPE (target)));
6452 empty_base = true;
6455 /* Detect modifying a constant object in constexpr evaluation.
6456 We have found a const object that is being modified. Figure out
6457 if we need to issue an error. Consider
6459 struct A {
6460 int n;
6461 constexpr A() : n(1) { n = 2; } // #1
6463 struct B {
6464 const A a;
6465 constexpr B() { a.n = 3; } // #2
6467 constexpr B b{};
6469 #1 is OK, since we're modifying an object under construction, but
6470 #2 is wrong, since "a" is const and has been fully constructed.
6471 To track it, we use the TREE_READONLY bit in the object's CONSTRUCTOR
6472 which means that the object is read-only. For the example above, the
6473 *ctors stack at the point of #2 will look like:
6475 ctors[0] = {.a={.n=2}} TREE_READONLY = 0
6476 ctors[1] = {.n=2} TREE_READONLY = 1
6478 and we're modifying "b.a", so we search the stack and see if the
6479 constructor for "b.a" has already run. */
6480 if (const_object_being_modified)
6482 bool fail = false;
6483 tree const_objtype
6484 = strip_array_types (TREE_TYPE (const_object_being_modified));
6485 if (!CLASS_TYPE_P (const_objtype))
6486 fail = true;
6487 else
6489 /* [class.ctor]p5 "A constructor can be invoked for a const,
6490 volatile, or const volatile object. const and volatile
6491 semantics are not applied on an object under construction.
6492 They come into effect when the constructor for the most
6493 derived object ends." */
6494 for (tree *elt : ctors)
6495 if (same_type_ignoring_top_level_qualifiers_p
6496 (TREE_TYPE (const_object_being_modified), TREE_TYPE (*elt)))
6498 fail = TREE_READONLY (*elt);
6499 break;
6502 if (fail)
6504 if (!ctx->quiet)
6505 modifying_const_object_error (t, const_object_being_modified);
6506 *non_constant_p = true;
6507 return t;
6511 if (!preeval)
6513 /* We're handling an INIT_EXPR of class type, so the value of the
6514 initializer can depend on the object it's initializing. */
6516 /* Create a new CONSTRUCTOR in case evaluation of the initializer
6517 wants to modify it. */
6518 if (*valp == NULL_TREE)
6520 *valp = build_constructor (type, NULL);
6521 CONSTRUCTOR_NO_CLEARING (*valp) = no_zero_init;
6523 new_ctx.ctor = empty_base ? NULL_TREE : *valp;
6524 new_ctx.object = target;
6525 /* Avoid temporary materialization when initializing from a TARGET_EXPR.
6526 We don't need to mess with AGGR_EXPR_SLOT/VEC_INIT_EXPR_SLOT because
6527 expansion of those trees uses ctx instead. */
6528 if (TREE_CODE (init) == TARGET_EXPR)
6529 if (tree tinit = TARGET_EXPR_INITIAL (init))
6530 init = tinit;
6531 init = cxx_eval_constant_expression (&new_ctx, init, vc_prvalue,
6532 non_constant_p, overflow_p);
6533 /* The hash table might have moved since the get earlier, and the
6534 initializer might have mutated the underlying CONSTRUCTORs, so we must
6535 recompute VALP. */
6536 valp = ctx->global->get_value_ptr (object);
6537 for (unsigned i = 0; i < vec_safe_length (indexes); i++)
6539 ctors[i] = valp;
6540 constructor_elt *cep
6541 = get_or_insert_ctor_field (*valp, indexes[i], index_pos_hints[i]);
6542 valp = &cep->value;
6546 if (*non_constant_p)
6547 return t;
6549 /* Don't share a CONSTRUCTOR that might be changed later. */
6550 init = unshare_constructor (init);
6552 gcc_checking_assert (!*valp || (same_type_ignoring_top_level_qualifiers_p
6553 (TREE_TYPE (*valp), type)));
6554 if (empty_base)
6556 /* Just evaluate the initializer and return, since there's no actual data
6557 to store, and we didn't build a CONSTRUCTOR. */
6558 if (!*valp)
6560 /* But do make sure we have something in *valp. */
6561 *valp = build_constructor (type, nullptr);
6562 CONSTRUCTOR_NO_CLEARING (*valp) = no_zero_init;
6565 else if (*valp && TREE_CODE (*valp) == CONSTRUCTOR
6566 && TREE_CODE (init) == CONSTRUCTOR)
6568 /* An outer ctx->ctor might be pointing to *valp, so replace
6569 its contents. */
6570 CONSTRUCTOR_ELTS (*valp) = CONSTRUCTOR_ELTS (init);
6571 TREE_CONSTANT (*valp) = TREE_CONSTANT (init);
6572 TREE_SIDE_EFFECTS (*valp) = TREE_SIDE_EFFECTS (init);
6573 CONSTRUCTOR_NO_CLEARING (*valp)
6574 = CONSTRUCTOR_NO_CLEARING (init);
6576 else
6577 *valp = init;
6579 /* After initialization, 'const' semantics apply to the value of the
6580 object. Make a note of this fact by marking the CONSTRUCTOR
6581 TREE_READONLY. */
6582 if (TREE_CODE (t) == INIT_EXPR
6583 && TREE_CODE (*valp) == CONSTRUCTOR
6584 && TYPE_READONLY (type))
6586 if (INDIRECT_REF_P (target)
6587 && (is_this_parameter
6588 (tree_strip_nop_conversions (TREE_OPERAND (target, 0)))))
6589 /* We've just initialized '*this' (perhaps via the target
6590 constructor of a delegating constructor). Leave it up to the
6591 caller that set 'this' to set TREE_READONLY appropriately. */
6592 gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
6593 (TREE_TYPE (target), type) || empty_base);
6594 else
6595 TREE_READONLY (*valp) = true;
6598 /* Update TREE_CONSTANT and TREE_SIDE_EFFECTS on enclosing
6599 CONSTRUCTORs, if any. */
6600 bool c = TREE_CONSTANT (init);
6601 bool s = TREE_SIDE_EFFECTS (init);
6602 if (!indexes->is_empty ())
6604 tree last = indexes->last ();
6605 if (TREE_CODE (last) == REALPART_EXPR
6606 || TREE_CODE (last) == IMAGPART_EXPR)
6608 /* And canonicalize COMPLEX_EXPR into COMPLEX_CST if
6609 possible. */
6610 tree *cexpr = ctors.last ();
6611 if (tree c = const_binop (COMPLEX_EXPR, TREE_TYPE (*cexpr),
6612 TREE_OPERAND (*cexpr, 0),
6613 TREE_OPERAND (*cexpr, 1)))
6614 *cexpr = c;
6615 else
6617 TREE_CONSTANT (*cexpr)
6618 = (TREE_CONSTANT (TREE_OPERAND (*cexpr, 0))
6619 & TREE_CONSTANT (TREE_OPERAND (*cexpr, 1)));
6620 TREE_SIDE_EFFECTS (*cexpr)
6621 = (TREE_SIDE_EFFECTS (TREE_OPERAND (*cexpr, 0))
6622 | TREE_SIDE_EFFECTS (TREE_OPERAND (*cexpr, 1)));
6624 c = TREE_CONSTANT (*cexpr);
6625 s = TREE_SIDE_EFFECTS (*cexpr);
6628 if (!c || s || activated_union_member_p)
6629 for (tree *elt : ctors)
6631 if (TREE_CODE (*elt) != CONSTRUCTOR)
6632 continue;
6633 if (!c)
6634 TREE_CONSTANT (*elt) = false;
6635 if (s)
6636 TREE_SIDE_EFFECTS (*elt) = true;
6637 /* Clear CONSTRUCTOR_NO_CLEARING since we've activated a member of
6638 this union. */
6639 if (TREE_CODE (TREE_TYPE (*elt)) == UNION_TYPE)
6640 CONSTRUCTOR_NO_CLEARING (*elt) = false;
6643 if (lval)
6644 return target;
6645 else
6646 return init;
6649 /* Evaluate a ++ or -- expression. */
6651 static tree
6652 cxx_eval_increment_expression (const constexpr_ctx *ctx, tree t,
6653 value_cat lval,
6654 bool *non_constant_p, bool *overflow_p)
6656 enum tree_code code = TREE_CODE (t);
6657 tree type = TREE_TYPE (t);
6658 tree op = TREE_OPERAND (t, 0);
6659 tree offset = TREE_OPERAND (t, 1);
6660 gcc_assert (TREE_CONSTANT (offset));
6662 /* OFFSET is constant, but perhaps not constant enough. We need to
6663 e.g. bash FLOAT_EXPRs to REAL_CSTs. */
6664 offset = fold_simple (offset);
6666 /* The operand as an lvalue. */
6667 op = cxx_eval_constant_expression (ctx, op, vc_glvalue,
6668 non_constant_p, overflow_p);
6670 /* The operand as an rvalue. */
6671 tree val
6672 = cxx_eval_constant_expression (ctx, op, vc_prvalue,
6673 non_constant_p, overflow_p);
6674 /* Don't VERIFY_CONSTANT if this might be dealing with a pointer to
6675 a local array in a constexpr function. */
6676 bool ptr = INDIRECT_TYPE_P (TREE_TYPE (val));
6677 if (!ptr)
6678 VERIFY_CONSTANT (val);
6680 /* The modified value. */
6681 bool inc = (code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR);
6682 tree mod;
6683 if (INDIRECT_TYPE_P (type))
6685 /* The middle end requires pointers to use POINTER_PLUS_EXPR. */
6686 offset = convert_to_ptrofftype (offset);
6687 if (!inc)
6688 offset = fold_build1 (NEGATE_EXPR, TREE_TYPE (offset), offset);
6689 mod = fold_build2 (POINTER_PLUS_EXPR, type, val, offset);
6691 else if (c_promoting_integer_type_p (type)
6692 && !TYPE_UNSIGNED (type)
6693 && TYPE_PRECISION (type) < TYPE_PRECISION (integer_type_node))
6695 offset = fold_convert (integer_type_node, offset);
6696 mod = fold_convert (integer_type_node, val);
6697 tree t = fold_build2 (inc ? PLUS_EXPR : MINUS_EXPR, integer_type_node,
6698 mod, offset);
6699 mod = fold_convert (type, t);
6700 if (TREE_OVERFLOW_P (mod) && !TREE_OVERFLOW_P (t))
6701 TREE_OVERFLOW (mod) = false;
6703 else
6704 mod = fold_build2 (inc ? PLUS_EXPR : MINUS_EXPR, type, val, offset);
6705 if (!ptr)
6706 VERIFY_CONSTANT (mod);
6708 /* Storing the modified value. */
6709 tree store = build2_loc (cp_expr_loc_or_loc (t, input_location),
6710 MODIFY_EXPR, type, op, mod);
6711 mod = cxx_eval_constant_expression (ctx, store, lval,
6712 non_constant_p, overflow_p);
6713 ggc_free (store);
6714 if (*non_constant_p)
6715 return t;
6717 /* And the value of the expression. */
6718 if (code == PREINCREMENT_EXPR || code == PREDECREMENT_EXPR)
6719 /* Prefix ops are lvalues, but the caller might want an rvalue;
6720 lval has already been taken into account in the store above. */
6721 return mod;
6722 else
6723 /* Postfix ops are rvalues. */
6724 return val;
6727 /* Predicates for the meaning of *jump_target. */
6729 static bool
6730 returns (tree *jump_target)
6732 return *jump_target
6733 && TREE_CODE (*jump_target) == RETURN_EXPR;
6736 static bool
6737 breaks (tree *jump_target)
6739 return *jump_target
6740 && ((TREE_CODE (*jump_target) == LABEL_DECL
6741 && LABEL_DECL_BREAK (*jump_target))
6742 || TREE_CODE (*jump_target) == BREAK_STMT
6743 || TREE_CODE (*jump_target) == EXIT_EXPR);
6746 static bool
6747 continues (tree *jump_target)
6749 return *jump_target
6750 && ((TREE_CODE (*jump_target) == LABEL_DECL
6751 && LABEL_DECL_CONTINUE (*jump_target))
6752 || TREE_CODE (*jump_target) == CONTINUE_STMT);
6756 static bool
6757 switches (tree *jump_target)
6759 return *jump_target
6760 && TREE_CODE (*jump_target) == INTEGER_CST;
6763 /* Subroutine of cxx_eval_statement_list. Determine whether the statement
6764 STMT matches *jump_target. If we're looking for a case label and we see
6765 the default label, note it in ctx->css_state. */
6767 static bool
6768 label_matches (const constexpr_ctx *ctx, tree *jump_target, tree stmt)
6770 switch (TREE_CODE (*jump_target))
6772 case LABEL_DECL:
6773 if (TREE_CODE (stmt) == LABEL_EXPR
6774 && LABEL_EXPR_LABEL (stmt) == *jump_target)
6775 return true;
6776 break;
6778 case INTEGER_CST:
6779 if (TREE_CODE (stmt) == CASE_LABEL_EXPR)
6781 gcc_assert (ctx->css_state != NULL);
6782 if (!CASE_LOW (stmt))
6784 /* default: should appear just once in a SWITCH_EXPR
6785 body (excluding nested SWITCH_EXPR). */
6786 gcc_assert (*ctx->css_state != css_default_seen);
6787 /* When evaluating SWITCH_EXPR body for the second time,
6788 return true for the default: label. */
6789 if (*ctx->css_state == css_default_processing)
6790 return true;
6791 *ctx->css_state = css_default_seen;
6793 else if (CASE_HIGH (stmt))
6795 if (tree_int_cst_le (CASE_LOW (stmt), *jump_target)
6796 && tree_int_cst_le (*jump_target, CASE_HIGH (stmt)))
6797 return true;
6799 else if (tree_int_cst_equal (*jump_target, CASE_LOW (stmt)))
6800 return true;
6802 break;
6804 case BREAK_STMT:
6805 case CONTINUE_STMT:
6806 /* These two are handled directly in cxx_eval_loop_expr by testing
6807 breaks (jump_target) or continues (jump_target). */
6808 break;
6810 default:
6811 gcc_unreachable ();
6813 return false;
6816 /* Evaluate a STATEMENT_LIST for side-effects. Handles various jump
6817 semantics, for switch, break, continue, and return. */
6819 static tree
6820 cxx_eval_statement_list (const constexpr_ctx *ctx, tree t,
6821 bool *non_constant_p, bool *overflow_p,
6822 tree *jump_target)
6824 tree local_target;
6825 /* In a statement-expression we want to return the last value.
6826 For empty statement expression return void_node. */
6827 tree r = void_node;
6828 if (!jump_target)
6830 local_target = NULL_TREE;
6831 jump_target = &local_target;
6833 for (tree_stmt_iterator i = tsi_start (t); !tsi_end_p (i); ++i)
6835 tree stmt = *i;
6837 /* We've found a continue, so skip everything until we reach
6838 the label its jumping to. */
6839 if (continues (jump_target))
6841 if (label_matches (ctx, jump_target, stmt))
6842 /* Found it. */
6843 *jump_target = NULL_TREE;
6844 else
6845 continue;
6847 if (TREE_CODE (stmt) == DEBUG_BEGIN_STMT)
6848 continue;
6850 value_cat lval = vc_discard;
6851 /* The result of a statement-expression is not wrapped in EXPR_STMT. */
6852 if (tsi_one_before_end_p (i) && TREE_CODE (stmt) != EXPR_STMT)
6853 lval = vc_prvalue;
6855 r = cxx_eval_constant_expression (ctx, stmt, lval,
6856 non_constant_p, overflow_p,
6857 jump_target);
6858 if (*non_constant_p)
6859 break;
6860 if (returns (jump_target) || breaks (jump_target))
6861 break;
6863 if (*jump_target && jump_target == &local_target)
6865 /* We aren't communicating the jump to our caller, so give up. We don't
6866 need to support evaluation of jumps out of statement-exprs. */
6867 if (!ctx->quiet)
6868 error_at (cp_expr_loc_or_input_loc (r),
6869 "statement is not a constant expression");
6870 *non_constant_p = true;
6872 return r;
6875 /* Evaluate a LOOP_EXPR for side-effects. Handles break and return
6876 semantics; continue semantics are covered by cxx_eval_statement_list. */
6878 static tree
6879 cxx_eval_loop_expr (const constexpr_ctx *ctx, tree t,
6880 bool *non_constant_p, bool *overflow_p,
6881 tree *jump_target)
6883 tree local_target;
6884 if (!jump_target)
6886 local_target = NULL_TREE;
6887 jump_target = &local_target;
6890 tree body, cond = NULL_TREE, expr = NULL_TREE;
6891 int count = 0;
6892 switch (TREE_CODE (t))
6894 case LOOP_EXPR:
6895 body = LOOP_EXPR_BODY (t);
6896 break;
6897 case DO_STMT:
6898 body = DO_BODY (t);
6899 cond = DO_COND (t);
6900 break;
6901 case WHILE_STMT:
6902 body = WHILE_BODY (t);
6903 cond = WHILE_COND (t);
6904 count = -1;
6905 break;
6906 case FOR_STMT:
6907 if (FOR_INIT_STMT (t))
6908 cxx_eval_constant_expression (ctx, FOR_INIT_STMT (t), vc_discard,
6909 non_constant_p, overflow_p, jump_target);
6910 if (*non_constant_p)
6911 return NULL_TREE;
6912 body = FOR_BODY (t);
6913 cond = FOR_COND (t);
6914 expr = FOR_EXPR (t);
6915 count = -1;
6916 break;
6917 default:
6918 gcc_unreachable ();
6922 if (count != -1)
6924 if (body)
6925 cxx_eval_constant_expression (ctx, body, vc_discard,
6926 non_constant_p, overflow_p,
6927 jump_target);
6928 if (breaks (jump_target))
6930 *jump_target = NULL_TREE;
6931 break;
6934 if (TREE_CODE (t) != LOOP_EXPR && continues (jump_target))
6935 *jump_target = NULL_TREE;
6937 if (expr)
6938 cxx_eval_constant_expression (ctx, expr, vc_prvalue,
6939 non_constant_p, overflow_p,
6940 jump_target);
6943 if (cond)
6945 tree res
6946 = cxx_eval_constant_expression (ctx, cond, vc_prvalue,
6947 non_constant_p, overflow_p,
6948 jump_target);
6949 if (res)
6951 if (verify_constant (res, ctx->quiet, non_constant_p,
6952 overflow_p))
6953 break;
6954 if (integer_zerop (res))
6955 break;
6957 else
6958 gcc_assert (*jump_target);
6961 if (++count >= constexpr_loop_limit)
6963 if (!ctx->quiet)
6964 error_at (cp_expr_loc_or_input_loc (t),
6965 "%<constexpr%> loop iteration count exceeds limit of %d "
6966 "(use %<-fconstexpr-loop-limit=%> to increase the limit)",
6967 constexpr_loop_limit);
6968 *non_constant_p = true;
6969 break;
6972 while (!returns (jump_target)
6973 && !breaks (jump_target)
6974 && !continues (jump_target)
6975 && (!switches (jump_target) || count == 0)
6976 && !*non_constant_p);
6978 return NULL_TREE;
6981 /* Evaluate a SWITCH_EXPR for side-effects. Handles switch and break jump
6982 semantics. */
6984 static tree
6985 cxx_eval_switch_expr (const constexpr_ctx *ctx, tree t,
6986 bool *non_constant_p, bool *overflow_p,
6987 tree *jump_target)
6989 tree cond
6990 = TREE_CODE (t) == SWITCH_STMT ? SWITCH_STMT_COND (t) : SWITCH_COND (t);
6991 cond = cxx_eval_constant_expression (ctx, cond, vc_prvalue,
6992 non_constant_p, overflow_p);
6993 VERIFY_CONSTANT (cond);
6994 *jump_target = cond;
6996 tree body
6997 = TREE_CODE (t) == SWITCH_STMT ? SWITCH_STMT_BODY (t) : SWITCH_BODY (t);
6998 constexpr_ctx new_ctx = *ctx;
6999 constexpr_switch_state css = css_default_not_seen;
7000 new_ctx.css_state = &css;
7001 cxx_eval_constant_expression (&new_ctx, body, vc_discard,
7002 non_constant_p, overflow_p, jump_target);
7003 if (switches (jump_target) && css == css_default_seen)
7005 /* If the SWITCH_EXPR body has default: label, process it once again,
7006 this time instructing label_matches to return true for default:
7007 label on switches (jump_target). */
7008 css = css_default_processing;
7009 cxx_eval_constant_expression (&new_ctx, body, vc_discard,
7010 non_constant_p, overflow_p, jump_target);
7012 if (breaks (jump_target) || switches (jump_target))
7013 *jump_target = NULL_TREE;
7014 return NULL_TREE;
7017 /* Find the object of TYPE under initialization in CTX. */
7019 static tree
7020 lookup_placeholder (const constexpr_ctx *ctx, value_cat lval, tree type)
7022 if (!ctx)
7023 return NULL_TREE;
7025 /* Prefer the outermost matching object, but don't cross
7026 CONSTRUCTOR_PLACEHOLDER_BOUNDARY constructors. */
7027 if (ctx->ctor && !CONSTRUCTOR_PLACEHOLDER_BOUNDARY (ctx->ctor))
7028 if (tree outer_ob = lookup_placeholder (ctx->parent, lval, type))
7029 return outer_ob;
7031 /* We could use ctx->object unconditionally, but using ctx->ctor when we
7032 can is a minor optimization. */
7033 if (!lval && ctx->ctor && same_type_p (TREE_TYPE (ctx->ctor), type))
7034 return ctx->ctor;
7036 if (!ctx->object)
7037 return NULL_TREE;
7039 /* Since an object cannot have a field of its own type, we can search outward
7040 from ctx->object to find the unique containing object of TYPE. */
7041 tree ob = ctx->object;
7042 while (ob)
7044 if (same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (ob), type))
7045 break;
7046 if (handled_component_p (ob))
7047 ob = TREE_OPERAND (ob, 0);
7048 else
7049 ob = NULL_TREE;
7052 return ob;
7055 /* Complain about an attempt to evaluate inline assembly. If FUNDEF_P is
7056 true, we're checking a constexpr function body. */
7058 static void
7059 inline_asm_in_constexpr_error (location_t loc, bool fundef_p)
7061 auto_diagnostic_group d;
7062 if (constexpr_error (loc, fundef_p, "inline assembly is not a "
7063 "constant expression"))
7064 inform (loc, "only unevaluated inline assembly is allowed in a "
7065 "%<constexpr%> function in C++20");
7068 /* We're getting the constant value of DECL in a manifestly constant-evaluated
7069 context; maybe complain about that. */
7071 static void
7072 maybe_warn_about_constant_value (location_t loc, tree decl)
7074 static bool explained = false;
7075 if (cxx_dialect >= cxx17
7076 && warn_interference_size
7077 && !OPTION_SET_P (param_destruct_interfere_size)
7078 && DECL_CONTEXT (decl) == std_node
7079 && id_equal (DECL_NAME (decl), "hardware_destructive_interference_size")
7080 && (LOCATION_FILE (input_location) != main_input_filename
7081 || module_exporting_p ())
7082 && warning_at (loc, OPT_Winterference_size, "use of %qD", decl)
7083 && !explained)
7085 explained = true;
7086 inform (loc, "its value can vary between compiler versions or "
7087 "with different %<-mtune%> or %<-mcpu%> flags");
7088 inform (loc, "if this use is part of a public ABI, change it to "
7089 "instead use a constant variable you define");
7090 inform (loc, "the default value for the current CPU tuning "
7091 "is %d bytes", param_destruct_interfere_size);
7092 inform (loc, "you can stabilize this value with %<--param "
7093 "hardware_destructive_interference_size=%d%>, or disable "
7094 "this warning with %<-Wno-interference-size%>",
7095 param_destruct_interfere_size);
7099 /* For element type ELT_TYPE, return the appropriate type of the heap object
7100 containing such element(s). COOKIE_SIZE is NULL or the size of cookie
7101 in bytes. If COOKIE_SIZE is NULL, return array type
7102 ELT_TYPE[FULL_SIZE / sizeof(ELT_TYPE)], otherwise return
7103 struct { size_t[COOKIE_SIZE/sizeof(size_t)]; ELT_TYPE[N]; }
7104 where N is is computed such that the size of the struct fits into FULL_SIZE.
7105 If ARG_SIZE is non-NULL, it is the first argument to the new operator.
7106 It should be passed if ELT_TYPE is zero sized type in which case FULL_SIZE
7107 will be also 0 and so it is not possible to determine the actual array
7108 size. CTX, NON_CONSTANT_P and OVERFLOW_P are used during constant
7109 expression evaluation of subexpressions of ARG_SIZE. */
7111 static tree
7112 build_new_constexpr_heap_type (const constexpr_ctx *ctx, tree elt_type,
7113 tree cookie_size, tree full_size, tree arg_size,
7114 bool *non_constant_p, bool *overflow_p)
7116 gcc_assert (cookie_size == NULL_TREE || tree_fits_uhwi_p (cookie_size));
7117 gcc_assert (tree_fits_uhwi_p (full_size));
7118 unsigned HOST_WIDE_INT csz = cookie_size ? tree_to_uhwi (cookie_size) : 0;
7119 if (arg_size)
7121 STRIP_NOPS (arg_size);
7122 if (cookie_size)
7124 if (TREE_CODE (arg_size) != PLUS_EXPR)
7125 arg_size = NULL_TREE;
7126 else if (TREE_CODE (TREE_OPERAND (arg_size, 0)) == INTEGER_CST
7127 && tree_int_cst_equal (cookie_size,
7128 TREE_OPERAND (arg_size, 0)))
7130 arg_size = TREE_OPERAND (arg_size, 1);
7131 STRIP_NOPS (arg_size);
7133 else if (TREE_CODE (TREE_OPERAND (arg_size, 1)) == INTEGER_CST
7134 && tree_int_cst_equal (cookie_size,
7135 TREE_OPERAND (arg_size, 1)))
7137 arg_size = TREE_OPERAND (arg_size, 0);
7138 STRIP_NOPS (arg_size);
7140 else
7141 arg_size = NULL_TREE;
7143 if (arg_size && TREE_CODE (arg_size) == MULT_EXPR)
7145 tree op0 = TREE_OPERAND (arg_size, 0);
7146 tree op1 = TREE_OPERAND (arg_size, 1);
7147 if (integer_zerop (op0))
7148 arg_size
7149 = cxx_eval_constant_expression (ctx, op1, vc_prvalue,
7150 non_constant_p, overflow_p);
7151 else if (integer_zerop (op1))
7152 arg_size
7153 = cxx_eval_constant_expression (ctx, op0, vc_prvalue,
7154 non_constant_p, overflow_p);
7155 else
7156 arg_size = NULL_TREE;
7158 else
7159 arg_size = NULL_TREE;
7162 unsigned HOST_WIDE_INT fsz = tree_to_uhwi (arg_size ? arg_size : full_size);
7163 if (!arg_size)
7165 unsigned HOST_WIDE_INT esz = int_size_in_bytes (elt_type);
7166 gcc_assert (fsz >= csz);
7167 fsz -= csz;
7168 if (esz)
7169 fsz /= esz;
7171 tree itype2 = build_index_type (size_int (fsz - 1));
7172 if (!cookie_size)
7173 return build_cplus_array_type (elt_type, itype2);
7174 return build_new_constexpr_heap_type (elt_type, cookie_size, itype2);
7177 /* Attempt to reduce the expression T to a constant value.
7178 On failure, issue diagnostic and return error_mark_node. */
7179 /* FIXME unify with c_fully_fold */
7180 /* FIXME overflow_p is too global */
7182 static tree
7183 cxx_eval_constant_expression (const constexpr_ctx *ctx, tree t,
7184 value_cat lval,
7185 bool *non_constant_p, bool *overflow_p,
7186 tree *jump_target /* = NULL */)
7188 if (jump_target && *jump_target)
7190 /* If we are jumping, ignore all statements/expressions except those
7191 that could have LABEL_EXPR or CASE_LABEL_EXPR in their bodies. */
7192 switch (TREE_CODE (t))
7194 case BIND_EXPR:
7195 case STATEMENT_LIST:
7196 case LOOP_EXPR:
7197 case COND_EXPR:
7198 case IF_STMT:
7199 case DO_STMT:
7200 case WHILE_STMT:
7201 case FOR_STMT:
7202 break;
7203 case LABEL_EXPR:
7204 case CASE_LABEL_EXPR:
7205 if (label_matches (ctx, jump_target, t))
7206 /* Found it. */
7207 *jump_target = NULL_TREE;
7208 return NULL_TREE;
7209 default:
7210 return NULL_TREE;
7213 if (error_operand_p (t))
7215 *non_constant_p = true;
7216 return t;
7219 /* Change the input location to the currently processed expression for
7220 better error messages when a subexpression has no location. */
7221 location_t loc = cp_expr_loc_or_input_loc (t);
7222 iloc_sentinel sentinel (loc);
7224 STRIP_ANY_LOCATION_WRAPPER (t);
7226 if (CONSTANT_CLASS_P (t))
7228 if (TREE_OVERFLOW (t))
7230 if (!ctx->quiet)
7231 permerror (input_location, "overflow in constant expression");
7232 if (!flag_permissive || ctx->quiet)
7233 *overflow_p = true;
7236 if (TREE_CODE (t) == INTEGER_CST
7237 && TYPE_PTR_P (TREE_TYPE (t))
7238 /* INTEGER_CST with pointer-to-method type is only used
7239 for a virtual method in a pointer to member function.
7240 Don't reject those. */
7241 && TREE_CODE (TREE_TYPE (TREE_TYPE (t))) != METHOD_TYPE
7242 && !integer_zerop (t))
7244 if (!ctx->quiet)
7245 error ("value %qE of type %qT is not a constant expression",
7246 t, TREE_TYPE (t));
7247 *non_constant_p = true;
7250 return t;
7253 /* Avoid excessively long constexpr evaluations. */
7254 if (++ctx->global->constexpr_ops_count >= constexpr_ops_limit)
7256 if (!ctx->quiet)
7257 error_at (loc,
7258 "%<constexpr%> evaluation operation count exceeds limit of "
7259 "%wd (use %<-fconstexpr-ops-limit=%> to increase the limit)",
7260 constexpr_ops_limit);
7261 ctx->global->constexpr_ops_count = INTTYPE_MINIMUM (HOST_WIDE_INT);
7262 *non_constant_p = true;
7263 return t;
7266 constexpr_ctx new_ctx;
7267 tree r = t;
7269 tree_code tcode = TREE_CODE (t);
7270 switch (tcode)
7272 case RESULT_DECL:
7273 if (lval)
7274 return t;
7275 /* We ask for an rvalue for the RESULT_DECL when indirecting
7276 through an invisible reference, or in named return value
7277 optimization. */
7278 if (tree v = ctx->global->get_value (t))
7279 return v;
7280 else
7282 if (!ctx->quiet)
7283 error ("%qE is not a constant expression", t);
7284 *non_constant_p = true;
7286 break;
7288 case VAR_DECL:
7289 if (DECL_HAS_VALUE_EXPR_P (t))
7291 if (is_normal_capture_proxy (t)
7292 && current_function_decl == DECL_CONTEXT (t))
7294 /* Function parms aren't constexpr within the function
7295 definition, so don't try to look at the closure. But if the
7296 captured variable is constant, try to evaluate it directly. */
7297 r = DECL_CAPTURED_VARIABLE (t);
7298 tree type = TREE_TYPE (t);
7299 if (TYPE_REF_P (type) != TYPE_REF_P (TREE_TYPE (r)))
7301 /* Adjust r to match the reference-ness of t. */
7302 if (TYPE_REF_P (type))
7303 r = build_address (r);
7304 else
7305 r = convert_from_reference (r);
7308 else
7309 r = DECL_VALUE_EXPR (t);
7310 return cxx_eval_constant_expression (ctx, r, lval, non_constant_p,
7311 overflow_p);
7313 /* fall through */
7314 case CONST_DECL:
7315 /* We used to not check lval for CONST_DECL, but darwin.cc uses
7316 CONST_DECL for aggregate constants. */
7317 if (lval)
7318 return t;
7319 else if (t == ctx->object)
7320 return ctx->ctor;
7321 if (VAR_P (t))
7323 if (tree v = ctx->global->get_value (t))
7325 r = v;
7326 break;
7328 if (ctx->global->is_outside_lifetime (t))
7330 if (!ctx->quiet)
7331 outside_lifetime_error (loc, t);
7332 *non_constant_p = true;
7333 break;
7336 if (ctx->manifestly_const_eval == mce_true)
7337 maybe_warn_about_constant_value (loc, t);
7338 if (COMPLETE_TYPE_P (TREE_TYPE (t))
7339 && is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
7341 /* If the class is empty, we aren't actually loading anything. */
7342 r = build_constructor (TREE_TYPE (t), NULL);
7343 TREE_CONSTANT (r) = true;
7345 else if (ctx->strict)
7346 r = decl_really_constant_value (t, /*unshare_p=*/false);
7347 else
7348 r = decl_constant_value (t, /*unshare_p=*/false);
7349 if (TREE_CODE (r) == TARGET_EXPR
7350 && TREE_CODE (TARGET_EXPR_INITIAL (r)) == CONSTRUCTOR)
7351 r = TARGET_EXPR_INITIAL (r);
7352 if (DECL_P (r)
7353 /* P2280 allows references to unknown. */
7354 && !(VAR_P (t) && TYPE_REF_P (TREE_TYPE (t))))
7356 if (!ctx->quiet)
7357 non_const_var_error (loc, r, /*fundef_p*/false);
7358 *non_constant_p = true;
7360 break;
7362 case DEBUG_BEGIN_STMT:
7363 /* ??? It might be nice to retain this information somehow, so
7364 as to be able to step into a constexpr function call. */
7365 /* Fall through. */
7367 case FUNCTION_DECL:
7368 case TEMPLATE_DECL:
7369 case LABEL_DECL:
7370 case LABEL_EXPR:
7371 case CASE_LABEL_EXPR:
7372 case PREDICT_EXPR:
7373 return t;
7375 case PARM_DECL:
7376 if (lval && !TYPE_REF_P (TREE_TYPE (t)))
7377 /* glvalue use. */;
7378 else if (tree v = ctx->global->get_value (t))
7379 r = v;
7380 else if (lval)
7381 /* Defer in case this is only used for its type. */;
7382 else if (ctx->global->is_outside_lifetime (t))
7384 if (!ctx->quiet)
7385 outside_lifetime_error (loc, t);
7386 *non_constant_p = true;
7387 break;
7389 else if (COMPLETE_TYPE_P (TREE_TYPE (t))
7390 && is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
7392 /* If the class is empty, we aren't actually loading anything. */
7393 r = build_constructor (TREE_TYPE (t), NULL);
7394 TREE_CONSTANT (r) = true;
7396 else if (TYPE_REF_P (TREE_TYPE (t)))
7397 /* P2280 allows references to unknown... */;
7398 else if (is_this_parameter (t))
7399 /* ...as well as the this pointer. */;
7400 else
7402 if (!ctx->quiet)
7403 error ("%qE is not a constant expression", t);
7404 *non_constant_p = true;
7406 break;
7408 case CALL_EXPR:
7409 case AGGR_INIT_EXPR:
7410 r = cxx_eval_call_expression (ctx, t, lval,
7411 non_constant_p, overflow_p);
7412 break;
7414 case DECL_EXPR:
7416 r = DECL_EXPR_DECL (t);
7417 if (TREE_CODE (r) == USING_DECL)
7419 r = void_node;
7420 break;
7423 if (VAR_P (r)
7424 && (TREE_STATIC (r)
7425 || (CP_DECL_THREAD_LOCAL_P (r) && !DECL_REALLY_EXTERN (r)))
7426 /* Allow __FUNCTION__ etc. */
7427 && !DECL_ARTIFICIAL (r)
7428 && !decl_constant_var_p (r))
7430 if (!ctx->quiet)
7432 if (CP_DECL_THREAD_LOCAL_P (r))
7433 error_at (loc, "control passes through definition of %qD "
7434 "with thread storage duration", r);
7435 else
7436 error_at (loc, "control passes through definition of %qD "
7437 "with static storage duration", r);
7439 *non_constant_p = true;
7440 break;
7443 /* make_rtl_for_nonlocal_decl could have deferred emission of
7444 a local static var, but if it appears in a statement expression
7445 which is constant expression evaluated to e.g. just the address
7446 of the variable, its DECL_EXPR will never be seen during
7447 gimple lowering's record_vars_into as the statement expression
7448 will not be in the IL at all. */
7449 if (VAR_P (r)
7450 && TREE_STATIC (r)
7451 && !DECL_REALLY_EXTERN (r)
7452 && DECL_FUNCTION_SCOPE_P (r)
7453 && !var_in_maybe_constexpr_fn (r)
7454 && decl_constant_var_p (r))
7456 varpool_node *node = varpool_node::get (r);
7457 if (node == NULL || !node->definition)
7458 rest_of_decl_compilation (r, 0, at_eof);
7461 if (AGGREGATE_TYPE_P (TREE_TYPE (r))
7462 || VECTOR_TYPE_P (TREE_TYPE (r)))
7464 new_ctx = *ctx;
7465 new_ctx.object = r;
7466 new_ctx.ctor = build_constructor (TREE_TYPE (r), NULL);
7467 CONSTRUCTOR_NO_CLEARING (new_ctx.ctor) = true;
7468 ctx->global->put_value (r, new_ctx.ctor);
7469 ctx = &new_ctx;
7472 if (tree init = DECL_INITIAL (r))
7474 init = cxx_eval_constant_expression (ctx, init, vc_prvalue,
7475 non_constant_p, overflow_p);
7476 /* Don't share a CONSTRUCTOR that might be changed. */
7477 init = unshare_constructor (init);
7478 /* Remember that a constant object's constructor has already
7479 run. */
7480 if (CLASS_TYPE_P (TREE_TYPE (r))
7481 && CP_TYPE_CONST_P (TREE_TYPE (r)))
7482 TREE_READONLY (init) = true;
7483 ctx->global->put_value (r, init);
7485 else if (ctx == &new_ctx)
7486 /* We gave it a CONSTRUCTOR above. */;
7487 else
7488 ctx->global->put_value (r, NULL_TREE);
7490 break;
7492 case TARGET_EXPR:
7494 tree type = TREE_TYPE (t);
7496 if (!literal_type_p (type))
7498 if (!ctx->quiet)
7500 auto_diagnostic_group d;
7501 error ("temporary of non-literal type %qT in a "
7502 "constant expression", type);
7503 explain_non_literal_class (type);
7505 *non_constant_p = true;
7506 break;
7508 gcc_checking_assert (!TARGET_EXPR_DIRECT_INIT_P (t));
7509 /* Avoid evaluating a TARGET_EXPR more than once. */
7510 tree slot = TARGET_EXPR_SLOT (t);
7511 if (tree v = ctx->global->get_value (slot))
7513 if (lval)
7514 return slot;
7515 r = v;
7516 break;
7518 if ((AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type)))
7520 /* We're being expanded without an explicit target, so start
7521 initializing a new object; expansion with an explicit target
7522 strips the TARGET_EXPR before we get here. */
7523 new_ctx = *ctx;
7524 /* Link CTX to NEW_CTX so that lookup_placeholder can resolve
7525 any PLACEHOLDER_EXPR within the initializer that refers to the
7526 former object under construction. */
7527 new_ctx.parent = ctx;
7528 new_ctx.ctor = build_constructor (type, NULL);
7529 CONSTRUCTOR_NO_CLEARING (new_ctx.ctor) = true;
7530 new_ctx.object = slot;
7531 ctx->global->put_value (new_ctx.object, new_ctx.ctor);
7532 ctx = &new_ctx;
7534 /* Pass vc_prvalue because this indicates
7535 initialization of a temporary. */
7536 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1), vc_prvalue,
7537 non_constant_p, overflow_p);
7538 if (*non_constant_p)
7539 break;
7540 /* If the initializer is complex, evaluate it to initialize slot. */
7541 bool is_complex = target_expr_needs_replace (t);
7542 if (!is_complex)
7544 r = unshare_constructor (r);
7545 /* Adjust the type of the result to the type of the temporary. */
7546 r = adjust_temp_type (type, r);
7547 ctx->global->put_value (slot, r);
7549 if (TARGET_EXPR_CLEANUP (t) && !CLEANUP_EH_ONLY (t))
7550 ctx->global->cleanups->safe_push (TARGET_EXPR_CLEANUP (t));
7551 if (ctx->save_exprs)
7552 ctx->save_exprs->safe_push (slot);
7553 if (lval)
7554 return slot;
7555 if (is_complex)
7556 r = ctx->global->get_value (slot);
7558 break;
7560 case INIT_EXPR:
7561 case MODIFY_EXPR:
7562 gcc_assert (jump_target == NULL || *jump_target == NULL_TREE);
7563 r = cxx_eval_store_expression (ctx, t, lval,
7564 non_constant_p, overflow_p);
7565 break;
7567 case SCOPE_REF:
7568 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
7569 lval,
7570 non_constant_p, overflow_p);
7571 break;
7573 case RETURN_EXPR:
7574 if (TREE_OPERAND (t, 0) != NULL_TREE)
7575 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
7576 lval,
7577 non_constant_p, overflow_p);
7578 /* FALLTHRU */
7579 case BREAK_STMT:
7580 case CONTINUE_STMT:
7581 if (jump_target)
7582 *jump_target = t;
7583 else
7585 /* Can happen with ({ return true; }) && false; passed to
7586 maybe_constant_value. There is nothing to jump over in this
7587 case, and the bug will be diagnosed later. */
7588 gcc_assert (ctx->quiet);
7589 *non_constant_p = true;
7591 break;
7593 case SAVE_EXPR:
7594 /* Avoid evaluating a SAVE_EXPR more than once. */
7595 if (tree v = ctx->global->get_value (t))
7596 r = v;
7597 else
7599 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), vc_prvalue,
7600 non_constant_p, overflow_p);
7601 if (*non_constant_p)
7602 break;
7603 ctx->global->put_value (t, r);
7604 if (ctx->save_exprs)
7605 ctx->save_exprs->safe_push (t);
7607 break;
7609 case TRY_CATCH_EXPR:
7610 if (TREE_OPERAND (t, 0) == NULL_TREE)
7612 r = void_node;
7613 break;
7615 /* FALLTHRU */
7616 case NON_LVALUE_EXPR:
7617 case TRY_BLOCK:
7618 case MUST_NOT_THROW_EXPR:
7619 case EXPR_STMT:
7620 case EH_SPEC_BLOCK:
7621 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
7622 lval,
7623 non_constant_p, overflow_p,
7624 jump_target);
7625 break;
7627 case CLEANUP_POINT_EXPR:
7629 auto_vec<tree, 2> cleanups;
7630 vec<tree> *prev_cleanups = ctx->global->cleanups;
7631 ctx->global->cleanups = &cleanups;
7633 auto_vec<tree, 10> save_exprs;
7634 constexpr_ctx new_ctx = *ctx;
7635 new_ctx.save_exprs = &save_exprs;
7637 r = cxx_eval_constant_expression (&new_ctx, TREE_OPERAND (t, 0),
7638 lval,
7639 non_constant_p, overflow_p,
7640 jump_target);
7642 ctx->global->cleanups = prev_cleanups;
7643 unsigned int i;
7644 tree cleanup;
7645 /* Evaluate the cleanups. */
7646 FOR_EACH_VEC_ELT_REVERSE (cleanups, i, cleanup)
7647 cxx_eval_constant_expression (&new_ctx, cleanup, vc_discard,
7648 non_constant_p, overflow_p);
7650 /* Forget SAVE_EXPRs and TARGET_EXPRs created by this
7651 full-expression. */
7652 for (tree save_expr : save_exprs)
7653 ctx->global->remove_value (save_expr);
7655 break;
7657 case TRY_FINALLY_EXPR:
7658 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
7659 non_constant_p, overflow_p,
7660 jump_target);
7661 if (!*non_constant_p)
7662 /* Also evaluate the cleanup. */
7663 cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1), vc_discard,
7664 non_constant_p, overflow_p);
7665 break;
7667 case CLEANUP_STMT:
7668 r = cxx_eval_constant_expression (ctx, CLEANUP_BODY (t), lval,
7669 non_constant_p, overflow_p,
7670 jump_target);
7671 if (!CLEANUP_EH_ONLY (t) && !*non_constant_p)
7673 iloc_sentinel ils (loc);
7674 /* Also evaluate the cleanup. */
7675 cxx_eval_constant_expression (ctx, CLEANUP_EXPR (t), vc_discard,
7676 non_constant_p, overflow_p);
7678 break;
7680 /* These differ from cxx_eval_unary_expression in that this doesn't
7681 check for a constant operand or result; an address can be
7682 constant without its operand being, and vice versa. */
7683 case MEM_REF:
7684 case INDIRECT_REF:
7685 r = cxx_eval_indirect_ref (ctx, t, lval,
7686 non_constant_p, overflow_p);
7687 break;
7689 case ADDR_EXPR:
7691 tree oldop = TREE_OPERAND (t, 0);
7692 tree op = cxx_eval_constant_expression (ctx, oldop, vc_glvalue,
7693 non_constant_p, overflow_p);
7694 /* Don't VERIFY_CONSTANT here. */
7695 if (*non_constant_p)
7696 return t;
7697 gcc_checking_assert (TREE_CODE (op) != CONSTRUCTOR);
7698 /* This function does more aggressive folding than fold itself. */
7699 r = build_fold_addr_expr_with_type (op, TREE_TYPE (t));
7700 if (TREE_CODE (r) == ADDR_EXPR && TREE_OPERAND (r, 0) == oldop)
7702 ggc_free (r);
7703 return t;
7705 break;
7708 case REALPART_EXPR:
7709 case IMAGPART_EXPR:
7710 if (lval)
7712 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
7713 non_constant_p, overflow_p);
7714 if (r == error_mark_node)
7716 else if (r == TREE_OPERAND (t, 0) || lval == vc_discard)
7717 r = t;
7718 else
7719 r = fold_build1 (TREE_CODE (t), TREE_TYPE (t), r);
7720 break;
7722 /* FALLTHRU */
7723 case CONJ_EXPR:
7724 case FIX_TRUNC_EXPR:
7725 case FLOAT_EXPR:
7726 case NEGATE_EXPR:
7727 case ABS_EXPR:
7728 case ABSU_EXPR:
7729 case BIT_NOT_EXPR:
7730 case TRUTH_NOT_EXPR:
7731 case FIXED_CONVERT_EXPR:
7732 r = cxx_eval_unary_expression (ctx, t, lval,
7733 non_constant_p, overflow_p);
7734 break;
7736 case SIZEOF_EXPR:
7737 r = fold_sizeof_expr (t);
7738 /* In a template, fold_sizeof_expr may merely create a new SIZEOF_EXPR,
7739 which could lead to an infinite recursion. */
7740 if (TREE_CODE (r) != SIZEOF_EXPR)
7741 r = cxx_eval_constant_expression (ctx, r, lval,
7742 non_constant_p, overflow_p,
7743 jump_target);
7744 else
7746 *non_constant_p = true;
7747 gcc_assert (ctx->quiet);
7750 break;
7752 case COMPOUND_EXPR:
7754 /* check_return_expr sometimes wraps a TARGET_EXPR in a
7755 COMPOUND_EXPR; don't get confused. Also handle EMPTY_CLASS_EXPR
7756 introduced by build_call_a. */
7757 tree op0 = TREE_OPERAND (t, 0);
7758 tree op1 = TREE_OPERAND (t, 1);
7759 STRIP_NOPS (op1);
7760 if ((TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
7761 || TREE_CODE (op1) == EMPTY_CLASS_EXPR)
7762 r = cxx_eval_constant_expression (ctx, op0,
7763 lval, non_constant_p, overflow_p,
7764 jump_target);
7765 else
7767 /* Check that the LHS is constant and then discard it. */
7768 cxx_eval_constant_expression (ctx, op0, vc_discard,
7769 non_constant_p, overflow_p,
7770 jump_target);
7771 if (*non_constant_p)
7772 return t;
7773 op1 = TREE_OPERAND (t, 1);
7774 r = cxx_eval_constant_expression (ctx, op1,
7775 lval, non_constant_p, overflow_p,
7776 jump_target);
7779 break;
7781 case POINTER_PLUS_EXPR:
7782 case POINTER_DIFF_EXPR:
7783 case PLUS_EXPR:
7784 case MINUS_EXPR:
7785 case MULT_EXPR:
7786 case TRUNC_DIV_EXPR:
7787 case CEIL_DIV_EXPR:
7788 case FLOOR_DIV_EXPR:
7789 case ROUND_DIV_EXPR:
7790 case TRUNC_MOD_EXPR:
7791 case CEIL_MOD_EXPR:
7792 case ROUND_MOD_EXPR:
7793 case RDIV_EXPR:
7794 case EXACT_DIV_EXPR:
7795 case MIN_EXPR:
7796 case MAX_EXPR:
7797 case LSHIFT_EXPR:
7798 case RSHIFT_EXPR:
7799 case LROTATE_EXPR:
7800 case RROTATE_EXPR:
7801 case BIT_IOR_EXPR:
7802 case BIT_XOR_EXPR:
7803 case BIT_AND_EXPR:
7804 case TRUTH_XOR_EXPR:
7805 case LT_EXPR:
7806 case LE_EXPR:
7807 case GT_EXPR:
7808 case GE_EXPR:
7809 case EQ_EXPR:
7810 case NE_EXPR:
7811 case SPACESHIP_EXPR:
7812 case UNORDERED_EXPR:
7813 case ORDERED_EXPR:
7814 case UNLT_EXPR:
7815 case UNLE_EXPR:
7816 case UNGT_EXPR:
7817 case UNGE_EXPR:
7818 case UNEQ_EXPR:
7819 case LTGT_EXPR:
7820 case RANGE_EXPR:
7821 case COMPLEX_EXPR:
7822 r = cxx_eval_binary_expression (ctx, t, lval,
7823 non_constant_p, overflow_p);
7824 break;
7826 /* fold can introduce non-IF versions of these; still treat them as
7827 short-circuiting. */
7828 case TRUTH_AND_EXPR:
7829 case TRUTH_ANDIF_EXPR:
7830 r = cxx_eval_logical_expression (ctx, t, boolean_false_node,
7831 boolean_true_node,
7832 non_constant_p, overflow_p);
7833 break;
7835 case TRUTH_OR_EXPR:
7836 case TRUTH_ORIF_EXPR:
7837 r = cxx_eval_logical_expression (ctx, t, boolean_true_node,
7838 boolean_false_node,
7839 non_constant_p, overflow_p);
7840 break;
7842 case ARRAY_REF:
7843 r = cxx_eval_array_reference (ctx, t, lval,
7844 non_constant_p, overflow_p);
7845 break;
7847 case COMPONENT_REF:
7848 if (is_overloaded_fn (t))
7850 /* We can only get here in checking mode via
7851 build_non_dependent_expr, because any expression that
7852 calls or takes the address of the function will have
7853 pulled a FUNCTION_DECL out of the COMPONENT_REF. */
7854 gcc_checking_assert (ctx->quiet || errorcount);
7855 *non_constant_p = true;
7856 return t;
7858 r = cxx_eval_component_reference (ctx, t, lval,
7859 non_constant_p, overflow_p);
7860 break;
7862 case BIT_FIELD_REF:
7863 r = cxx_eval_bit_field_ref (ctx, t, lval,
7864 non_constant_p, overflow_p);
7865 break;
7867 case COND_EXPR:
7868 case IF_STMT:
7869 if (jump_target && *jump_target)
7871 tree orig_jump = *jump_target;
7872 tree arg = ((TREE_CODE (t) != IF_STMT || TREE_OPERAND (t, 1))
7873 ? TREE_OPERAND (t, 1) : void_node);
7874 /* When jumping to a label, the label might be either in the
7875 then or else blocks, so process then block first in skipping
7876 mode first, and if we are still in the skipping mode at its end,
7877 process the else block too. */
7878 r = cxx_eval_constant_expression (ctx, arg, lval, non_constant_p,
7879 overflow_p, jump_target);
7880 /* It's possible that we found the label in the then block. But
7881 it could have been followed by another jumping statement, e.g.
7882 say we're looking for case 1:
7883 if (cond)
7885 // skipped statements
7886 case 1:; // clears up *jump_target
7887 return 1; // and sets it to a RETURN_EXPR
7889 else { ... }
7890 in which case we need not go looking to the else block.
7891 (goto is not allowed in a constexpr function.) */
7892 if (*jump_target == orig_jump)
7894 arg = ((TREE_CODE (t) != IF_STMT || TREE_OPERAND (t, 2))
7895 ? TREE_OPERAND (t, 2) : void_node);
7896 r = cxx_eval_constant_expression (ctx, arg, lval, non_constant_p,
7897 overflow_p, jump_target);
7899 break;
7901 r = cxx_eval_conditional_expression (ctx, t, lval,
7902 non_constant_p, overflow_p,
7903 jump_target);
7904 break;
7905 case VEC_COND_EXPR:
7906 r = cxx_eval_vector_conditional_expression (ctx, t, non_constant_p,
7907 overflow_p);
7908 break;
7910 case CONSTRUCTOR:
7911 if (TREE_CONSTANT (t) && reduced_constant_expression_p (t))
7913 /* Don't re-process a constant CONSTRUCTOR. */
7914 verify_constructor_flags (t);
7915 if (TREE_CONSTANT (t))
7916 return t;
7918 r = cxx_eval_bare_aggregate (ctx, t, lval,
7919 non_constant_p, overflow_p);
7920 break;
7922 case VEC_INIT_EXPR:
7923 /* We can get this in a defaulted constructor for a class with a
7924 non-static data member of array type. Either the initializer will
7925 be NULL, meaning default-initialization, or it will be an lvalue
7926 or xvalue of the same type, meaning direct-initialization from the
7927 corresponding member. */
7928 r = cxx_eval_vec_init (ctx, t, lval,
7929 non_constant_p, overflow_p);
7930 break;
7932 case VEC_PERM_EXPR:
7933 r = cxx_eval_trinary_expression (ctx, t, lval,
7934 non_constant_p, overflow_p);
7935 break;
7937 case PAREN_EXPR:
7938 gcc_assert (!REF_PARENTHESIZED_P (t));
7939 /* A PAREN_EXPR resulting from __builtin_assoc_barrier has no effect in
7940 constant expressions since it's unaffected by -fassociative-math. */
7941 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
7942 non_constant_p, overflow_p);
7943 break;
7945 case NOP_EXPR:
7946 if (REINTERPRET_CAST_P (t))
7948 if (!ctx->quiet)
7949 error_at (loc,
7950 "%<reinterpret_cast%> is not a constant expression");
7951 *non_constant_p = true;
7952 return t;
7954 /* FALLTHROUGH. */
7955 case CONVERT_EXPR:
7956 case VIEW_CONVERT_EXPR:
7957 case UNARY_PLUS_EXPR:
7959 tree oldop = TREE_OPERAND (t, 0);
7961 tree op = cxx_eval_constant_expression (ctx, oldop,
7962 lval,
7963 non_constant_p, overflow_p);
7964 if (*non_constant_p)
7965 return t;
7966 tree type = TREE_TYPE (t);
7968 if (VOID_TYPE_P (type))
7969 return void_node;
7971 if (TREE_CODE (t) == CONVERT_EXPR
7972 && ARITHMETIC_TYPE_P (type)
7973 && INDIRECT_TYPE_P (TREE_TYPE (op))
7974 && ctx->manifestly_const_eval == mce_true)
7976 if (!ctx->quiet)
7977 error_at (loc,
7978 "conversion from pointer type %qT to arithmetic type "
7979 "%qT in a constant expression", TREE_TYPE (op), type);
7980 *non_constant_p = true;
7981 return t;
7984 /* [expr.const]: a conversion from type cv void* to a pointer-to-object
7985 type cannot be part of a core constant expression as a resolution to
7986 DR 1312. */
7987 if (TYPE_PTROB_P (type)
7988 && TYPE_PTR_P (TREE_TYPE (op))
7989 && VOID_TYPE_P (TREE_TYPE (TREE_TYPE (op)))
7990 /* Inside a call to std::construct_at,
7991 std::allocator<T>::{,de}allocate, or
7992 std::source_location::current, we permit casting from void*
7993 because that is compiler-generated code. */
7994 && !is_std_construct_at (ctx->call)
7995 && !is_std_allocator_allocate (ctx->call)
7996 && !is_std_source_location_current (ctx->call))
7998 /* Likewise, don't error when casting from void* when OP is
7999 &heap uninit and similar. */
8000 tree sop = tree_strip_nop_conversions (op);
8001 tree decl = NULL_TREE;
8002 if (TREE_CODE (sop) == ADDR_EXPR)
8003 decl = TREE_OPERAND (sop, 0);
8004 if (decl
8005 && VAR_P (decl)
8006 && DECL_ARTIFICIAL (decl)
8007 && (DECL_NAME (decl) == heap_identifier
8008 || DECL_NAME (decl) == heap_uninit_identifier
8009 || DECL_NAME (decl) == heap_vec_identifier
8010 || DECL_NAME (decl) == heap_vec_uninit_identifier))
8011 /* OK */;
8012 /* P2738 (C++26): a conversion from a prvalue P of type "pointer to
8013 cv void" to a pointer-to-object type T unless P points to an
8014 object whose type is similar to T. */
8015 else if (cxx_dialect > cxx23)
8017 r = cxx_fold_indirect_ref (ctx, loc, TREE_TYPE (type), sop);
8018 if (r)
8020 r = build1 (ADDR_EXPR, type, r);
8021 break;
8023 if (!ctx->quiet)
8025 if (TREE_CODE (sop) == ADDR_EXPR)
8027 auto_diagnostic_group d;
8028 error_at (loc, "cast from %qT is not allowed in a "
8029 "constant expression because "
8030 "pointed-to type %qT is not similar to %qT",
8031 TREE_TYPE (op), TREE_TYPE (TREE_TYPE (sop)),
8032 TREE_TYPE (type));
8033 tree obj = build_fold_indirect_ref (sop);
8034 inform (DECL_SOURCE_LOCATION (obj),
8035 "pointed-to object declared here");
8037 else
8039 gcc_assert (integer_zerop (sop));
8040 error_at (loc, "cast from %qT is not allowed in a "
8041 "constant expression because "
8042 "%qE does not point to an object",
8043 TREE_TYPE (op), oldop);
8046 *non_constant_p = true;
8047 return t;
8049 else
8051 if (!ctx->quiet)
8052 error_at (loc, "cast from %qT is not allowed in a "
8053 "constant expression before C++26",
8054 TREE_TYPE (op));
8055 *non_constant_p = true;
8056 return t;
8060 if (TREE_CODE (op) == PTRMEM_CST && !TYPE_PTRMEM_P (type))
8062 op = cplus_expand_constant (op);
8063 if (TREE_CODE (op) == PTRMEM_CST)
8065 if (!ctx->quiet)
8066 error_at (loc, "%qE is not a constant expression when the "
8067 "class %qT is still incomplete", op,
8068 PTRMEM_CST_CLASS (op));
8069 *non_constant_p = true;
8070 return t;
8074 if (TREE_CODE (op) == PTRMEM_CST && tcode == NOP_EXPR)
8076 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (op))
8077 && !can_convert_qual (type, op))
8078 op = cplus_expand_constant (op);
8079 return cp_fold_convert (type, op);
8082 if (INDIRECT_TYPE_P (type) && TREE_CODE (op) == INTEGER_CST)
8084 if (integer_zerop (op))
8086 if (TYPE_REF_P (type))
8088 if (!ctx->quiet)
8089 error_at (loc, "dereferencing a null pointer");
8090 *non_constant_p = true;
8091 return t;
8094 else
8096 /* This detects for example:
8097 reinterpret_cast<void*>(sizeof 0)
8099 if (!ctx->quiet)
8100 error_at (loc, "%<reinterpret_cast<%T>(%E)%> is not "
8101 "a constant expression",
8102 type, op);
8103 *non_constant_p = true;
8104 return t;
8108 if (INDIRECT_TYPE_P (type)
8109 && TREE_CODE (op) == NOP_EXPR
8110 && TREE_TYPE (op) == ptr_type_node
8111 && TREE_CODE (TREE_OPERAND (op, 0)) == ADDR_EXPR
8112 && VAR_P (TREE_OPERAND (TREE_OPERAND (op, 0), 0))
8113 && (DECL_NAME (TREE_OPERAND (TREE_OPERAND (op, 0),
8114 0)) == heap_uninit_identifier
8115 || DECL_NAME (TREE_OPERAND (TREE_OPERAND (op, 0),
8116 0)) == heap_vec_uninit_identifier))
8118 tree var = TREE_OPERAND (TREE_OPERAND (op, 0), 0);
8119 tree var_size = TYPE_SIZE_UNIT (TREE_TYPE (var));
8120 tree elt_type = TREE_TYPE (type);
8121 tree cookie_size = NULL_TREE;
8122 tree arg_size = NULL_TREE;
8123 if (TREE_CODE (elt_type) == RECORD_TYPE
8124 && TYPE_NAME (elt_type) == heap_identifier)
8126 tree fld1 = TYPE_FIELDS (elt_type);
8127 tree fld2 = DECL_CHAIN (fld1);
8128 elt_type = TREE_TYPE (TREE_TYPE (fld2));
8129 cookie_size = TYPE_SIZE_UNIT (TREE_TYPE (fld1));
8131 DECL_NAME (var)
8132 = (DECL_NAME (var) == heap_uninit_identifier
8133 ? heap_identifier : heap_vec_identifier);
8134 /* For zero sized elt_type, try to recover how many outer_nelts
8135 it should have. */
8136 if ((cookie_size ? tree_int_cst_equal (var_size, cookie_size)
8137 : integer_zerop (var_size))
8138 && !int_size_in_bytes (elt_type)
8139 && TREE_CODE (oldop) == CALL_EXPR
8140 && call_expr_nargs (oldop) >= 1)
8141 if (tree fun = get_function_named_in_call (oldop))
8142 if (cxx_replaceable_global_alloc_fn (fun)
8143 && IDENTIFIER_NEW_OP_P (DECL_NAME (fun)))
8144 arg_size = CALL_EXPR_ARG (oldop, 0);
8145 TREE_TYPE (var)
8146 = build_new_constexpr_heap_type (ctx, elt_type, cookie_size,
8147 var_size, arg_size,
8148 non_constant_p, overflow_p);
8149 TREE_TYPE (TREE_OPERAND (op, 0))
8150 = build_pointer_type (TREE_TYPE (var));
8153 if (op == oldop && tcode != UNARY_PLUS_EXPR)
8154 /* We didn't fold at the top so we could check for ptr-int
8155 conversion. */
8156 return fold (t);
8158 tree sop;
8160 /* Handle an array's bounds having been deduced after we built
8161 the wrapping expression. */
8162 if (same_type_ignoring_tlq_and_bounds_p (type, TREE_TYPE (op)))
8163 r = op;
8164 else if (sop = tree_strip_nop_conversions (op),
8165 sop != op && (same_type_ignoring_tlq_and_bounds_p
8166 (type, TREE_TYPE (sop))))
8167 r = sop;
8168 else if (tcode == UNARY_PLUS_EXPR)
8169 r = fold_convert (TREE_TYPE (t), op);
8170 else
8171 r = fold_build1 (tcode, type, op);
8173 /* Conversion of an out-of-range value has implementation-defined
8174 behavior; the language considers it different from arithmetic
8175 overflow, which is undefined. */
8176 if (TREE_OVERFLOW_P (r) && !TREE_OVERFLOW_P (op))
8177 TREE_OVERFLOW (r) = false;
8179 break;
8181 case EXCESS_PRECISION_EXPR:
8183 tree oldop = TREE_OPERAND (t, 0);
8185 tree op = cxx_eval_constant_expression (ctx, oldop,
8186 lval,
8187 non_constant_p, overflow_p);
8188 if (*non_constant_p)
8189 return t;
8190 r = fold_convert (TREE_TYPE (t), op);
8191 break;
8194 case EMPTY_CLASS_EXPR:
8195 /* Handle EMPTY_CLASS_EXPR produced by build_call_a by lowering
8196 it to an appropriate CONSTRUCTOR. */
8197 return build_constructor (TREE_TYPE (t), NULL);
8199 case STATEMENT_LIST:
8200 new_ctx = *ctx;
8201 new_ctx.ctor = new_ctx.object = NULL_TREE;
8202 return cxx_eval_statement_list (&new_ctx, t,
8203 non_constant_p, overflow_p, jump_target);
8205 case BIND_EXPR:
8206 r = cxx_eval_constant_expression (ctx, BIND_EXPR_BODY (t),
8207 lval,
8208 non_constant_p, overflow_p,
8209 jump_target);
8210 for (tree decl = BIND_EXPR_VARS (t); decl; decl = DECL_CHAIN (decl))
8211 ctx->global->remove_value (decl);
8212 return r;
8214 case PREINCREMENT_EXPR:
8215 case POSTINCREMENT_EXPR:
8216 case PREDECREMENT_EXPR:
8217 case POSTDECREMENT_EXPR:
8218 return cxx_eval_increment_expression (ctx, t,
8219 lval, non_constant_p, overflow_p);
8221 case LAMBDA_EXPR:
8222 case NEW_EXPR:
8223 case VEC_NEW_EXPR:
8224 case DELETE_EXPR:
8225 case VEC_DELETE_EXPR:
8226 case THROW_EXPR:
8227 case MODOP_EXPR:
8228 /* GCC internal stuff. */
8229 case VA_ARG_EXPR:
8230 case BASELINK:
8231 case OFFSET_REF:
8232 if (!ctx->quiet)
8233 error_at (loc, "expression %qE is not a constant expression", t);
8234 *non_constant_p = true;
8235 break;
8237 case OBJ_TYPE_REF:
8238 /* Virtual function lookup. We don't need to do anything fancy. */
8239 return cxx_eval_constant_expression (ctx, OBJ_TYPE_REF_EXPR (t),
8240 lval, non_constant_p, overflow_p);
8242 case PLACEHOLDER_EXPR:
8243 /* Use of the value or address of the current object. */
8244 if (tree ctor = lookup_placeholder (ctx, lval, TREE_TYPE (t)))
8246 if (TREE_CODE (ctor) == CONSTRUCTOR)
8247 return ctor;
8248 else
8249 return cxx_eval_constant_expression (ctx, ctor, lval,
8250 non_constant_p, overflow_p);
8252 /* A placeholder without a referent. We can get here when
8253 checking whether NSDMIs are noexcept, or in massage_init_elt;
8254 just say it's non-constant for now. */
8255 gcc_assert (ctx->quiet);
8256 *non_constant_p = true;
8257 break;
8259 case EXIT_EXPR:
8261 tree cond = TREE_OPERAND (t, 0);
8262 cond = cxx_eval_constant_expression (ctx, cond, vc_prvalue,
8263 non_constant_p, overflow_p);
8264 VERIFY_CONSTANT (cond);
8265 if (integer_nonzerop (cond))
8266 *jump_target = t;
8268 break;
8270 case GOTO_EXPR:
8271 if (breaks (&TREE_OPERAND (t, 0))
8272 || continues (&TREE_OPERAND (t, 0)))
8273 *jump_target = TREE_OPERAND (t, 0);
8274 else
8276 gcc_assert (cxx_dialect >= cxx23);
8277 if (!ctx->quiet)
8278 error_at (loc, "%<goto%> is not a constant expression");
8279 *non_constant_p = true;
8281 break;
8283 case LOOP_EXPR:
8284 case DO_STMT:
8285 case WHILE_STMT:
8286 case FOR_STMT:
8287 cxx_eval_loop_expr (ctx, t,
8288 non_constant_p, overflow_p, jump_target);
8289 break;
8291 case SWITCH_EXPR:
8292 case SWITCH_STMT:
8293 cxx_eval_switch_expr (ctx, t,
8294 non_constant_p, overflow_p, jump_target);
8295 break;
8297 case REQUIRES_EXPR:
8298 /* It's possible to get a requires-expression in a constant
8299 expression. For example:
8301 template<typename T> concept bool C() {
8302 return requires (T t) { t; };
8305 template<typename T> requires !C<T>() void f(T);
8307 Normalization leaves f with the associated constraint
8308 '!requires (T t) { ... }' which is not transformed into
8309 a constraint. */
8310 if (!processing_template_decl)
8311 return evaluate_requires_expr (t);
8312 else
8313 *non_constant_p = true;
8314 return t;
8316 case ANNOTATE_EXPR:
8317 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
8318 lval,
8319 non_constant_p, overflow_p,
8320 jump_target);
8321 break;
8323 case USING_STMT:
8324 r = void_node;
8325 break;
8327 case ASSERTION_STMT:
8328 case PRECONDITION_STMT:
8329 case POSTCONDITION_STMT:
8331 contract_semantic semantic = get_contract_semantic (t);
8332 if (semantic == CCS_IGNORE)
8333 break;
8335 if (!cxx_eval_assert (ctx, CONTRACT_CONDITION (t),
8336 G_("contract predicate is false in "
8337 "constant expression"),
8338 EXPR_LOCATION (t), checked_contract_p (semantic),
8339 non_constant_p, overflow_p))
8340 *non_constant_p = true;
8341 r = void_node;
8343 break;
8345 case TEMPLATE_ID_EXPR:
8347 /* We can evaluate template-id that refers to a concept only if
8348 the template arguments are non-dependent. */
8349 tree id = unpack_concept_check (t);
8350 tree tmpl = TREE_OPERAND (id, 0);
8351 if (!concept_definition_p (tmpl))
8352 internal_error ("unexpected template-id %qE", t);
8354 if (function_concept_p (tmpl))
8356 if (!ctx->quiet)
8357 error_at (cp_expr_loc_or_input_loc (t),
8358 "function concept must be called");
8359 r = error_mark_node;
8360 break;
8363 if (!value_dependent_expression_p (t)
8364 && !uid_sensitive_constexpr_evaluation_p ())
8365 r = evaluate_concept_check (t);
8366 else
8367 *non_constant_p = true;
8369 break;
8372 case ASM_EXPR:
8373 if (!ctx->quiet)
8374 inline_asm_in_constexpr_error (loc, /*constexpr_fundef_p*/false);
8375 *non_constant_p = true;
8376 return t;
8378 case BIT_CAST_EXPR:
8379 if (lval)
8381 if (!ctx->quiet)
8382 error_at (EXPR_LOCATION (t),
8383 "address of a call to %qs is not a constant expression",
8384 "__builtin_bit_cast");
8385 *non_constant_p = true;
8386 return t;
8388 r = cxx_eval_bit_cast (ctx, t, non_constant_p, overflow_p);
8389 break;
8391 case OMP_PARALLEL:
8392 case OMP_TASK:
8393 case OMP_FOR:
8394 case OMP_SIMD:
8395 case OMP_DISTRIBUTE:
8396 case OMP_TASKLOOP:
8397 case OMP_LOOP:
8398 case OMP_TEAMS:
8399 case OMP_TARGET_DATA:
8400 case OMP_TARGET:
8401 case OMP_SECTIONS:
8402 case OMP_ORDERED:
8403 case OMP_CRITICAL:
8404 case OMP_SINGLE:
8405 case OMP_SCAN:
8406 case OMP_SCOPE:
8407 case OMP_SECTION:
8408 case OMP_STRUCTURED_BLOCK:
8409 case OMP_MASTER:
8410 case OMP_MASKED:
8411 case OMP_TASKGROUP:
8412 case OMP_TARGET_UPDATE:
8413 case OMP_TARGET_ENTER_DATA:
8414 case OMP_TARGET_EXIT_DATA:
8415 case OMP_ATOMIC:
8416 case OMP_ATOMIC_READ:
8417 case OMP_ATOMIC_CAPTURE_OLD:
8418 case OMP_ATOMIC_CAPTURE_NEW:
8419 case OMP_DEPOBJ:
8420 case OACC_PARALLEL:
8421 case OACC_KERNELS:
8422 case OACC_SERIAL:
8423 case OACC_DATA:
8424 case OACC_HOST_DATA:
8425 case OACC_LOOP:
8426 case OACC_CACHE:
8427 case OACC_DECLARE:
8428 case OACC_ENTER_DATA:
8429 case OACC_EXIT_DATA:
8430 case OACC_UPDATE:
8431 if (!ctx->quiet)
8432 error_at (EXPR_LOCATION (t),
8433 "statement is not a constant expression");
8434 *non_constant_p = true;
8435 break;
8437 default:
8438 if (STATEMENT_CODE_P (TREE_CODE (t)))
8440 /* This function doesn't know how to deal with pre-genericize
8441 statements; this can only happen with statement-expressions,
8442 so for now just fail. */
8443 if (!ctx->quiet)
8444 error_at (EXPR_LOCATION (t),
8445 "statement is not a constant expression");
8447 else
8448 internal_error ("unexpected expression %qE of kind %s", t,
8449 get_tree_code_name (TREE_CODE (t)));
8450 *non_constant_p = true;
8451 break;
8454 if (r == error_mark_node)
8455 *non_constant_p = true;
8457 if (*non_constant_p)
8458 return t;
8459 else
8460 return r;
8463 /* P0859: A function is needed for constant evaluation if it is a constexpr
8464 function that is named by an expression ([basic.def.odr]) that is
8465 potentially constant evaluated.
8467 So we need to instantiate any constexpr functions mentioned by the
8468 expression even if the definition isn't needed for evaluating the
8469 expression. */
8471 static tree
8472 instantiate_cx_fn_r (tree *tp, int *walk_subtrees, void */*data*/)
8474 if (TREE_CODE (*tp) == FUNCTION_DECL
8475 && DECL_DECLARED_CONSTEXPR_P (*tp)
8476 && !DECL_INITIAL (*tp)
8477 && !trivial_fn_p (*tp)
8478 && (DECL_TEMPLOID_INSTANTIATION (*tp) || DECL_DEFAULTED_FN (*tp))
8479 && !uid_sensitive_constexpr_evaluation_p ())
8481 ++function_depth;
8482 if (DECL_TEMPLOID_INSTANTIATION (*tp))
8483 instantiate_decl (*tp, /*defer_ok*/false, /*expl_inst*/false);
8484 else
8485 synthesize_method (*tp);
8486 --function_depth;
8488 else if (TREE_CODE (*tp) == CALL_EXPR
8489 || TREE_CODE (*tp) == AGGR_INIT_EXPR)
8491 if (EXPR_HAS_LOCATION (*tp))
8492 input_location = EXPR_LOCATION (*tp);
8495 if (!EXPR_P (*tp))
8496 *walk_subtrees = 0;
8498 return NULL_TREE;
8501 static void
8502 instantiate_constexpr_fns (tree t)
8504 location_t loc = input_location;
8505 cp_walk_tree_without_duplicates (&t, instantiate_cx_fn_r, NULL);
8506 input_location = loc;
8509 /* Look for heap variables in the expression *TP. */
8511 static tree
8512 find_heap_var_refs (tree *tp, int *walk_subtrees, void */*data*/)
8514 if (VAR_P (*tp)
8515 && (DECL_NAME (*tp) == heap_uninit_identifier
8516 || DECL_NAME (*tp) == heap_identifier
8517 || DECL_NAME (*tp) == heap_vec_uninit_identifier
8518 || DECL_NAME (*tp) == heap_vec_identifier
8519 || DECL_NAME (*tp) == heap_deleted_identifier))
8520 return *tp;
8522 if (TYPE_P (*tp))
8523 *walk_subtrees = 0;
8524 return NULL_TREE;
8527 /* Find immediate function decls in *TP if any. */
8529 static tree
8530 find_immediate_fndecl (tree *tp, int */*walk_subtrees*/, void */*data*/)
8532 if (TREE_CODE (*tp) == FUNCTION_DECL && DECL_IMMEDIATE_FUNCTION_P (*tp))
8533 return *tp;
8534 if (TREE_CODE (*tp) == PTRMEM_CST
8535 && TREE_CODE (PTRMEM_CST_MEMBER (*tp)) == FUNCTION_DECL
8536 && DECL_IMMEDIATE_FUNCTION_P (PTRMEM_CST_MEMBER (*tp)))
8537 return PTRMEM_CST_MEMBER (*tp);
8538 return NULL_TREE;
8541 /* T has TREE_CONSTANT set but has been deemed not a valid C++ constant
8542 expression. Return a version of T that has TREE_CONSTANT cleared. */
8544 static tree
8545 mark_non_constant (tree t)
8547 gcc_checking_assert (TREE_CONSTANT (t));
8549 /* This isn't actually constant, so unset TREE_CONSTANT.
8550 Don't clear TREE_CONSTANT on ADDR_EXPR, as the middle-end requires
8551 it to be set if it is invariant address, even when it is not
8552 a valid C++ constant expression. Wrap it with a NOP_EXPR
8553 instead. */
8554 if (EXPR_P (t) && TREE_CODE (t) != ADDR_EXPR)
8555 t = copy_node (t);
8556 else if (TREE_CODE (t) == CONSTRUCTOR)
8557 t = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (t), t);
8558 else
8559 t = build_nop (TREE_TYPE (t), t);
8560 TREE_CONSTANT (t) = false;
8561 return t;
8564 /* ALLOW_NON_CONSTANT is false if T is required to be a constant expression.
8565 STRICT has the same sense as for constant_value_1: true if we only allow
8566 conforming C++ constant expressions, or false if we want a constant value
8567 even if it doesn't conform.
8568 MANIFESTLY_CONST_EVAL is true if T is manifestly const-evaluated as
8569 per P0595 even when ALLOW_NON_CONSTANT is true.
8570 CONSTEXPR_DTOR is true when evaluating the dtor of a constexpr variable.
8571 OBJECT must be non-NULL in that case. */
8573 static tree
8574 cxx_eval_outermost_constant_expr (tree t, bool allow_non_constant,
8575 bool strict = true,
8576 mce_value manifestly_const_eval = mce_unknown,
8577 bool constexpr_dtor = false,
8578 tree object = NULL_TREE)
8580 auto_timevar time (TV_CONSTEXPR);
8582 bool non_constant_p = false;
8583 bool overflow_p = false;
8585 if (BRACE_ENCLOSED_INITIALIZER_P (t))
8587 gcc_checking_assert (allow_non_constant);
8588 return t;
8591 constexpr_global_ctx global_ctx;
8592 constexpr_ctx ctx = { &global_ctx, NULL, NULL, NULL, NULL, NULL, NULL,
8593 allow_non_constant, strict,
8594 !allow_non_constant ? mce_true : manifestly_const_eval };
8596 /* Turn off -frounding-math for manifestly constant evaluation. */
8597 warning_sentinel rm (flag_rounding_math,
8598 ctx.manifestly_const_eval == mce_true);
8599 tree type = initialized_type (t);
8600 tree r = t;
8601 bool is_consteval = false;
8602 if (VOID_TYPE_P (type))
8604 if (constexpr_dtor)
8605 /* Used for destructors of array elements. */
8606 type = TREE_TYPE (object);
8607 else
8609 if (cxx_dialect < cxx20)
8610 return t;
8611 if (TREE_CODE (t) != CALL_EXPR && TREE_CODE (t) != AGGR_INIT_EXPR)
8612 return t;
8613 /* Calls to immediate functions returning void need to be
8614 evaluated. */
8615 tree fndecl = cp_get_callee_fndecl_nofold (t);
8616 if (fndecl == NULL_TREE || !DECL_IMMEDIATE_FUNCTION_P (fndecl))
8617 return t;
8618 else
8619 is_consteval = true;
8622 else if (cxx_dialect >= cxx20
8623 && (TREE_CODE (t) == CALL_EXPR
8624 || TREE_CODE (t) == AGGR_INIT_EXPR
8625 || TREE_CODE (t) == TARGET_EXPR))
8627 /* For non-concept checks, determine if it is consteval. */
8628 if (!concept_check_p (t))
8630 tree x = t;
8631 if (TREE_CODE (x) == TARGET_EXPR)
8632 x = TARGET_EXPR_INITIAL (x);
8633 tree fndecl = cp_get_callee_fndecl_nofold (x);
8634 if (fndecl && DECL_IMMEDIATE_FUNCTION_P (fndecl))
8635 is_consteval = true;
8638 if (AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type))
8640 /* In C++14 an NSDMI can participate in aggregate initialization,
8641 and can refer to the address of the object being initialized, so
8642 we need to pass in the relevant VAR_DECL if we want to do the
8643 evaluation in a single pass. The evaluation will dynamically
8644 update ctx.values for the VAR_DECL. We use the same strategy
8645 for C++11 constexpr constructors that refer to the object being
8646 initialized. */
8647 if (constexpr_dtor)
8649 gcc_assert (object && VAR_P (object));
8650 gcc_assert (DECL_DECLARED_CONSTEXPR_P (object));
8651 gcc_assert (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (object));
8652 if (error_operand_p (DECL_INITIAL (object)))
8653 return t;
8654 ctx.ctor = unshare_expr (DECL_INITIAL (object));
8655 TREE_READONLY (ctx.ctor) = false;
8656 /* Temporarily force decl_really_constant_value to return false
8657 for it, we want to use ctx.ctor for the current value instead. */
8658 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (object) = false;
8660 else
8662 ctx.ctor = build_constructor (type, NULL);
8663 CONSTRUCTOR_NO_CLEARING (ctx.ctor) = true;
8665 if (!object)
8667 if (TREE_CODE (t) == CALL_EXPR)
8669 /* If T is calling a constructor to initialize an object, reframe
8670 it as an AGGR_INIT_EXPR to avoid trying to modify an object
8671 from outside the constant evaluation, which will fail even if
8672 the value is actually constant (is_constant_evaluated3.C). */
8673 tree fn = cp_get_callee_fndecl_nofold (t);
8674 if (fn && DECL_CONSTRUCTOR_P (fn))
8676 object = CALL_EXPR_ARG (t, 0);
8677 object = build_fold_indirect_ref (object);
8678 r = build_aggr_init_expr (type, r);
8681 else if (TREE_CODE (t) == TARGET_EXPR)
8682 object = TARGET_EXPR_SLOT (t);
8683 else if (TREE_CODE (t) == AGGR_INIT_EXPR)
8684 object = AGGR_INIT_EXPR_SLOT (t);
8686 ctx.object = object;
8687 if (object)
8688 gcc_assert (same_type_ignoring_top_level_qualifiers_p
8689 (type, TREE_TYPE (object)));
8690 if (object && DECL_P (object))
8691 global_ctx.put_value (object, ctx.ctor);
8692 if (TREE_CODE (r) == TARGET_EXPR)
8693 /* Avoid creating another CONSTRUCTOR when we expand the
8694 TARGET_EXPR. */
8695 r = TARGET_EXPR_INITIAL (r);
8698 auto_vec<tree, 16> cleanups;
8699 global_ctx.cleanups = &cleanups;
8701 if (manifestly_const_eval == mce_true)
8702 instantiate_constexpr_fns (r);
8703 r = cxx_eval_constant_expression (&ctx, r, vc_prvalue,
8704 &non_constant_p, &overflow_p);
8706 if (!constexpr_dtor)
8707 verify_constant (r, allow_non_constant, &non_constant_p, &overflow_p);
8708 else
8709 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (object) = true;
8711 unsigned int i;
8712 tree cleanup;
8713 /* Evaluate the cleanups. */
8714 FOR_EACH_VEC_ELT_REVERSE (cleanups, i, cleanup)
8715 cxx_eval_constant_expression (&ctx, cleanup, vc_discard,
8716 &non_constant_p, &overflow_p);
8718 /* Mutable logic is a bit tricky: we want to allow initialization of
8719 constexpr variables with mutable members, but we can't copy those
8720 members to another constexpr variable. */
8721 if (TREE_CODE (r) == CONSTRUCTOR && CONSTRUCTOR_MUTABLE_POISON (r))
8723 if (!allow_non_constant)
8724 error ("%qE is not a constant expression because it refers to "
8725 "mutable subobjects of %qT", t, type);
8726 non_constant_p = true;
8729 if (TREE_CODE (r) == CONSTRUCTOR && CONSTRUCTOR_NO_CLEARING (r))
8731 if (!allow_non_constant)
8732 error ("%qE is not a constant expression because it refers to "
8733 "an incompletely initialized variable", t);
8734 TREE_CONSTANT (r) = false;
8735 non_constant_p = true;
8738 if (!non_constant_p && cxx_dialect >= cxx20
8739 && !global_ctx.heap_vars.is_empty ())
8741 tree heap_var = cp_walk_tree_without_duplicates (&r, find_heap_var_refs,
8742 NULL);
8743 unsigned int i;
8744 if (heap_var)
8746 if (!allow_non_constant && !non_constant_p)
8747 error_at (DECL_SOURCE_LOCATION (heap_var),
8748 "%qE is not a constant expression because it refers to "
8749 "a result of %<operator new%>", t);
8750 r = t;
8751 non_constant_p = true;
8753 FOR_EACH_VEC_ELT (global_ctx.heap_vars, i, heap_var)
8755 if (DECL_NAME (heap_var) != heap_deleted_identifier)
8757 if (!allow_non_constant && !non_constant_p)
8758 error_at (DECL_SOURCE_LOCATION (heap_var),
8759 "%qE is not a constant expression because allocated "
8760 "storage has not been deallocated", t);
8761 r = t;
8762 non_constant_p = true;
8764 varpool_node::get (heap_var)->remove ();
8768 /* Check that immediate invocation does not return an expression referencing
8769 any immediate function decls. */
8770 if (!non_constant_p && cxx_dialect >= cxx20)
8771 if (tree immediate_fndecl
8772 = cp_walk_tree_without_duplicates (&r, find_immediate_fndecl,
8773 NULL))
8775 if (!allow_non_constant && !non_constant_p)
8777 if (is_consteval)
8778 error_at (cp_expr_loc_or_input_loc (t),
8779 "immediate evaluation returns address of immediate "
8780 "function %qD", immediate_fndecl);
8781 else
8782 error_at (cp_expr_loc_or_input_loc (t),
8783 "constant evaluation returns address of immediate "
8784 "function %qD", immediate_fndecl);
8786 r = t;
8787 non_constant_p = true;
8790 if (non_constant_p)
8791 /* If we saw something bad, go back to our argument. The wrapping below is
8792 only for the cases of TREE_CONSTANT argument or overflow. */
8793 r = t;
8795 if (!non_constant_p && overflow_p)
8796 non_constant_p = true;
8798 /* Unshare the result. */
8799 bool should_unshare = true;
8800 if (r == t || (TREE_CODE (t) == TARGET_EXPR
8801 && TARGET_EXPR_INITIAL (t) == r))
8802 should_unshare = false;
8804 if (non_constant_p && !allow_non_constant)
8805 return error_mark_node;
8806 else if (constexpr_dtor)
8807 return r;
8808 else if (non_constant_p && TREE_CONSTANT (r))
8809 r = mark_non_constant (r);
8810 else if (non_constant_p)
8811 return t;
8813 if (should_unshare)
8814 r = unshare_expr (r);
8816 if (TREE_CODE (r) == CONSTRUCTOR && CLASS_TYPE_P (TREE_TYPE (r)))
8818 r = adjust_temp_type (type, r);
8819 if (TREE_CODE (t) == TARGET_EXPR
8820 && TARGET_EXPR_INITIAL (t) == r)
8821 return t;
8822 else if (TREE_CODE (t) == CONSTRUCTOR || TREE_CODE (t) == CALL_EXPR)
8823 /* Don't add a TARGET_EXPR if our argument didn't have one. */;
8824 else if (TREE_CODE (t) == TARGET_EXPR && TARGET_EXPR_CLEANUP (t))
8825 r = get_target_expr (r);
8826 else
8828 r = get_target_expr (r, tf_warning_or_error | tf_no_cleanup);
8829 TREE_CONSTANT (r) = true;
8833 if (TREE_CODE (t) == TARGET_EXPR
8834 && TREE_CODE (r) == TARGET_EXPR)
8836 /* Preserve this flag for potential_constant_expression, and the others
8837 for good measure. */
8838 TARGET_EXPR_ELIDING_P (r) = TARGET_EXPR_ELIDING_P (t);
8839 TARGET_EXPR_IMPLICIT_P (r) = TARGET_EXPR_IMPLICIT_P (t);
8840 TARGET_EXPR_LIST_INIT_P (r) = TARGET_EXPR_LIST_INIT_P (t);
8841 TARGET_EXPR_DIRECT_INIT_P (r) = TARGET_EXPR_DIRECT_INIT_P (t);
8844 /* Remember the original location if that wouldn't need a wrapper. */
8845 if (location_t loc = EXPR_LOCATION (t))
8846 protected_set_expr_location (r, loc);
8848 return r;
8851 /* If T represents a constant expression returns its reduced value.
8852 Otherwise return error_mark_node. */
8854 tree
8855 cxx_constant_value (tree t, tree decl /* = NULL_TREE */,
8856 tsubst_flags_t complain /* = tf_error */)
8858 bool sfinae = !(complain & tf_error);
8859 tree r = cxx_eval_outermost_constant_expr (t, sfinae, true, mce_true, false, decl);
8860 if (sfinae && !TREE_CONSTANT (r))
8861 r = error_mark_node;
8862 return r;
8865 /* Like cxx_constant_value, but used for evaluation of constexpr destructors
8866 of constexpr variables. The actual initializer of DECL is not modified. */
8868 void
8869 cxx_constant_dtor (tree t, tree decl)
8871 cxx_eval_outermost_constant_expr (t, false, true, mce_true, true, decl);
8874 /* Helper routine for fold_simple function. Either return simplified
8875 expression T, otherwise NULL_TREE.
8876 In contrast to cp_fully_fold, and to maybe_constant_value, we try to fold
8877 even if we are within template-declaration. So be careful on call, as in
8878 such case types can be undefined. */
8880 static tree
8881 fold_simple_1 (tree t)
8883 tree op1;
8884 enum tree_code code = TREE_CODE (t);
8886 switch (code)
8888 case INTEGER_CST:
8889 case REAL_CST:
8890 case VECTOR_CST:
8891 case FIXED_CST:
8892 case COMPLEX_CST:
8893 return t;
8895 case SIZEOF_EXPR:
8896 return fold_sizeof_expr (t);
8898 case ABS_EXPR:
8899 case ABSU_EXPR:
8900 case CONJ_EXPR:
8901 case REALPART_EXPR:
8902 case IMAGPART_EXPR:
8903 case NEGATE_EXPR:
8904 case BIT_NOT_EXPR:
8905 case TRUTH_NOT_EXPR:
8906 case VIEW_CONVERT_EXPR:
8907 CASE_CONVERT:
8908 case FLOAT_EXPR:
8909 case FIX_TRUNC_EXPR:
8910 case FIXED_CONVERT_EXPR:
8911 case ADDR_SPACE_CONVERT_EXPR:
8913 op1 = TREE_OPERAND (t, 0);
8915 t = const_unop (code, TREE_TYPE (t), op1);
8916 if (!t)
8917 return NULL_TREE;
8919 if (CONVERT_EXPR_CODE_P (code)
8920 && TREE_OVERFLOW_P (t) && !TREE_OVERFLOW_P (op1))
8921 TREE_OVERFLOW (t) = false;
8922 return t;
8924 default:
8925 return NULL_TREE;
8929 /* If T is a simple constant expression, returns its simplified value.
8930 Otherwise returns T. In contrast to maybe_constant_value we
8931 simplify only few operations on constant-expressions, and we don't
8932 try to simplify constexpressions. */
8934 tree
8935 fold_simple (tree t)
8937 if (processing_template_decl)
8938 return t;
8940 tree r = fold_simple_1 (t);
8941 if (r)
8942 return r;
8944 return t;
8947 /* Try folding the expression T to a simple constant.
8948 Returns that constant, otherwise returns T. */
8950 tree
8951 fold_to_constant (tree t)
8953 tree r = fold (t);
8954 if (CONSTANT_CLASS_P (r) && !TREE_OVERFLOW (r))
8955 return r;
8956 else
8957 return t;
8960 /* If T is a constant expression, returns its reduced value.
8961 Otherwise, if T does not have TREE_CONSTANT set, returns T.
8962 Otherwise, returns a version of T without TREE_CONSTANT.
8963 MANIFESTLY_CONST_EVAL is true if T is manifestly const-evaluated
8964 as per P0595. */
8966 static GTY((deletable)) hash_map<tree, tree> *cv_cache;
8968 tree
8969 maybe_constant_value (tree t, tree decl /* = NULL_TREE */,
8970 mce_value manifestly_const_eval /* = mce_unknown */)
8972 tree r;
8974 if (!is_nondependent_constant_expression (t))
8976 if (TREE_OVERFLOW_P (t)
8977 || (!processing_template_decl && TREE_CONSTANT (t)))
8978 t = mark_non_constant (t);
8979 return t;
8981 else if (CONSTANT_CLASS_P (t))
8982 /* No caching or evaluation needed. */
8983 return t;
8985 /* Don't constant evaluate an unevaluated non-manifestly-constant operand,
8986 but at least try folding it to a simple constant. */
8987 if (cp_unevaluated_operand && manifestly_const_eval != mce_true)
8988 return fold_to_constant (t);
8990 if (manifestly_const_eval != mce_unknown)
8991 return cxx_eval_outermost_constant_expr (t, true, true,
8992 manifestly_const_eval, false, decl);
8994 if (cv_cache == NULL)
8995 cv_cache = hash_map<tree, tree>::create_ggc (101);
8996 if (tree *cached = cv_cache->get (t))
8998 r = *cached;
8999 if (r != t)
9001 /* Clear processing_template_decl for sake of break_out_target_exprs;
9002 entries in the cv_cache are non-templated. */
9003 processing_template_decl_sentinel ptds;
9005 r = break_out_target_exprs (r, /*clear_loc*/true);
9006 protected_set_expr_location (r, EXPR_LOCATION (t));
9008 return r;
9011 uid_sensitive_constexpr_evaluation_checker c;
9012 r = cxx_eval_outermost_constant_expr (t, true, true,
9013 manifestly_const_eval, false, decl);
9014 gcc_checking_assert (r == t
9015 || CONVERT_EXPR_P (t)
9016 || TREE_CODE (t) == VIEW_CONVERT_EXPR
9017 || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
9018 || !cp_tree_equal (r, t));
9019 if (!c.evaluation_restricted_p ())
9020 cv_cache->put (t, r);
9021 return r;
9024 /* Dispose of the whole CV_CACHE. */
9026 static void
9027 clear_cv_cache (void)
9029 if (cv_cache != NULL)
9030 cv_cache->empty ();
9033 /* Dispose of the whole CV_CACHE and FOLD_CACHE. */
9035 void
9036 clear_cv_and_fold_caches ()
9038 clear_cv_cache ();
9039 clear_fold_cache ();
9042 /* Internal function handling expressions in templates for
9043 fold_non_dependent_expr and fold_non_dependent_init.
9045 If we're in a template, but T isn't value dependent, simplify
9046 it. We're supposed to treat:
9048 template <typename T> void f(T[1 + 1]);
9049 template <typename T> void f(T[2]);
9051 as two declarations of the same function, for example. */
9053 static tree
9054 fold_non_dependent_expr_template (tree t, tsubst_flags_t complain,
9055 bool manifestly_const_eval,
9056 tree object)
9058 gcc_assert (processing_template_decl);
9060 if (is_nondependent_constant_expression (t))
9062 processing_template_decl_sentinel s;
9063 t = instantiate_non_dependent_expr_internal (t, complain);
9065 if (type_unknown_p (t) || BRACE_ENCLOSED_INITIALIZER_P (t))
9067 if (TREE_OVERFLOW_P (t))
9069 t = build_nop (TREE_TYPE (t), t);
9070 TREE_CONSTANT (t) = false;
9072 return t;
9074 else if (CONSTANT_CLASS_P (t))
9075 /* No evaluation needed. */
9076 return t;
9078 /* Don't constant evaluate an unevaluated non-manifestly-constant operand,
9079 but at least try folding it to a simple constant. */
9080 if (cp_unevaluated_operand && !manifestly_const_eval)
9081 return fold_to_constant (t);
9083 tree r = cxx_eval_outermost_constant_expr (t, true, true,
9084 mce_value (manifestly_const_eval),
9085 false, object);
9086 /* cp_tree_equal looks through NOPs, so allow them. */
9087 gcc_checking_assert (r == t
9088 || CONVERT_EXPR_P (t)
9089 || TREE_CODE (t) == VIEW_CONVERT_EXPR
9090 || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
9091 || !cp_tree_equal (r, t));
9092 return r;
9094 else if (TREE_OVERFLOW_P (t))
9096 t = build_nop (TREE_TYPE (t), t);
9097 TREE_CONSTANT (t) = false;
9100 return t;
9103 /* Like maybe_constant_value but first fully instantiate the argument.
9105 Note: this is equivalent to instantiate_non_dependent_expr (t, complain)
9106 followed by maybe_constant_value but is more efficient,
9107 because it calls instantiation_dependent_expression_p and
9108 potential_constant_expression at most once.
9109 The manifestly_const_eval argument is passed to maybe_constant_value.
9111 Callers should generally pass their active complain, or if they are in a
9112 non-template, diagnosing context, they can use the default of
9113 tf_warning_or_error. Callers that might be within a template context, don't
9114 have a complain parameter, and aren't going to remember the result for long
9115 (e.g. null_ptr_cst_p), can pass tf_none and deal with error_mark_node
9116 appropriately. */
9118 tree
9119 fold_non_dependent_expr (tree t,
9120 tsubst_flags_t complain /* = tf_warning_or_error */,
9121 bool manifestly_const_eval /* = false */,
9122 tree object /* = NULL_TREE */)
9124 if (t == NULL_TREE)
9125 return NULL_TREE;
9127 if (processing_template_decl)
9128 return fold_non_dependent_expr_template (t, complain,
9129 manifestly_const_eval, object);
9131 return maybe_constant_value (t, object, mce_value (manifestly_const_eval));
9134 /* Like fold_non_dependent_expr, but if EXPR couldn't be folded to a constant,
9135 return the original expression. */
9137 tree
9138 maybe_fold_non_dependent_expr (tree expr,
9139 tsubst_flags_t complain/*=tf_warning_or_error*/)
9141 tree t = fold_non_dependent_expr (expr, complain);
9142 if (t && TREE_CONSTANT (t))
9143 return t;
9145 return expr;
9148 /* Like maybe_constant_init but first fully instantiate the argument. */
9150 tree
9151 fold_non_dependent_init (tree t,
9152 tsubst_flags_t complain /*=tf_warning_or_error*/,
9153 bool manifestly_const_eval /*=false*/,
9154 tree object /* = NULL_TREE */)
9156 if (t == NULL_TREE)
9157 return NULL_TREE;
9159 if (processing_template_decl)
9161 t = fold_non_dependent_expr_template (t, complain,
9162 manifestly_const_eval, object);
9163 /* maybe_constant_init does this stripping, so do it here too. */
9164 if (TREE_CODE (t) == TARGET_EXPR)
9166 tree init = TARGET_EXPR_INITIAL (t);
9167 if (TREE_CODE (init) == CONSTRUCTOR)
9168 t = init;
9170 return t;
9173 return maybe_constant_init (t, object, manifestly_const_eval);
9176 /* Like maybe_constant_value, but returns a CONSTRUCTOR directly, rather
9177 than wrapped in a TARGET_EXPR.
9178 ALLOW_NON_CONSTANT is false if T is required to be a constant expression.
9179 MANIFESTLY_CONST_EVAL is true if T is manifestly const-evaluated as
9180 per P0595 even when ALLOW_NON_CONSTANT is true. */
9182 static tree
9183 maybe_constant_init_1 (tree t, tree decl, bool allow_non_constant,
9184 bool manifestly_const_eval)
9186 if (!t)
9187 return t;
9188 if (TREE_CODE (t) == EXPR_STMT)
9189 t = TREE_OPERAND (t, 0);
9190 if (TREE_CODE (t) == CONVERT_EXPR
9191 && VOID_TYPE_P (TREE_TYPE (t)))
9192 t = TREE_OPERAND (t, 0);
9193 if (TREE_CODE (t) == INIT_EXPR)
9194 t = TREE_OPERAND (t, 1);
9195 if (TREE_CODE (t) == TARGET_EXPR)
9196 t = TARGET_EXPR_INITIAL (t);
9197 if (!is_nondependent_static_init_expression (t))
9198 /* Don't try to evaluate it. */;
9199 else if (CONSTANT_CLASS_P (t) && TREE_CODE (t) != PTRMEM_CST)
9200 /* No evaluation needed. PTRMEM_CST needs the immediate fn check. */;
9201 else
9203 /* [basic.start.static] allows constant-initialization of variables with
9204 static or thread storage duration even if it isn't required, but we
9205 shouldn't bend the rules the same way for automatic variables. */
9206 bool is_static = (decl && DECL_P (decl)
9207 && (TREE_STATIC (decl) || DECL_EXTERNAL (decl)));
9208 if (is_static)
9209 manifestly_const_eval = true;
9211 if (cp_unevaluated_operand && !manifestly_const_eval)
9212 return fold_to_constant (t);
9214 t = cxx_eval_outermost_constant_expr (t, allow_non_constant, !is_static,
9215 mce_value (manifestly_const_eval),
9216 false, decl);
9218 if (TREE_CODE (t) == TARGET_EXPR)
9220 tree init = TARGET_EXPR_INITIAL (t);
9221 if (TREE_CODE (init) == CONSTRUCTOR)
9222 t = init;
9224 return t;
9227 /* Wrapper for maybe_constant_init_1 which permits non constants. */
9229 tree
9230 maybe_constant_init (tree t, tree decl, bool manifestly_const_eval)
9232 return maybe_constant_init_1 (t, decl, true, manifestly_const_eval);
9235 /* Wrapper for maybe_constant_init_1 which does not permit non constants. */
9237 tree
9238 cxx_constant_init (tree t, tree decl)
9240 return maybe_constant_init_1 (t, decl, false, true);
9243 #if 0
9244 /* FIXME see ADDR_EXPR section in potential_constant_expression_1. */
9245 /* Return true if the object referred to by REF has automatic or thread
9246 local storage. */
9248 enum { ck_ok, ck_bad, ck_unknown };
9249 static int
9250 check_automatic_or_tls (tree ref)
9252 machine_mode mode;
9253 poly_int64 bitsize, bitpos;
9254 tree offset;
9255 int volatilep = 0, unsignedp = 0;
9256 tree decl = get_inner_reference (ref, &bitsize, &bitpos, &offset,
9257 &mode, &unsignedp, &volatilep, false);
9258 duration_kind dk;
9260 /* If there isn't a decl in the middle, we don't know the linkage here,
9261 and this isn't a constant expression anyway. */
9262 if (!DECL_P (decl))
9263 return ck_unknown;
9264 dk = decl_storage_duration (decl);
9265 return (dk == dk_auto || dk == dk_thread) ? ck_bad : ck_ok;
9267 #endif
9269 /* Data structure for passing data from potential_constant_expression_1
9270 to check_for_return_continue via cp_walk_tree. */
9271 struct check_for_return_continue_data {
9272 hash_set<tree> *pset;
9273 tree continue_stmt;
9274 tree break_stmt;
9277 /* Helper function for potential_constant_expression_1 SWITCH_STMT handling,
9278 called through cp_walk_tree. Return the first RETURN_EXPR found, or note
9279 the first CONTINUE_STMT and/or BREAK_STMT if RETURN_EXPR is not found. */
9280 static tree
9281 check_for_return_continue (tree *tp, int *walk_subtrees, void *data)
9283 tree t = *tp, s, b;
9284 check_for_return_continue_data *d = (check_for_return_continue_data *) data;
9285 switch (TREE_CODE (t))
9287 case RETURN_EXPR:
9288 return t;
9290 case CONTINUE_STMT:
9291 if (d->continue_stmt == NULL_TREE)
9292 d->continue_stmt = t;
9293 break;
9295 case BREAK_STMT:
9296 if (d->break_stmt == NULL_TREE)
9297 d->break_stmt = t;
9298 break;
9300 #define RECUR(x) \
9301 if (tree r = cp_walk_tree (&x, check_for_return_continue, data, \
9302 d->pset)) \
9303 return r
9305 /* For loops, walk subtrees manually, so that continue stmts found
9306 inside of the bodies of the loops are ignored. */
9307 case DO_STMT:
9308 *walk_subtrees = 0;
9309 RECUR (DO_COND (t));
9310 s = d->continue_stmt;
9311 b = d->break_stmt;
9312 RECUR (DO_BODY (t));
9313 d->continue_stmt = s;
9314 d->break_stmt = b;
9315 break;
9317 case WHILE_STMT:
9318 *walk_subtrees = 0;
9319 RECUR (WHILE_COND (t));
9320 s = d->continue_stmt;
9321 b = d->break_stmt;
9322 RECUR (WHILE_BODY (t));
9323 d->continue_stmt = s;
9324 d->break_stmt = b;
9325 break;
9327 case FOR_STMT:
9328 *walk_subtrees = 0;
9329 RECUR (FOR_INIT_STMT (t));
9330 RECUR (FOR_COND (t));
9331 RECUR (FOR_EXPR (t));
9332 s = d->continue_stmt;
9333 b = d->break_stmt;
9334 RECUR (FOR_BODY (t));
9335 d->continue_stmt = s;
9336 d->break_stmt = b;
9337 break;
9339 case RANGE_FOR_STMT:
9340 *walk_subtrees = 0;
9341 RECUR (RANGE_FOR_EXPR (t));
9342 s = d->continue_stmt;
9343 b = d->break_stmt;
9344 RECUR (RANGE_FOR_BODY (t));
9345 d->continue_stmt = s;
9346 d->break_stmt = b;
9347 break;
9349 case SWITCH_STMT:
9350 *walk_subtrees = 0;
9351 RECUR (SWITCH_STMT_COND (t));
9352 b = d->break_stmt;
9353 RECUR (SWITCH_STMT_BODY (t));
9354 d->break_stmt = b;
9355 break;
9356 #undef RECUR
9358 case STATEMENT_LIST:
9359 case CONSTRUCTOR:
9360 break;
9362 default:
9363 if (!EXPR_P (t))
9364 *walk_subtrees = 0;
9365 break;
9368 return NULL_TREE;
9371 /* Return true if T denotes a potentially constant expression. Issue
9372 diagnostic as appropriate under control of FLAGS. If WANT_RVAL is true,
9373 an lvalue-rvalue conversion is implied. If NOW is true, we want to
9374 consider the expression in the current context, independent of constexpr
9375 substitution. If FUNDEF_P is true, we're checking a constexpr function body
9376 and hard errors should not be reported by constexpr_error.
9378 C++0x [expr.const] used to say
9380 6 An expression is a potential constant expression if it is
9381 a constant expression where all occurrences of function
9382 parameters are replaced by arbitrary constant expressions
9383 of the appropriate type.
9385 2 A conditional expression is a constant expression unless it
9386 involves one of the following as a potentially evaluated
9387 subexpression (3.2), but subexpressions of logical AND (5.14),
9388 logical OR (5.15), and conditional (5.16) operations that are
9389 not evaluated are not considered. */
9391 static bool
9392 potential_constant_expression_1 (tree t, bool want_rval, bool strict, bool now,
9393 bool fundef_p, tsubst_flags_t flags,
9394 tree *jump_target)
9396 #define RECUR(T,RV) \
9397 potential_constant_expression_1 ((T), (RV), strict, now, fundef_p, flags, \
9398 jump_target)
9400 enum { any = false, rval = true };
9401 int i;
9402 tree tmp;
9404 if (t == error_mark_node)
9405 return false;
9406 if (t == NULL_TREE)
9407 return true;
9408 location_t loc = cp_expr_loc_or_input_loc (t);
9410 if (*jump_target)
9411 /* If we are jumping, ignore everything. This is simpler than the
9412 cxx_eval_constant_expression handling because we only need to be
9413 conservatively correct, and we don't necessarily have a constant value
9414 available, so we don't bother with switch tracking. */
9415 return true;
9417 if (TREE_THIS_VOLATILE (t) && want_rval
9418 && !FUNC_OR_METHOD_TYPE_P (TREE_TYPE (t)))
9420 if (flags & tf_error)
9421 constexpr_error (loc, fundef_p, "lvalue-to-rvalue conversion of "
9422 "a volatile lvalue %qE with type %qT", t,
9423 TREE_TYPE (t));
9424 return false;
9426 if (CONSTANT_CLASS_P (t))
9427 return true;
9428 if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_TYPED)
9429 && TREE_TYPE (t) == error_mark_node)
9430 return false;
9432 switch (TREE_CODE (t))
9434 case FUNCTION_DECL:
9435 case BASELINK:
9436 case TEMPLATE_DECL:
9437 case OVERLOAD:
9438 case TEMPLATE_ID_EXPR:
9439 case LABEL_DECL:
9440 case CASE_LABEL_EXPR:
9441 case PREDICT_EXPR:
9442 case CONST_DECL:
9443 case SIZEOF_EXPR:
9444 case ALIGNOF_EXPR:
9445 case OFFSETOF_EXPR:
9446 case NOEXCEPT_EXPR:
9447 case TEMPLATE_PARM_INDEX:
9448 case TRAIT_EXPR:
9449 case IDENTIFIER_NODE:
9450 case USERDEF_LITERAL:
9451 /* We can see a FIELD_DECL in a pointer-to-member expression. */
9452 case FIELD_DECL:
9453 case RESULT_DECL:
9454 case USING_DECL:
9455 case USING_STMT:
9456 case PLACEHOLDER_EXPR:
9457 case REQUIRES_EXPR:
9458 case STATIC_ASSERT:
9459 case DEBUG_BEGIN_STMT:
9460 return true;
9462 case RETURN_EXPR:
9463 if (!RECUR (TREE_OPERAND (t, 0), any))
9464 return false;
9465 /* FALLTHROUGH */
9467 case BREAK_STMT:
9468 case CONTINUE_STMT:
9469 *jump_target = t;
9470 return true;
9472 case PARM_DECL:
9473 if (now && want_rval)
9475 tree type = TREE_TYPE (t);
9476 if (dependent_type_p (type)
9477 || !COMPLETE_TYPE_P (processing_template_decl
9478 ? type : complete_type (type))
9479 || is_really_empty_class (type, /*ignore_vptr*/false))
9480 /* An empty class has no data to read. */
9481 return true;
9482 if (flags & tf_error)
9483 constexpr_error (input_location, fundef_p,
9484 "%qE is not a constant expression", t);
9485 return false;
9487 return true;
9489 case AGGR_INIT_EXPR:
9490 case CALL_EXPR:
9491 /* -- an invocation of a function other than a constexpr function
9492 or a constexpr constructor. */
9494 tree fun = get_function_named_in_call (t);
9495 const int nargs = call_expr_nargs (t);
9496 i = 0;
9498 if (fun == NULL_TREE)
9500 /* Reset to allow the function to continue past the end
9501 of the block below. Otherwise return early. */
9502 bool bail = true;
9504 if (TREE_CODE (t) == CALL_EXPR
9505 && CALL_EXPR_FN (t) == NULL_TREE)
9506 switch (CALL_EXPR_IFN (t))
9508 /* These should be ignored, they are optimized away from
9509 constexpr functions. */
9510 case IFN_UBSAN_NULL:
9511 case IFN_UBSAN_BOUNDS:
9512 case IFN_UBSAN_VPTR:
9513 case IFN_FALLTHROUGH:
9514 case IFN_ASSUME:
9515 return true;
9517 case IFN_ADD_OVERFLOW:
9518 case IFN_SUB_OVERFLOW:
9519 case IFN_MUL_OVERFLOW:
9520 case IFN_LAUNDER:
9521 case IFN_VEC_CONVERT:
9522 bail = false;
9523 break;
9525 default:
9526 break;
9529 if (bail)
9531 /* fold_call_expr can't do anything with IFN calls. */
9532 if (flags & tf_error)
9533 constexpr_error (loc, fundef_p,
9534 "call to internal function %qE", t);
9535 return false;
9539 if (fun && is_overloaded_fn (fun))
9541 if (!RECUR (fun, true))
9542 return false;
9543 fun = get_fns (fun);
9545 if (TREE_CODE (fun) == FUNCTION_DECL)
9547 if (builtin_valid_in_constant_expr_p (fun))
9548 return true;
9549 if (!maybe_constexpr_fn (fun)
9550 /* Allow any built-in function; if the expansion
9551 isn't constant, we'll deal with that then. */
9552 && !fndecl_built_in_p (fun)
9553 /* In C++20, replaceable global allocation functions
9554 are constant expressions. */
9555 && (!cxx_replaceable_global_alloc_fn (fun)
9556 || TREE_CODE (t) != CALL_EXPR
9557 || (!CALL_FROM_NEW_OR_DELETE_P (t)
9558 && (current_function_decl == NULL_TREE
9559 || !is_std_allocator_allocate
9560 (current_function_decl))))
9561 /* Allow placement new in std::construct_at. */
9562 && (!cxx_placement_new_fn (fun)
9563 || TREE_CODE (t) != CALL_EXPR
9564 || current_function_decl == NULL_TREE
9565 || !is_std_construct_at (current_function_decl))
9566 && !cxx_dynamic_cast_fn_p (fun))
9568 if ((flags & tf_error)
9569 && constexpr_error (loc, fundef_p,
9570 "call to non-%<constexpr%> "
9571 "function %qD", fun))
9572 explain_invalid_constexpr_fn (fun);
9573 return false;
9577 fun = OVL_FIRST (fun);
9578 /* Skip initial arguments to base constructors. */
9579 if (DECL_BASE_CONSTRUCTOR_P (fun))
9580 i = num_artificial_parms_for (fun);
9582 else if (fun)
9584 if (TREE_TYPE (fun)
9585 && FUNCTION_POINTER_TYPE_P (TREE_TYPE (fun)))
9586 want_rval = rval;
9587 else
9588 want_rval = any;
9589 if (RECUR (fun, want_rval))
9590 /* Might end up being a constant function pointer. But it
9591 could also be a function object with constexpr op(), so
9592 we pass 'any' so that the underlying VAR_DECL is deemed
9593 as potentially-constant even though it wasn't declared
9594 constexpr. */;
9595 else
9596 return false;
9598 for (; i < nargs; ++i)
9600 tree x = get_nth_callarg (t, i);
9601 /* In a template, reference arguments haven't been converted to
9602 REFERENCE_TYPE and we might not even know if the parameter
9603 is a reference, so accept lvalue constants too. */
9604 bool rv = processing_template_decl ? any : rval;
9605 /* Don't require an immediately constant value, as constexpr
9606 substitution might not use the value of the argument. */
9607 bool sub_now = false;
9608 if (!potential_constant_expression_1 (x, rv, strict,
9609 sub_now, fundef_p, flags,
9610 jump_target))
9611 return false;
9613 return true;
9616 case NON_LVALUE_EXPR:
9617 /* -- an lvalue-to-rvalue conversion (4.1) unless it is applied to
9618 -- an lvalue of integral type that refers to a non-volatile
9619 const variable or static data member initialized with
9620 constant expressions, or
9622 -- an lvalue of literal type that refers to non-volatile
9623 object defined with constexpr, or that refers to a
9624 sub-object of such an object; */
9625 return RECUR (TREE_OPERAND (t, 0), rval);
9627 case EXCESS_PRECISION_EXPR:
9628 return RECUR (TREE_OPERAND (t, 0), rval);
9630 case VAR_DECL:
9631 if (DECL_HAS_VALUE_EXPR_P (t))
9633 if (now && is_normal_capture_proxy (t))
9635 /* -- in a lambda-expression, a reference to this or to a
9636 variable with automatic storage duration defined outside that
9637 lambda-expression, where the reference would be an
9638 odr-use. */
9640 if (want_rval)
9641 /* Since we're doing an lvalue-rvalue conversion, this might
9642 not be an odr-use, so evaluate the variable directly. */
9643 return RECUR (DECL_CAPTURED_VARIABLE (t), rval);
9645 if (flags & tf_error)
9647 tree cap = DECL_CAPTURED_VARIABLE (t);
9648 auto_diagnostic_group d;
9649 if (constexpr_error (input_location, fundef_p,
9650 "lambda capture of %qE is not a "
9651 "constant expression", cap)
9652 && decl_constant_var_p (cap))
9653 inform (input_location, "because it is used as a glvalue");
9655 return false;
9657 /* Treat __PRETTY_FUNCTION__ inside a template function as
9658 potentially-constant. */
9659 else if (DECL_PRETTY_FUNCTION_P (t)
9660 && DECL_VALUE_EXPR (t) == error_mark_node)
9661 return true;
9662 return RECUR (DECL_VALUE_EXPR (t), rval);
9664 if (want_rval
9665 && (now || !var_in_maybe_constexpr_fn (t))
9666 && !type_dependent_expression_p (t)
9667 && !decl_maybe_constant_var_p (t)
9668 && (strict
9669 || !CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (t))
9670 || (DECL_INITIAL (t)
9671 && !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t)))
9672 && COMPLETE_TYPE_P (TREE_TYPE (t))
9673 && !is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
9675 if (flags & tf_error)
9676 non_const_var_error (loc, t, fundef_p);
9677 return false;
9679 return true;
9681 case NOP_EXPR:
9682 if (REINTERPRET_CAST_P (t))
9684 if (flags & tf_error)
9685 constexpr_error (loc, fundef_p, "%<reinterpret_cast%> is not a "
9686 "constant expression");
9687 return false;
9689 /* FALLTHRU */
9690 case CONVERT_EXPR:
9691 case VIEW_CONVERT_EXPR:
9692 /* -- a reinterpret_cast. FIXME not implemented, and this rule
9693 may change to something more specific to type-punning (DR 1312). */
9695 tree from = TREE_OPERAND (t, 0);
9696 if (location_wrapper_p (t))
9698 iloc_sentinel ils = loc;
9699 return (RECUR (from, want_rval));
9701 if (INDIRECT_TYPE_P (TREE_TYPE (t)))
9703 STRIP_ANY_LOCATION_WRAPPER (from);
9704 if (TREE_CODE (from) == INTEGER_CST
9705 && !integer_zerop (from))
9707 if (flags & tf_error)
9708 constexpr_error (loc, fundef_p,
9709 "%<reinterpret_cast%> from integer to "
9710 "pointer");
9711 return false;
9714 return (RECUR (from, TREE_CODE (t) != VIEW_CONVERT_EXPR));
9717 case ADDRESSOF_EXPR:
9718 /* This is like ADDR_EXPR, except it won't form pointer-to-member. */
9719 t = TREE_OPERAND (t, 0);
9720 goto handle_addr_expr;
9722 case ADDR_EXPR:
9723 /* -- a unary operator & that is applied to an lvalue that
9724 designates an object with thread or automatic storage
9725 duration; */
9726 t = TREE_OPERAND (t, 0);
9728 if (TREE_CODE (t) == OFFSET_REF && PTRMEM_OK_P (t))
9729 /* A pointer-to-member constant. */
9730 return true;
9732 handle_addr_expr:
9733 #if 0
9734 /* FIXME adjust when issue 1197 is fully resolved. For now don't do
9735 any checking here, as we might dereference the pointer later. If
9736 we remove this code, also remove check_automatic_or_tls. */
9737 i = check_automatic_or_tls (t);
9738 if (i == ck_ok)
9739 return true;
9740 if (i == ck_bad)
9742 if (flags & tf_error)
9743 error ("address-of an object %qE with thread local or "
9744 "automatic storage is not a constant expression", t);
9745 return false;
9747 #endif
9748 return RECUR (t, any);
9750 case COMPONENT_REF:
9751 case ARROW_EXPR:
9752 case OFFSET_REF:
9753 /* -- a class member access unless its postfix-expression is
9754 of literal type or of pointer to literal type. */
9755 /* This test would be redundant, as it follows from the
9756 postfix-expression being a potential constant expression. */
9757 if (type_unknown_p (t))
9758 return true;
9759 if (is_overloaded_fn (t))
9760 /* In a template, a COMPONENT_REF of a function expresses ob.fn(),
9761 which uses ob as an lvalue. */
9762 want_rval = false;
9763 gcc_fallthrough ();
9765 case REALPART_EXPR:
9766 case IMAGPART_EXPR:
9767 case BIT_FIELD_REF:
9768 return RECUR (TREE_OPERAND (t, 0), want_rval);
9770 case EXPR_PACK_EXPANSION:
9771 return RECUR (PACK_EXPANSION_PATTERN (t), want_rval);
9773 case INDIRECT_REF:
9775 tree x = TREE_OPERAND (t, 0);
9776 STRIP_NOPS (x);
9777 if (is_this_parameter (x) && !is_capture_proxy (x))
9779 if (now || !var_in_maybe_constexpr_fn (x))
9781 if (flags & tf_error)
9782 constexpr_error (loc, fundef_p, "use of %<this%> in a "
9783 "constant expression");
9784 return false;
9786 return true;
9788 return RECUR (x, rval);
9791 case STATEMENT_LIST:
9792 for (tree stmt : tsi_range (t))
9793 if (!RECUR (stmt, any))
9794 return false;
9795 return true;
9797 case MODIFY_EXPR:
9798 if (cxx_dialect < cxx14)
9799 goto fail;
9800 if (!RECUR (TREE_OPERAND (t, 0), any))
9801 return false;
9802 /* Just ignore clobbers. */
9803 if (TREE_CLOBBER_P (TREE_OPERAND (t, 1)))
9804 return true;
9805 if (!RECUR (TREE_OPERAND (t, 1), rval))
9806 return false;
9807 return true;
9809 case MODOP_EXPR:
9810 if (cxx_dialect < cxx14)
9811 goto fail;
9812 if (!RECUR (TREE_OPERAND (t, 0), rval))
9813 return false;
9814 if (!RECUR (TREE_OPERAND (t, 2), rval))
9815 return false;
9816 return true;
9818 case DO_STMT:
9819 if (!RECUR (DO_COND (t), rval))
9820 return false;
9821 if (!RECUR (DO_BODY (t), any))
9822 return false;
9823 if (breaks (jump_target) || continues (jump_target))
9824 *jump_target = NULL_TREE;
9825 return true;
9827 case FOR_STMT:
9828 if (!RECUR (FOR_INIT_STMT (t), any))
9829 return false;
9830 tmp = FOR_COND (t);
9831 if (!RECUR (tmp, rval))
9832 return false;
9833 if (tmp)
9835 if (!processing_template_decl)
9836 tmp = cxx_eval_outermost_constant_expr (tmp, true);
9837 /* If we couldn't evaluate the condition, it might not ever be
9838 true. */
9839 if (!integer_onep (tmp))
9841 /* Before returning true, check if the for body can contain
9842 a return. */
9843 hash_set<tree> pset;
9844 check_for_return_continue_data data = { &pset, NULL_TREE,
9845 NULL_TREE };
9846 if (tree ret_expr
9847 = cp_walk_tree (&FOR_BODY (t), check_for_return_continue,
9848 &data, &pset))
9849 *jump_target = ret_expr;
9850 return true;
9853 if (!RECUR (FOR_EXPR (t), any))
9854 return false;
9855 if (!RECUR (FOR_BODY (t), any))
9856 return false;
9857 if (breaks (jump_target) || continues (jump_target))
9858 *jump_target = NULL_TREE;
9859 return true;
9861 case RANGE_FOR_STMT:
9862 if (!RECUR (RANGE_FOR_INIT_STMT (t), any))
9863 return false;
9864 if (!RECUR (RANGE_FOR_EXPR (t), any))
9865 return false;
9866 if (!RECUR (RANGE_FOR_BODY (t), any))
9867 return false;
9868 if (breaks (jump_target) || continues (jump_target))
9869 *jump_target = NULL_TREE;
9870 return true;
9872 case WHILE_STMT:
9873 tmp = WHILE_COND (t);
9874 if (!RECUR (tmp, rval))
9875 return false;
9876 if (!processing_template_decl)
9877 tmp = cxx_eval_outermost_constant_expr (tmp, true);
9878 /* If we couldn't evaluate the condition, it might not ever be true. */
9879 if (!integer_onep (tmp))
9881 /* Before returning true, check if the while body can contain
9882 a return. */
9883 hash_set<tree> pset;
9884 check_for_return_continue_data data = { &pset, NULL_TREE,
9885 NULL_TREE };
9886 if (tree ret_expr
9887 = cp_walk_tree (&WHILE_BODY (t), check_for_return_continue,
9888 &data, &pset))
9889 *jump_target = ret_expr;
9890 return true;
9892 if (!RECUR (WHILE_BODY (t), any))
9893 return false;
9894 if (breaks (jump_target) || continues (jump_target))
9895 *jump_target = NULL_TREE;
9896 return true;
9898 case SWITCH_STMT:
9899 if (!RECUR (SWITCH_STMT_COND (t), rval))
9900 return false;
9901 /* FIXME we don't check SWITCH_STMT_BODY currently, because even
9902 unreachable labels would be checked and it is enough if there is
9903 a single switch cond value for which it is a valid constant
9904 expression. We need to check if there are any RETURN_EXPRs
9905 or CONTINUE_STMTs inside of the body though, as in that case
9906 we need to set *jump_target. */
9907 else
9909 hash_set<tree> pset;
9910 check_for_return_continue_data data = { &pset, NULL_TREE,
9911 NULL_TREE };
9912 if (tree ret_expr
9913 = cp_walk_tree (&SWITCH_STMT_BODY (t), check_for_return_continue,
9914 &data, &pset))
9915 /* The switch might return. */
9916 *jump_target = ret_expr;
9917 else if (data.continue_stmt)
9918 /* The switch can't return, but might continue. */
9919 *jump_target = data.continue_stmt;
9921 return true;
9923 case STMT_EXPR:
9924 return RECUR (STMT_EXPR_STMT (t), rval);
9926 case LAMBDA_EXPR:
9927 if (cxx_dialect >= cxx17)
9928 /* In C++17 lambdas can be constexpr, don't give up yet. */
9929 return true;
9930 else if (flags & tf_error)
9931 constexpr_error (loc, fundef_p, "lambda-expression is not a "
9932 "constant expression before C++17");
9933 return false;
9935 case NEW_EXPR:
9936 case VEC_NEW_EXPR:
9937 case DELETE_EXPR:
9938 case VEC_DELETE_EXPR:
9939 if (cxx_dialect >= cxx20)
9940 /* In C++20, new-expressions are potentially constant. */
9941 return true;
9942 else if (flags & tf_error)
9943 constexpr_error (loc, fundef_p, "new-expression is not a "
9944 "constant expression before C++20");
9945 return false;
9947 case DYNAMIC_CAST_EXPR:
9948 case PSEUDO_DTOR_EXPR:
9949 case THROW_EXPR:
9950 case OMP_PARALLEL:
9951 case OMP_TASK:
9952 case OMP_FOR:
9953 case OMP_SIMD:
9954 case OMP_DISTRIBUTE:
9955 case OMP_TASKLOOP:
9956 case OMP_LOOP:
9957 case OMP_TEAMS:
9958 case OMP_TARGET_DATA:
9959 case OMP_TARGET:
9960 case OMP_SECTIONS:
9961 case OMP_ORDERED:
9962 case OMP_CRITICAL:
9963 case OMP_SINGLE:
9964 case OMP_SCAN:
9965 case OMP_SCOPE:
9966 case OMP_SECTION:
9967 case OMP_MASTER:
9968 case OMP_MASKED:
9969 case OMP_TASKGROUP:
9970 case OMP_TARGET_UPDATE:
9971 case OMP_TARGET_ENTER_DATA:
9972 case OMP_TARGET_EXIT_DATA:
9973 case OMP_ATOMIC:
9974 case OMP_ATOMIC_READ:
9975 case OMP_ATOMIC_CAPTURE_OLD:
9976 case OMP_ATOMIC_CAPTURE_NEW:
9977 case OMP_DEPOBJ:
9978 case OACC_PARALLEL:
9979 case OACC_KERNELS:
9980 case OACC_SERIAL:
9981 case OACC_DATA:
9982 case OACC_HOST_DATA:
9983 case OACC_LOOP:
9984 case OACC_CACHE:
9985 case OACC_DECLARE:
9986 case OACC_ENTER_DATA:
9987 case OACC_EXIT_DATA:
9988 case OACC_UPDATE:
9989 /* GCC internal stuff. */
9990 case VA_ARG_EXPR:
9991 case TRANSACTION_EXPR:
9992 case AT_ENCODE_EXPR:
9993 fail:
9994 if (flags & tf_error)
9995 constexpr_error (loc, fundef_p, "expression %qE is not a constant "
9996 "expression", t);
9997 return false;
9999 case ASM_EXPR:
10000 if (flags & tf_error)
10001 inline_asm_in_constexpr_error (loc, fundef_p);
10002 return false;
10004 case OBJ_TYPE_REF:
10005 if (cxx_dialect >= cxx20)
10006 /* In C++20 virtual calls can be constexpr, don't give up yet. */
10007 return true;
10008 else if (flags & tf_error)
10009 constexpr_error (loc, fundef_p, "virtual functions cannot be "
10010 "%<constexpr%> before C++20");
10011 return false;
10013 case TYPEID_EXPR:
10014 /* In C++20, a typeid expression whose operand is of polymorphic
10015 class type can be constexpr. */
10017 tree e = TREE_OPERAND (t, 0);
10018 if (cxx_dialect < cxx20
10019 && strict
10020 && !TYPE_P (e)
10021 && !type_dependent_expression_p (e)
10022 && TYPE_POLYMORPHIC_P (TREE_TYPE (e)))
10024 if (flags & tf_error)
10025 constexpr_error (loc, fundef_p, "%<typeid%> is not a "
10026 "constant expression because %qE is "
10027 "of polymorphic type", e);
10028 return false;
10030 return true;
10033 case POINTER_DIFF_EXPR:
10034 case MINUS_EXPR:
10035 want_rval = true;
10036 goto binary;
10038 case LT_EXPR:
10039 case LE_EXPR:
10040 case GT_EXPR:
10041 case GE_EXPR:
10042 case EQ_EXPR:
10043 case NE_EXPR:
10044 case SPACESHIP_EXPR:
10045 want_rval = true;
10046 goto binary;
10048 case PREINCREMENT_EXPR:
10049 case POSTINCREMENT_EXPR:
10050 case PREDECREMENT_EXPR:
10051 case POSTDECREMENT_EXPR:
10052 if (cxx_dialect < cxx14)
10053 goto fail;
10054 goto unary;
10056 case BIT_NOT_EXPR:
10057 /* A destructor. */
10058 if (TYPE_P (TREE_OPERAND (t, 0)))
10059 return true;
10060 /* fall through. */
10062 case CONJ_EXPR:
10063 case SAVE_EXPR:
10064 case FIX_TRUNC_EXPR:
10065 case FLOAT_EXPR:
10066 case NEGATE_EXPR:
10067 case ABS_EXPR:
10068 case ABSU_EXPR:
10069 case TRUTH_NOT_EXPR:
10070 case FIXED_CONVERT_EXPR:
10071 case UNARY_PLUS_EXPR:
10072 case UNARY_LEFT_FOLD_EXPR:
10073 case UNARY_RIGHT_FOLD_EXPR:
10074 unary:
10075 return RECUR (TREE_OPERAND (t, 0), rval);
10077 case CAST_EXPR:
10078 case CONST_CAST_EXPR:
10079 case STATIC_CAST_EXPR:
10080 case REINTERPRET_CAST_EXPR:
10081 case IMPLICIT_CONV_EXPR:
10082 if (!cast_valid_in_integral_constant_expression_p (TREE_TYPE (t)))
10083 /* In C++98, a conversion to non-integral type can't be part of a
10084 constant expression. */
10086 if (flags & tf_error)
10087 constexpr_error (loc, fundef_p,
10088 "cast to non-integral type %qT in a constant "
10089 "expression", TREE_TYPE (t));
10090 return false;
10092 /* This might be a conversion from a class to a (potentially) literal
10093 type. Let's consider it potentially constant since the conversion
10094 might be a constexpr user-defined conversion. */
10095 else if (cxx_dialect >= cxx11
10096 && (dependent_type_p (TREE_TYPE (t))
10097 || !COMPLETE_TYPE_P (TREE_TYPE (t))
10098 || literal_type_p (TREE_TYPE (t)))
10099 && TREE_OPERAND (t, 0))
10101 tree type = TREE_TYPE (TREE_OPERAND (t, 0));
10102 /* If this is a dependent type, it could end up being a class
10103 with conversions. */
10104 if (type == NULL_TREE || WILDCARD_TYPE_P (type))
10105 return true;
10106 /* Or a non-dependent class which has conversions. */
10107 else if (CLASS_TYPE_P (type)
10108 && (TYPE_HAS_CONVERSION (type) || dependent_scope_p (type)))
10109 return true;
10112 return (RECUR (TREE_OPERAND (t, 0),
10113 !TYPE_REF_P (TREE_TYPE (t))));
10115 case BIND_EXPR:
10116 return RECUR (BIND_EXPR_BODY (t), want_rval);
10118 case CLEANUP_POINT_EXPR:
10119 case MUST_NOT_THROW_EXPR:
10120 case TRY_CATCH_EXPR:
10121 case TRY_BLOCK:
10122 case EH_SPEC_BLOCK:
10123 case EXPR_STMT:
10124 case PAREN_EXPR:
10125 /* For convenience. */
10126 case LOOP_EXPR:
10127 case EXIT_EXPR:
10128 return RECUR (TREE_OPERAND (t, 0), want_rval);
10130 case DECL_EXPR:
10131 tmp = DECL_EXPR_DECL (t);
10132 if (VAR_P (tmp) && !DECL_ARTIFICIAL (tmp)
10133 && (processing_template_decl
10134 ? !decl_maybe_constant_var_p (tmp)
10135 : !decl_constant_var_p (tmp)))
10137 if (CP_DECL_THREAD_LOCAL_P (tmp) && !DECL_REALLY_EXTERN (tmp))
10139 if (flags & tf_error)
10140 constexpr_error (DECL_SOURCE_LOCATION (tmp), fundef_p,
10141 "%qD defined %<thread_local%> in "
10142 "%<constexpr%> context", tmp);
10143 return false;
10145 else if (TREE_STATIC (tmp))
10147 if (flags & tf_error)
10148 constexpr_error (DECL_SOURCE_LOCATION (tmp), fundef_p,
10149 "%qD defined %<static%> in %<constexpr%> "
10150 "context", tmp);
10151 return false;
10153 else if (!check_for_uninitialized_const_var
10154 (tmp, /*constexpr_context_p=*/true, flags))
10155 return false;
10157 if (VAR_P (tmp))
10158 return RECUR (DECL_INITIAL (tmp), want_rval);
10159 return true;
10161 case TRY_FINALLY_EXPR:
10162 return (RECUR (TREE_OPERAND (t, 0), want_rval)
10163 && RECUR (TREE_OPERAND (t, 1), any));
10165 case SCOPE_REF:
10166 return RECUR (TREE_OPERAND (t, 1), want_rval);
10168 case TARGET_EXPR:
10169 if (!TARGET_EXPR_DIRECT_INIT_P (t)
10170 && !TARGET_EXPR_ELIDING_P (t)
10171 && !literal_type_p (TREE_TYPE (t)))
10173 if (flags & tf_error)
10175 auto_diagnostic_group d;
10176 if (constexpr_error (loc, fundef_p,
10177 "temporary of non-literal type %qT in a "
10178 "constant expression", TREE_TYPE (t)))
10179 explain_non_literal_class (TREE_TYPE (t));
10181 return false;
10183 /* FALLTHRU */
10184 case INIT_EXPR:
10185 return RECUR (TREE_OPERAND (t, 1), rval);
10187 case CONSTRUCTOR:
10189 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
10190 constructor_elt *ce;
10191 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
10192 if (!RECUR (ce->value, want_rval))
10193 return false;
10194 return true;
10197 case TREE_LIST:
10199 gcc_assert (TREE_PURPOSE (t) == NULL_TREE
10200 || DECL_P (TREE_PURPOSE (t)));
10201 if (!RECUR (TREE_VALUE (t), want_rval))
10202 return false;
10203 if (TREE_CHAIN (t) == NULL_TREE)
10204 return true;
10205 return RECUR (TREE_CHAIN (t), want_rval);
10208 case TRUNC_DIV_EXPR:
10209 case CEIL_DIV_EXPR:
10210 case FLOOR_DIV_EXPR:
10211 case ROUND_DIV_EXPR:
10212 case TRUNC_MOD_EXPR:
10213 case CEIL_MOD_EXPR:
10214 case ROUND_MOD_EXPR:
10216 tree denom = TREE_OPERAND (t, 1);
10217 if (!RECUR (denom, rval))
10218 return false;
10219 /* We can't call cxx_eval_outermost_constant_expr on an expression
10220 that hasn't been through instantiate_non_dependent_expr yet. */
10221 if (!processing_template_decl)
10222 denom = cxx_eval_outermost_constant_expr (denom, true);
10223 if (integer_zerop (denom))
10225 if (flags & tf_error)
10226 constexpr_error (input_location, fundef_p,
10227 "division by zero is not a constant expression");
10228 return false;
10230 else
10232 want_rval = true;
10233 return RECUR (TREE_OPERAND (t, 0), want_rval);
10237 case COMPOUND_EXPR:
10239 /* check_return_expr sometimes wraps a TARGET_EXPR in a
10240 COMPOUND_EXPR; don't get confused. */
10241 tree op0 = TREE_OPERAND (t, 0);
10242 tree op1 = TREE_OPERAND (t, 1);
10243 STRIP_NOPS (op1);
10244 if (TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
10245 return RECUR (op0, want_rval);
10246 else
10247 goto binary;
10250 /* If the first operand is the non-short-circuit constant, look at
10251 the second operand; otherwise we only care about the first one for
10252 potentiality. */
10253 case TRUTH_AND_EXPR:
10254 case TRUTH_ANDIF_EXPR:
10255 tmp = boolean_true_node;
10256 goto truth;
10257 case TRUTH_OR_EXPR:
10258 case TRUTH_ORIF_EXPR:
10259 tmp = boolean_false_node;
10260 truth:
10262 tree op0 = TREE_OPERAND (t, 0);
10263 tree op1 = TREE_OPERAND (t, 1);
10264 if (!RECUR (op0, rval))
10265 return false;
10266 if (!(flags & tf_error) && RECUR (op1, rval))
10267 /* When quiet, try to avoid expensive trial evaluation by first
10268 checking potentiality of the second operand. */
10269 return true;
10270 if (!processing_template_decl)
10271 op0 = cxx_eval_outermost_constant_expr (op0, true);
10272 if (tree_int_cst_equal (op0, tmp))
10273 return (flags & tf_error) ? RECUR (op1, rval) : false;
10274 else
10275 return true;
10278 case PLUS_EXPR:
10279 case MULT_EXPR:
10280 case POINTER_PLUS_EXPR:
10281 case RDIV_EXPR:
10282 case EXACT_DIV_EXPR:
10283 case MIN_EXPR:
10284 case MAX_EXPR:
10285 case LSHIFT_EXPR:
10286 case RSHIFT_EXPR:
10287 case LROTATE_EXPR:
10288 case RROTATE_EXPR:
10289 case BIT_IOR_EXPR:
10290 case BIT_XOR_EXPR:
10291 case BIT_AND_EXPR:
10292 case TRUTH_XOR_EXPR:
10293 case UNORDERED_EXPR:
10294 case ORDERED_EXPR:
10295 case UNLT_EXPR:
10296 case UNLE_EXPR:
10297 case UNGT_EXPR:
10298 case UNGE_EXPR:
10299 case UNEQ_EXPR:
10300 case LTGT_EXPR:
10301 case RANGE_EXPR:
10302 case COMPLEX_EXPR:
10303 want_rval = true;
10304 /* Fall through. */
10305 case ARRAY_REF:
10306 case ARRAY_RANGE_REF:
10307 case MEMBER_REF:
10308 case DOTSTAR_EXPR:
10309 case MEM_REF:
10310 case BINARY_LEFT_FOLD_EXPR:
10311 case BINARY_RIGHT_FOLD_EXPR:
10312 binary:
10313 for (i = 0; i < 2; ++i)
10314 if (!RECUR (TREE_OPERAND (t, i), want_rval))
10315 return false;
10316 return true;
10318 case VEC_PERM_EXPR:
10319 for (i = 0; i < 3; ++i)
10320 if (!RECUR (TREE_OPERAND (t, i), true))
10321 return false;
10322 return true;
10324 case COND_EXPR:
10325 if (COND_EXPR_IS_VEC_DELETE (t) && cxx_dialect < cxx20)
10327 if (flags & tf_error)
10328 constexpr_error (loc, fundef_p, "%<delete[]%> is not a "
10329 "constant expression");
10330 return false;
10332 /* Fall through. */
10333 case IF_STMT:
10334 case VEC_COND_EXPR:
10335 /* If the condition is a known constant, we know which of the legs we
10336 care about; otherwise we only require that the condition and
10337 either of the legs be potentially constant. */
10338 tmp = TREE_OPERAND (t, 0);
10339 if (!RECUR (tmp, rval))
10340 return false;
10341 if (!processing_template_decl)
10342 tmp = cxx_eval_outermost_constant_expr (tmp, true);
10343 /* potential_constant_expression* isn't told if it is called for
10344 manifestly_const_eval or not, so for consteval if always
10345 process both branches as if the condition is not a known
10346 constant. */
10347 if (TREE_CODE (t) != IF_STMT || !IF_STMT_CONSTEVAL_P (t))
10349 if (integer_zerop (tmp))
10350 return RECUR (TREE_OPERAND (t, 2), want_rval);
10351 else if (TREE_CODE (tmp) == INTEGER_CST)
10352 return RECUR (TREE_OPERAND (t, 1), want_rval);
10354 tmp = *jump_target;
10355 for (i = 1; i < 3; ++i)
10357 tree this_jump_target = tmp;
10358 if (potential_constant_expression_1 (TREE_OPERAND (t, i),
10359 want_rval, strict, now, fundef_p,
10360 tf_none, &this_jump_target))
10362 if (returns (&this_jump_target))
10363 *jump_target = this_jump_target;
10364 else if (!returns (jump_target))
10366 if (breaks (&this_jump_target)
10367 || continues (&this_jump_target))
10368 *jump_target = this_jump_target;
10369 if (i == 1)
10371 /* If the then branch is potentially constant, but
10372 does not return, check if the else branch
10373 couldn't return, break or continue. */
10374 hash_set<tree> pset;
10375 check_for_return_continue_data data = { &pset, NULL_TREE,
10376 NULL_TREE };
10377 if (tree ret_expr
10378 = cp_walk_tree (&TREE_OPERAND (t, 2),
10379 check_for_return_continue, &data,
10380 &pset))
10381 *jump_target = ret_expr;
10382 else if (*jump_target == NULL_TREE)
10384 if (data.continue_stmt)
10385 *jump_target = data.continue_stmt;
10386 else if (data.break_stmt)
10387 *jump_target = data.break_stmt;
10391 return true;
10394 if (flags & tf_error)
10396 if (TREE_CODE (t) == IF_STMT)
10397 constexpr_error (loc, fundef_p, "neither branch of %<if%> is a "
10398 "constant expression");
10399 else
10400 constexpr_error (loc, fundef_p, "expression %qE is not a "
10401 "constant expression", t);
10403 return false;
10405 case VEC_INIT_EXPR:
10406 if (VEC_INIT_EXPR_IS_CONSTEXPR (t))
10407 return true;
10408 if (flags & tf_error)
10410 if (constexpr_error (loc, fundef_p, "non-constant array "
10411 "initialization"))
10412 diagnose_non_constexpr_vec_init (t);
10414 return false;
10416 case TYPE_DECL:
10417 case TAG_DEFN:
10418 /* We can see these in statement-expressions. */
10419 return true;
10421 case CLEANUP_STMT:
10422 if (!RECUR (CLEANUP_BODY (t), any))
10423 return false;
10424 if (!CLEANUP_EH_ONLY (t) && !RECUR (CLEANUP_EXPR (t), any))
10425 return false;
10426 return true;
10428 case EMPTY_CLASS_EXPR:
10429 return true;
10431 case GOTO_EXPR:
10433 tree *target = &TREE_OPERAND (t, 0);
10434 /* Gotos representing break, continue and cdtor return are OK. */
10435 if (breaks (target) || continues (target) || returns (target))
10437 *jump_target = *target;
10438 return true;
10440 if (flags & tf_error)
10441 constexpr_error (loc, fundef_p, "%<goto%> is not a constant "
10442 "expression");
10443 return false;
10446 case ASSERTION_STMT:
10447 case PRECONDITION_STMT:
10448 case POSTCONDITION_STMT:
10449 if (!checked_contract_p (get_contract_semantic (t)))
10450 return true;
10451 return RECUR (CONTRACT_CONDITION (t), rval);
10453 case LABEL_EXPR:
10454 t = LABEL_EXPR_LABEL (t);
10455 if (DECL_ARTIFICIAL (t) || cxx_dialect >= cxx23)
10456 return true;
10457 else if (flags & tf_error)
10458 constexpr_error (loc, fundef_p, "label definition in %<constexpr%> "
10459 "function only available with %<-std=c++2b%> or "
10460 "%<-std=gnu++2b%>");
10461 return false;
10463 case ANNOTATE_EXPR:
10464 return RECUR (TREE_OPERAND (t, 0), rval);
10466 case BIT_CAST_EXPR:
10467 return RECUR (TREE_OPERAND (t, 0), rval);
10469 /* Coroutine await, yield and return expressions are not. */
10470 case CO_AWAIT_EXPR:
10471 case CO_YIELD_EXPR:
10472 case CO_RETURN_EXPR:
10473 return false;
10475 case NONTYPE_ARGUMENT_PACK:
10477 tree args = ARGUMENT_PACK_ARGS (t);
10478 int len = TREE_VEC_LENGTH (args);
10479 for (int i = 0; i < len; ++i)
10480 if (!RECUR (TREE_VEC_ELT (args, i), any))
10481 return false;
10482 return true;
10485 default:
10486 if (objc_non_constant_expr_p (t))
10487 return false;
10489 sorry ("unexpected AST of kind %s", get_tree_code_name (TREE_CODE (t)));
10490 gcc_unreachable ();
10491 return false;
10493 #undef RECUR
10496 bool
10497 potential_constant_expression_1 (tree t, bool want_rval, bool strict, bool now,
10498 bool fundef_p, tsubst_flags_t flags)
10500 if (flags & tf_error)
10502 /* Check potentiality quietly first, as that could be performed more
10503 efficiently in some cases (currently only for TRUTH_*_EXPR). If
10504 that fails, replay the check noisily to give errors. */
10505 flags &= ~tf_error;
10506 if (potential_constant_expression_1 (t, want_rval, strict, now, fundef_p,
10507 flags))
10508 return true;
10509 flags |= tf_error;
10512 tree target = NULL_TREE;
10513 return potential_constant_expression_1 (t, want_rval, strict, now, fundef_p,
10514 flags, &target);
10517 /* The main entry point to the above. */
10519 bool
10520 potential_constant_expression (tree t)
10522 return potential_constant_expression_1 (t, /*want_rval*/false, /*strict*/true,
10523 /*now*/false, /*fundef_p*/false,
10524 tf_none);
10527 /* As above, but require a constant rvalue. */
10529 bool
10530 potential_rvalue_constant_expression (tree t)
10532 return potential_constant_expression_1 (t, /*want_rval*/true, /*strict*/true,
10533 /*now*/false, /*fundef_p*/false,
10534 tf_none);
10537 /* Like above, but complain about non-constant expressions. */
10539 bool
10540 require_potential_constant_expression (tree t)
10542 return potential_constant_expression_1 (t, /*want_rval*/false, /*strict*/true,
10543 /*now*/false, /*fundef_p*/false,
10544 tf_warning_or_error);
10547 /* Cross product of the above. */
10549 bool
10550 require_potential_rvalue_constant_expression (tree t)
10552 return potential_constant_expression_1 (t, /*want_rval*/true, /*strict*/true,
10553 /*now*/false, /*fundef_p*/false,
10554 tf_warning_or_error);
10557 /* Like require_potential_rvalue_constant_expression, but fundef_p is true. */
10559 bool
10560 require_potential_rvalue_constant_expression_fncheck (tree t)
10562 return potential_constant_expression_1 (t, /*want_rval*/true, /*strict*/true,
10563 /*now*/false, /*fundef_p*/true,
10564 tf_warning_or_error);
10567 /* Like above, but don't consider PARM_DECL a potential_constant_expression. */
10569 bool
10570 require_rvalue_constant_expression (tree t)
10572 return potential_constant_expression_1 (t, /*want_rval*/true, /*strict*/true,
10573 /*now*/true, /*fundef_p*/false,
10574 tf_warning_or_error);
10577 /* Like potential_constant_expression, but don't consider possible constexpr
10578 substitution of the current function. That is, PARM_DECL qualifies under
10579 potential_constant_expression, but not here.
10581 This is basically what you can check when any actual constant values might
10582 be value-dependent. */
10584 bool
10585 is_constant_expression (tree t)
10587 return potential_constant_expression_1 (t, /*want_rval*/false, /*strict*/true,
10588 /*now*/true, /*fundef_p*/false,
10589 tf_none);
10592 /* As above, but expect an rvalue. */
10594 bool
10595 is_rvalue_constant_expression (tree t)
10597 return potential_constant_expression_1 (t, /*want_rval*/true, /*strict*/true,
10598 /*now*/true, /*fundef_p*/false,
10599 tf_none);
10602 /* Like above, but complain about non-constant expressions. */
10604 bool
10605 require_constant_expression (tree t)
10607 return potential_constant_expression_1 (t, /*want_rval*/false, /*strict*/true,
10608 /*now*/true, /*fundef_p*/false,
10609 tf_warning_or_error);
10612 /* Like is_constant_expression, but allow const variables that are not allowed
10613 under constexpr rules. */
10615 bool
10616 is_static_init_expression (tree t)
10618 return potential_constant_expression_1 (t, /*want_rval*/false,
10619 /*strict*/false, /*now*/true,
10620 /*fundef_p*/false, tf_none);
10623 /* Returns true if T is a potential constant expression that is not
10624 instantiation-dependent, and therefore a candidate for constant folding even
10625 in a template. */
10627 bool
10628 is_nondependent_constant_expression (tree t)
10630 return (!type_unknown_p (t)
10631 && is_constant_expression (t)
10632 && !instantiation_dependent_expression_p (t));
10635 /* Returns true if T is a potential static initializer expression that is not
10636 instantiation-dependent. */
10638 bool
10639 is_nondependent_static_init_expression (tree t)
10641 return (!type_unknown_p (t)
10642 && is_static_init_expression (t)
10643 && !instantiation_dependent_expression_p (t));
10646 /* True iff FN is an implicitly constexpr function. */
10648 bool
10649 decl_implicit_constexpr_p (tree fn)
10651 if (!(flag_implicit_constexpr
10652 && TREE_CODE (fn) == FUNCTION_DECL
10653 && DECL_DECLARED_CONSTEXPR_P (fn)))
10654 return false;
10656 if (DECL_CLONED_FUNCTION_P (fn))
10657 fn = DECL_CLONED_FUNCTION (fn);
10659 return (DECL_LANG_SPECIFIC (fn)
10660 && DECL_LANG_SPECIFIC (fn)->u.fn.implicit_constexpr);
10663 /* Finalize constexpr processing after parsing. */
10665 void
10666 fini_constexpr (void)
10668 /* The contexpr call and fundef copies tables are no longer needed. */
10669 constexpr_call_table = NULL;
10670 fundef_copies_table = NULL;
10673 #include "gt-cp-constexpr.h"