Daily bump.
[official-gcc.git] / gcc / cp / constexpr.cc
blob6350fe1540856ade686cec72bfa7cf1a61165d08
1 /* Perform -*- C++ -*- constant expression evaluation, including calls to
2 constexpr functions. These routines are used both during actual parsing
3 and during the instantiation of template functions.
5 Copyright (C) 1998-2024 Free Software Foundation, Inc.
7 This file is part of GCC.
9 GCC is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3, or (at your option)
12 any later version.
14 GCC is distributed in the hope that it will be useful, but
15 WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3. If not see
21 <http://www.gnu.org/licenses/>. */
23 #include "config.h"
24 #include "system.h"
25 #include "coretypes.h"
26 #include "cp-tree.h"
27 #include "varasm.h"
28 #include "c-family/c-objc.h"
29 #include "tree-iterator.h"
30 #include "gimplify.h"
31 #include "builtins.h"
32 #include "tree-inline.h"
33 #include "ubsan.h"
34 #include "timevar.h"
35 #include "fold-const-call.h"
36 #include "stor-layout.h"
37 #include "cgraph.h"
38 #include "opts.h"
39 #include "stringpool.h"
40 #include "attribs.h"
41 #include "fold-const.h"
42 #include "intl.h"
43 #include "toplev.h"
45 static bool verify_constant (tree, bool, bool *, bool *);
46 #define VERIFY_CONSTANT(X) \
47 do { \
48 if (verify_constant ((X), ctx->quiet, non_constant_p, overflow_p)) \
49 return t; \
50 } while (0)
52 static HOST_WIDE_INT find_array_ctor_elt (tree ary, tree dindex,
53 bool insert = false);
54 static int array_index_cmp (tree key, tree index);
56 /* Returns true iff FUN is an instantiation of a constexpr function
57 template or a defaulted constexpr function. */
59 bool
60 is_instantiation_of_constexpr (tree fun)
62 return ((DECL_TEMPLOID_INSTANTIATION (fun)
63 && DECL_DECLARED_CONSTEXPR_P (DECL_TI_TEMPLATE (fun)))
64 || (DECL_DEFAULTED_FN (fun)
65 && DECL_DECLARED_CONSTEXPR_P (fun)));
68 /* Return true if T is a literal type. */
70 bool
71 literal_type_p (tree t)
73 if (SCALAR_TYPE_P (t)
74 || VECTOR_TYPE_P (t)
75 || TYPE_REF_P (t)
76 || (VOID_TYPE_P (t) && cxx_dialect >= cxx14))
77 return true;
78 if (CLASS_TYPE_P (t))
80 t = complete_type (t);
81 gcc_assert (COMPLETE_TYPE_P (t) || errorcount);
82 return CLASSTYPE_LITERAL_P (t);
84 if (TREE_CODE (t) == ARRAY_TYPE)
85 return literal_type_p (strip_array_types (t));
86 return false;
89 /* If DECL is a variable declared `constexpr', require its type
90 be literal. Return error_mark_node if we give an error, the
91 DECL otherwise. */
93 tree
94 ensure_literal_type_for_constexpr_object (tree decl)
96 tree type = TREE_TYPE (decl);
97 if (VAR_P (decl)
98 && (DECL_DECLARED_CONSTEXPR_P (decl)
99 || var_in_constexpr_fn (decl))
100 && !processing_template_decl)
102 tree stype = strip_array_types (type);
103 if (CLASS_TYPE_P (stype) && !COMPLETE_TYPE_P (complete_type (stype)))
104 /* Don't complain here, we'll complain about incompleteness
105 when we try to initialize the variable. */;
106 else if (!literal_type_p (type))
108 if (DECL_DECLARED_CONSTEXPR_P (decl))
110 auto_diagnostic_group d;
111 error_at (DECL_SOURCE_LOCATION (decl),
112 "the type %qT of %<constexpr%> variable %qD "
113 "is not literal", type, decl);
114 explain_non_literal_class (type);
115 decl = error_mark_node;
117 else if (cxx_dialect < cxx23)
119 if (!is_instantiation_of_constexpr (current_function_decl))
121 auto_diagnostic_group d;
122 error_at (DECL_SOURCE_LOCATION (decl),
123 "variable %qD of non-literal type %qT in "
124 "%<constexpr%> function only available with "
125 "%<-std=c++2b%> or %<-std=gnu++2b%>", decl, type);
126 explain_non_literal_class (type);
127 decl = error_mark_node;
129 cp_function_chain->invalid_constexpr = true;
132 else if (DECL_DECLARED_CONSTEXPR_P (decl)
133 && variably_modified_type_p (type, NULL_TREE))
135 error_at (DECL_SOURCE_LOCATION (decl),
136 "%<constexpr%> variable %qD has variably-modified "
137 "type %qT", decl, type);
138 decl = error_mark_node;
141 return decl;
144 /* Issue a diagnostic with text GMSGID for constructs that are invalid in
145 constexpr functions. CONSTEXPR_FUNDEF_P is true if we're checking
146 a constexpr function body; if so, don't report hard errors and issue
147 a pedwarn pre-C++23, or a warning in C++23, if requested by
148 -Winvalid-constexpr. Otherwise, we're not in the context where we are
149 checking if a function can be marked 'constexpr', so give a hard error. */
151 ATTRIBUTE_GCC_DIAG(3,4)
152 static bool
153 constexpr_error (location_t location, bool constexpr_fundef_p,
154 const char *gmsgid, ...)
156 diagnostic_info diagnostic;
157 va_list ap;
158 rich_location richloc (line_table, location);
159 va_start (ap, gmsgid);
160 bool ret;
161 if (!constexpr_fundef_p)
163 /* Report an error that cannot be suppressed. */
164 diagnostic_set_info (&diagnostic, gmsgid, &ap, &richloc, DK_ERROR);
165 ret = diagnostic_report_diagnostic (global_dc, &diagnostic);
167 else if (warn_invalid_constexpr)
169 diagnostic_set_info (&diagnostic, gmsgid, &ap, &richloc,
170 cxx_dialect < cxx23 ? DK_PEDWARN : DK_WARNING);
171 diagnostic.option_index = OPT_Winvalid_constexpr;
172 ret = diagnostic_report_diagnostic (global_dc, &diagnostic);
174 else
175 ret = false;
176 va_end (ap);
177 return ret;
180 struct constexpr_fundef_hasher : ggc_ptr_hash<constexpr_fundef>
182 static hashval_t hash (const constexpr_fundef *);
183 static bool equal (const constexpr_fundef *, const constexpr_fundef *);
186 /* This table holds all constexpr function definitions seen in
187 the current translation unit. */
189 static GTY (()) hash_table<constexpr_fundef_hasher> *constexpr_fundef_table;
191 /* Utility function used for managing the constexpr function table.
192 Return true if the entries pointed to by P and Q are for the
193 same constexpr function. */
195 inline bool
196 constexpr_fundef_hasher::equal (const constexpr_fundef *lhs,
197 const constexpr_fundef *rhs)
199 return lhs->decl == rhs->decl;
202 /* Utility function used for managing the constexpr function table.
203 Return a hash value for the entry pointed to by Q. */
205 inline hashval_t
206 constexpr_fundef_hasher::hash (const constexpr_fundef *fundef)
208 return DECL_UID (fundef->decl);
211 /* Return a previously saved definition of function FUN. */
213 constexpr_fundef *
214 retrieve_constexpr_fundef (tree fun)
216 if (constexpr_fundef_table == NULL)
217 return NULL;
219 constexpr_fundef fundef = { fun, NULL_TREE, NULL_TREE, NULL_TREE };
220 return constexpr_fundef_table->find (&fundef);
223 /* Check whether the parameter and return types of FUN are valid for a
224 constexpr function, and complain if COMPLAIN. */
226 bool
227 is_valid_constexpr_fn (tree fun, bool complain)
229 bool ret = true;
231 if (DECL_INHERITED_CTOR (fun)
232 && TREE_CODE (fun) == TEMPLATE_DECL)
234 ret = false;
235 if (complain)
236 error ("inherited constructor %qD is not %<constexpr%>",
237 DECL_INHERITED_CTOR (fun));
239 else
241 for (tree parm = FUNCTION_FIRST_USER_PARM (fun);
242 parm != NULL_TREE; parm = TREE_CHAIN (parm))
243 if (!literal_type_p (TREE_TYPE (parm)))
245 ret = false;
246 if (complain)
248 auto_diagnostic_group d;
249 if (constexpr_error (input_location, /*constexpr_fundef_p*/true,
250 "invalid type for parameter %d of "
251 "%<constexpr%> function %q+#D",
252 DECL_PARM_INDEX (parm), fun))
253 explain_non_literal_class (TREE_TYPE (parm));
258 if (LAMBDA_TYPE_P (CP_DECL_CONTEXT (fun)) && cxx_dialect < cxx17)
260 ret = false;
261 if (complain)
262 inform (DECL_SOURCE_LOCATION (fun),
263 "lambdas are implicitly %<constexpr%> only in C++17 and later");
265 else if (DECL_DESTRUCTOR_P (fun))
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_IOBJ_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, bool initializing)
1198 if (modifiable && !modifiable->contains (t))
1199 return nullptr;
1200 if (tree *p = values.get (t))
1202 if (*p != void_node)
1203 return p;
1204 else if (initializing)
1206 *p = NULL_TREE;
1207 return p;
1210 return nullptr;
1212 void put_value (tree t, tree v)
1214 bool already_in_map = values.put (t, v);
1215 if (!already_in_map && modifiable)
1216 modifiable->add (t);
1218 void destroy_value (tree t)
1220 if (TREE_CODE (t) == VAR_DECL
1221 || TREE_CODE (t) == PARM_DECL
1222 || TREE_CODE (t) == RESULT_DECL)
1223 values.put (t, void_node);
1224 else
1225 values.remove (t);
1227 void clear_value (tree t)
1229 values.remove (t);
1233 /* Helper class for constexpr_global_ctx. In some cases we want to avoid
1234 side-effects from evaluation of a particular subexpression of a
1235 constant-expression. In such cases we use modifiable_tracker to prevent
1236 modification of variables created outside of that subexpression.
1238 ??? We could change the hash_set to a hash_map, allow and track external
1239 modifications, and roll them back in the destructor. It's not clear to me
1240 that this would be worthwhile. */
1242 class modifiable_tracker
1244 hash_set<tree> set;
1245 constexpr_global_ctx *global;
1246 public:
1247 modifiable_tracker (constexpr_global_ctx *g): global(g)
1249 global->modifiable = &set;
1251 ~modifiable_tracker ()
1253 for (tree t: set)
1254 global->clear_value (t);
1255 global->modifiable = nullptr;
1259 /* The constexpr expansion context. CALL is the current function
1260 expansion, CTOR is the current aggregate initializer, OBJECT is the
1261 object being initialized by CTOR, either a VAR_DECL or a _REF. */
1263 struct constexpr_ctx {
1264 /* The part of the context that needs to be unique to the whole
1265 cxx_eval_outermost_constant_expr invocation. */
1266 constexpr_global_ctx *global;
1267 /* The innermost call we're evaluating. */
1268 constexpr_call *call;
1269 /* SAVE_EXPRs and TARGET_EXPR_SLOT vars of TARGET_EXPRs that we've seen
1270 within the current LOOP_EXPR. NULL if we aren't inside a loop. */
1271 vec<tree> *save_exprs;
1272 /* The CONSTRUCTOR we're currently building up for an aggregate
1273 initializer. */
1274 tree ctor;
1275 /* The object we're building the CONSTRUCTOR for. */
1276 tree object;
1277 /* If inside SWITCH_EXPR. */
1278 constexpr_switch_state *css_state;
1279 /* The aggregate initialization context inside which this one is nested. This
1280 is used by lookup_placeholder to resolve PLACEHOLDER_EXPRs. */
1281 const constexpr_ctx *parent;
1283 /* Whether we should error on a non-constant expression or fail quietly.
1284 This flag needs to be here, but some of the others could move to global
1285 if they get larger than a word. */
1286 bool quiet;
1287 /* Whether we are strictly conforming to constant expression rules or
1288 trying harder to get a constant value. */
1289 bool strict;
1290 /* Whether __builtin_is_constant_evaluated () should be true. */
1291 mce_value manifestly_const_eval;
1294 /* Remove T from the global values map, checking for attempts to destroy
1295 a value that has already finished its lifetime. */
1297 static void
1298 destroy_value_checked (const constexpr_ctx* ctx, tree t, bool *non_constant_p)
1300 if (t == error_mark_node || TREE_TYPE (t) == error_mark_node)
1301 return;
1303 /* Don't error again here if we've already reported a problem. */
1304 if (!*non_constant_p
1305 && DECL_P (t)
1306 /* Non-trivial destructors have their lifetimes ended explicitly
1307 with a clobber, so don't worry about it here. */
1308 && (!TYPE_HAS_NONTRIVIAL_DESTRUCTOR (TREE_TYPE (t))
1309 /* ...except parameters are remapped in cxx_eval_call_expression,
1310 and the destructor call during cleanup won't be able to tell that
1311 this value has already been destroyed, so complain now. This is
1312 not quite unobservable, but is extremely unlikely to crop up in
1313 practice; see g++.dg/cpp2a/constexpr-lifetime2.C. */
1314 || TREE_CODE (t) == PARM_DECL)
1315 && ctx->global->is_outside_lifetime (t))
1317 if (!ctx->quiet)
1319 auto_diagnostic_group d;
1320 error ("destroying %qE outside its lifetime", t);
1321 inform (DECL_SOURCE_LOCATION (t), "declared here");
1323 *non_constant_p = true;
1325 ctx->global->destroy_value (t);
1328 /* This internal flag controls whether we should avoid doing anything during
1329 constexpr evaluation that would cause extra DECL_UID generation, such as
1330 template instantiation and function body copying. */
1332 static bool uid_sensitive_constexpr_evaluation_value;
1334 /* An internal counter that keeps track of the number of times
1335 uid_sensitive_constexpr_evaluation_p returned true. */
1337 static unsigned uid_sensitive_constexpr_evaluation_true_counter;
1339 /* The accessor for uid_sensitive_constexpr_evaluation_value which also
1340 increments the corresponding counter. */
1342 static bool
1343 uid_sensitive_constexpr_evaluation_p ()
1345 if (uid_sensitive_constexpr_evaluation_value)
1347 ++uid_sensitive_constexpr_evaluation_true_counter;
1348 return true;
1350 else
1351 return false;
1354 /* The default constructor for uid_sensitive_constexpr_evaluation_sentinel
1355 enables the internal flag for uid_sensitive_constexpr_evaluation_p
1356 during the lifetime of the sentinel object. Upon its destruction, the
1357 previous value of uid_sensitive_constexpr_evaluation_p is restored. */
1359 uid_sensitive_constexpr_evaluation_sentinel
1360 ::uid_sensitive_constexpr_evaluation_sentinel ()
1361 : ovr (uid_sensitive_constexpr_evaluation_value, true)
1365 /* The default constructor for uid_sensitive_constexpr_evaluation_checker
1366 records the current number of times that uid_sensitive_constexpr_evaluation_p
1367 has been called and returned true. */
1369 uid_sensitive_constexpr_evaluation_checker
1370 ::uid_sensitive_constexpr_evaluation_checker ()
1371 : saved_counter (uid_sensitive_constexpr_evaluation_true_counter)
1375 /* Returns true iff uid_sensitive_constexpr_evaluation_p is true, and
1376 some constexpr evaluation was restricted due to u_s_c_e_p being called
1377 and returning true during the lifetime of this checker object. */
1379 bool
1380 uid_sensitive_constexpr_evaluation_checker::evaluation_restricted_p () const
1382 return (uid_sensitive_constexpr_evaluation_value
1383 && saved_counter != uid_sensitive_constexpr_evaluation_true_counter);
1387 /* A table of all constexpr calls that have been evaluated by the
1388 compiler in this translation unit. */
1390 static GTY (()) hash_table<constexpr_call_hasher> *constexpr_call_table;
1392 /* Compute a hash value for a constexpr call representation. */
1394 inline hashval_t
1395 constexpr_call_hasher::hash (constexpr_call *info)
1397 return info->hash;
1400 /* Return true if the objects pointed to by P and Q represent calls
1401 to the same constexpr function with the same arguments.
1402 Otherwise, return false. */
1404 bool
1405 constexpr_call_hasher::equal (constexpr_call *lhs, constexpr_call *rhs)
1407 if (lhs == rhs)
1408 return true;
1409 if (lhs->hash != rhs->hash)
1410 return false;
1411 if (lhs->manifestly_const_eval != rhs->manifestly_const_eval)
1412 return false;
1413 if (!constexpr_fundef_hasher::equal (lhs->fundef, rhs->fundef))
1414 return false;
1415 return cp_tree_equal (lhs->bindings, rhs->bindings);
1418 /* Initialize the constexpr call table, if needed. */
1420 static void
1421 maybe_initialize_constexpr_call_table (void)
1423 if (constexpr_call_table == NULL)
1424 constexpr_call_table = hash_table<constexpr_call_hasher>::create_ggc (101);
1427 /* During constexpr CALL_EXPR evaluation, to avoid issues with sharing when
1428 a function happens to get called recursively, we unshare the callee
1429 function's body and evaluate this unshared copy instead of evaluating the
1430 original body.
1432 FUNDEF_COPIES_TABLE is a per-function freelist of these unshared function
1433 copies. The underlying data structure of FUNDEF_COPIES_TABLE is a hash_map
1434 that's keyed off of the original FUNCTION_DECL and whose value is a
1435 TREE_LIST of this function's unused copies awaiting reuse.
1437 This is not GC-deletable to avoid GC affecting UID generation. */
1439 static GTY(()) decl_tree_map *fundef_copies_table;
1441 /* Reuse a copy or create a new unshared copy of the function FUN.
1442 Return this copy. We use a TREE_LIST whose PURPOSE is body, VALUE
1443 is parms, TYPE is result. */
1445 static tree
1446 get_fundef_copy (constexpr_fundef *fundef)
1448 tree copy;
1449 bool existed;
1450 tree *slot = &(hash_map_safe_get_or_insert<hm_ggc>
1451 (fundef_copies_table, fundef->decl, &existed, 127));
1453 if (!existed)
1455 /* There is no cached function available, or in use. We can use
1456 the function directly. That the slot is now created records
1457 that this function is now in use. */
1458 copy = build_tree_list (fundef->body, fundef->parms);
1459 TREE_TYPE (copy) = fundef->result;
1461 else if (*slot == NULL_TREE)
1463 if (uid_sensitive_constexpr_evaluation_p ())
1464 return NULL_TREE;
1466 /* We've already used the function itself, so make a copy. */
1467 copy = build_tree_list (NULL, NULL);
1468 tree saved_body = DECL_SAVED_TREE (fundef->decl);
1469 tree saved_parms = DECL_ARGUMENTS (fundef->decl);
1470 tree saved_result = DECL_RESULT (fundef->decl);
1471 tree saved_fn = current_function_decl;
1472 DECL_SAVED_TREE (fundef->decl) = fundef->body;
1473 DECL_ARGUMENTS (fundef->decl) = fundef->parms;
1474 DECL_RESULT (fundef->decl) = fundef->result;
1475 current_function_decl = fundef->decl;
1476 TREE_PURPOSE (copy) = copy_fn (fundef->decl, TREE_VALUE (copy),
1477 TREE_TYPE (copy));
1478 current_function_decl = saved_fn;
1479 DECL_RESULT (fundef->decl) = saved_result;
1480 DECL_ARGUMENTS (fundef->decl) = saved_parms;
1481 DECL_SAVED_TREE (fundef->decl) = saved_body;
1483 else
1485 /* We have a cached function available. */
1486 copy = *slot;
1487 *slot = TREE_CHAIN (copy);
1490 return copy;
1493 /* Save the copy COPY of function FUN for later reuse by
1494 get_fundef_copy(). By construction, there will always be an entry
1495 to find. */
1497 static void
1498 save_fundef_copy (tree fun, tree copy)
1500 tree *slot = fundef_copies_table->get (fun);
1501 TREE_CHAIN (copy) = *slot;
1502 *slot = copy;
1505 /* Whether our evaluation wants a prvalue (e.g. CONSTRUCTOR or _CST),
1506 a glvalue (e.g. VAR_DECL or _REF), or nothing. */
1508 enum value_cat {
1509 vc_prvalue = 0,
1510 vc_glvalue = 1,
1511 vc_discard = 2
1514 static tree cxx_eval_constant_expression (const constexpr_ctx *, tree,
1515 value_cat, bool *, bool *, tree * = NULL);
1516 static tree cxx_eval_bare_aggregate (const constexpr_ctx *, tree,
1517 value_cat, bool *, bool *);
1518 static tree cxx_fold_indirect_ref (const constexpr_ctx *, location_t, tree, tree,
1519 bool * = NULL);
1520 static tree find_heap_var_refs (tree *, int *, void *);
1522 /* Attempt to evaluate T which represents a call to a builtin function.
1523 We assume here that all builtin functions evaluate to scalar types
1524 represented by _CST nodes. */
1526 static tree
1527 cxx_eval_builtin_function_call (const constexpr_ctx *ctx, tree t, tree fun,
1528 value_cat lval,
1529 bool *non_constant_p, bool *overflow_p)
1531 const int nargs = call_expr_nargs (t);
1532 tree *args = (tree *) alloca (nargs * sizeof (tree));
1533 tree new_call;
1534 int i;
1536 /* Don't fold __builtin_constant_p within a constexpr function. */
1537 bool bi_const_p = DECL_IS_BUILTIN_CONSTANT_P (fun);
1539 /* If we aren't requiring a constant expression, defer __builtin_constant_p
1540 in a constexpr function until we have values for the parameters. */
1541 if (bi_const_p
1542 && ctx->manifestly_const_eval != mce_true
1543 && current_function_decl
1544 && DECL_DECLARED_CONSTEXPR_P (current_function_decl))
1546 *non_constant_p = true;
1547 return t;
1550 /* For __builtin_is_constant_evaluated, defer it if not
1551 ctx->manifestly_const_eval (as sometimes we try to constant evaluate
1552 without manifestly_const_eval even expressions or parts thereof which
1553 will later be manifestly const_eval evaluated), otherwise fold it to
1554 true. */
1555 if (fndecl_built_in_p (fun, CP_BUILT_IN_IS_CONSTANT_EVALUATED,
1556 BUILT_IN_FRONTEND))
1558 if (ctx->manifestly_const_eval == mce_unknown)
1560 *non_constant_p = true;
1561 return t;
1563 return constant_boolean_node (ctx->manifestly_const_eval == mce_true,
1564 boolean_type_node);
1567 if (fndecl_built_in_p (fun, CP_BUILT_IN_SOURCE_LOCATION, BUILT_IN_FRONTEND))
1569 temp_override<tree> ovr (current_function_decl);
1570 if (ctx->call && ctx->call->fundef)
1571 current_function_decl = ctx->call->fundef->decl;
1572 return fold_builtin_source_location (t);
1575 int strops = 0;
1576 int strret = 0;
1577 if (fndecl_built_in_p (fun, BUILT_IN_NORMAL))
1578 switch (DECL_FUNCTION_CODE (fun))
1580 case BUILT_IN_STRLEN:
1581 case BUILT_IN_STRNLEN:
1582 strops = 1;
1583 break;
1584 case BUILT_IN_MEMCHR:
1585 case BUILT_IN_STRCHR:
1586 case BUILT_IN_STRRCHR:
1587 strops = 1;
1588 strret = 1;
1589 break;
1590 case BUILT_IN_MEMCMP:
1591 case BUILT_IN_STRCMP:
1592 strops = 2;
1593 break;
1594 case BUILT_IN_STRSTR:
1595 strops = 2;
1596 strret = 1;
1597 break;
1598 case BUILT_IN_ASAN_POINTER_COMPARE:
1599 case BUILT_IN_ASAN_POINTER_SUBTRACT:
1600 /* These builtins shall be ignored during constant expression
1601 evaluation. */
1602 return void_node;
1603 case BUILT_IN_UNREACHABLE:
1604 case BUILT_IN_TRAP:
1605 if (!*non_constant_p && !ctx->quiet)
1607 /* Do not allow__builtin_unreachable in constexpr function.
1608 The __builtin_unreachable call with BUILTINS_LOCATION
1609 comes from cp_maybe_instrument_return. */
1610 if (EXPR_LOCATION (t) == BUILTINS_LOCATION)
1611 error ("%<constexpr%> call flows off the end of the function");
1612 else
1613 error ("%q+E is not a constant expression", t);
1615 *non_constant_p = true;
1616 return t;
1617 default:
1618 break;
1621 /* Be permissive for arguments to built-ins; __builtin_constant_p should
1622 return constant false for a non-constant argument. */
1623 constexpr_ctx new_ctx = *ctx;
1624 new_ctx.quiet = true;
1625 for (i = 0; i < nargs; ++i)
1627 tree arg = CALL_EXPR_ARG (t, i);
1628 tree oarg = arg;
1630 /* To handle string built-ins we need to pass ADDR_EXPR<STRING_CST> since
1631 expand_builtin doesn't know how to look in the values table. */
1632 bool strop = i < strops;
1633 if (strop)
1635 STRIP_NOPS (arg);
1636 if (TREE_CODE (arg) == ADDR_EXPR)
1637 arg = TREE_OPERAND (arg, 0);
1638 else
1639 strop = false;
1642 /* If builtin_valid_in_constant_expr_p is true,
1643 potential_constant_expression_1 has not recursed into the arguments
1644 of the builtin, verify it here. */
1645 if (!builtin_valid_in_constant_expr_p (fun)
1646 || potential_constant_expression (arg))
1648 bool dummy1 = false, dummy2 = false;
1649 arg = cxx_eval_constant_expression (&new_ctx, arg, vc_prvalue,
1650 &dummy1, &dummy2);
1653 if (bi_const_p)
1654 /* For __builtin_constant_p, fold all expressions with constant values
1655 even if they aren't C++ constant-expressions. */
1656 arg = cp_fold_rvalue (arg);
1657 else if (strop)
1659 if (TREE_CODE (arg) == CONSTRUCTOR)
1660 arg = braced_lists_to_strings (TREE_TYPE (arg), arg);
1661 if (TREE_CODE (arg) == STRING_CST)
1662 arg = build_address (arg);
1663 else
1664 arg = oarg;
1667 args[i] = arg;
1670 bool save_ffbcp = force_folding_builtin_constant_p;
1671 force_folding_builtin_constant_p |= ctx->manifestly_const_eval == mce_true;
1672 tree save_cur_fn = current_function_decl;
1673 /* Return name of ctx->call->fundef->decl for __builtin_FUNCTION (). */
1674 if (fndecl_built_in_p (fun, BUILT_IN_FUNCTION)
1675 && ctx->call
1676 && ctx->call->fundef)
1677 current_function_decl = ctx->call->fundef->decl;
1678 if (fndecl_built_in_p (fun,
1679 CP_BUILT_IN_IS_POINTER_INTERCONVERTIBLE_WITH_CLASS,
1680 BUILT_IN_FRONTEND))
1682 location_t loc = EXPR_LOCATION (t);
1683 if (nargs >= 1)
1684 VERIFY_CONSTANT (args[0]);
1685 new_call
1686 = fold_builtin_is_pointer_inverconvertible_with_class (loc, nargs,
1687 args);
1689 else if (fndecl_built_in_p (fun,
1690 CP_BUILT_IN_IS_CORRESPONDING_MEMBER,
1691 BUILT_IN_FRONTEND))
1693 location_t loc = EXPR_LOCATION (t);
1694 if (nargs >= 2)
1696 VERIFY_CONSTANT (args[0]);
1697 VERIFY_CONSTANT (args[1]);
1699 new_call = fold_builtin_is_corresponding_member (loc, nargs, args);
1701 else
1702 new_call = fold_builtin_call_array (EXPR_LOCATION (t), TREE_TYPE (t),
1703 CALL_EXPR_FN (t), nargs, args);
1704 current_function_decl = save_cur_fn;
1705 force_folding_builtin_constant_p = save_ffbcp;
1706 if (new_call == NULL)
1708 if (!*non_constant_p && !ctx->quiet)
1710 new_call = build_call_array_loc (EXPR_LOCATION (t), TREE_TYPE (t),
1711 CALL_EXPR_FN (t), nargs, args);
1712 error ("%q+E is not a constant expression", new_call);
1714 *non_constant_p = true;
1715 return t;
1718 if (!potential_constant_expression (new_call))
1720 if (!*non_constant_p && !ctx->quiet)
1721 error ("%q+E is not a constant expression", new_call);
1722 *non_constant_p = true;
1723 return t;
1726 if (strret)
1728 /* memchr returns a pointer into the first argument, but we replaced the
1729 argument above with a STRING_CST; put it back it now. */
1730 tree op = CALL_EXPR_ARG (t, strret-1);
1731 STRIP_NOPS (new_call);
1732 if (TREE_CODE (new_call) == POINTER_PLUS_EXPR)
1733 TREE_OPERAND (new_call, 0) = op;
1734 else if (TREE_CODE (new_call) == ADDR_EXPR)
1735 new_call = op;
1738 return cxx_eval_constant_expression (&new_ctx, new_call, lval,
1739 non_constant_p, overflow_p);
1742 /* TEMP is the constant value of a temporary object of type TYPE. Adjust
1743 the type of the value to match. */
1745 static tree
1746 adjust_temp_type (tree type, tree temp)
1748 if (same_type_p (TREE_TYPE (temp), type))
1749 return temp;
1750 /* Avoid wrapping an aggregate value in a NOP_EXPR. */
1751 if (TREE_CODE (temp) == CONSTRUCTOR)
1753 /* build_constructor wouldn't retain various CONSTRUCTOR flags. */
1754 tree t = copy_node (temp);
1755 TREE_TYPE (t) = type;
1756 return t;
1758 if (TREE_CODE (temp) == EMPTY_CLASS_EXPR)
1759 return build0 (EMPTY_CLASS_EXPR, type);
1760 gcc_assert (scalarish_type_p (type));
1761 /* Now we know we're dealing with a scalar, and a prvalue of non-class
1762 type is cv-unqualified. */
1763 return cp_fold_convert (cv_unqualified (type), temp);
1766 /* If T is a CONSTRUCTOR, return an unshared copy of T and any
1767 sub-CONSTRUCTORs. Otherwise return T.
1769 We use this whenever we initialize an object as a whole, whether it's a
1770 parameter, a local variable, or a subobject, so that subsequent
1771 modifications don't affect other places where it was used. */
1773 tree
1774 unshare_constructor (tree t MEM_STAT_DECL)
1776 if (!t || TREE_CODE (t) != CONSTRUCTOR)
1777 return t;
1778 auto_vec <tree*, 4> ptrs;
1779 ptrs.safe_push (&t);
1780 while (!ptrs.is_empty ())
1782 tree *p = ptrs.pop ();
1783 tree n = copy_node (*p PASS_MEM_STAT);
1784 CONSTRUCTOR_ELTS (n) = vec_safe_copy (CONSTRUCTOR_ELTS (*p) PASS_MEM_STAT);
1785 *p = n;
1786 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (n);
1787 constructor_elt *ce;
1788 for (HOST_WIDE_INT i = 0; vec_safe_iterate (v, i, &ce); ++i)
1789 if (ce->value && TREE_CODE (ce->value) == CONSTRUCTOR)
1790 ptrs.safe_push (&ce->value);
1792 return t;
1795 /* If T is a CONSTRUCTOR, ggc_free T and any sub-CONSTRUCTORs. */
1797 static void
1798 free_constructor (tree t)
1800 if (!t || TREE_CODE (t) != CONSTRUCTOR)
1801 return;
1802 releasing_vec ctors;
1803 vec_safe_push (ctors, t);
1804 while (!ctors->is_empty ())
1806 tree c = ctors->pop ();
1807 if (vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (c))
1809 constructor_elt *ce;
1810 for (HOST_WIDE_INT i = 0; vec_safe_iterate (elts, i, &ce); ++i)
1811 if (ce->value && TREE_CODE (ce->value) == CONSTRUCTOR)
1812 vec_safe_push (ctors, ce->value);
1813 ggc_free (elts);
1815 ggc_free (c);
1819 /* Helper function of cxx_bind_parameters_in_call. Return non-NULL
1820 if *TP is address of a static variable (or part of it) currently being
1821 constructed or of a heap artificial variable. */
1823 static tree
1824 addr_of_non_const_var (tree *tp, int *walk_subtrees, void *data)
1826 if (TREE_CODE (*tp) == ADDR_EXPR)
1827 if (tree var = get_base_address (TREE_OPERAND (*tp, 0)))
1828 if (VAR_P (var) && TREE_STATIC (var))
1830 if (DECL_NAME (var) == heap_uninit_identifier
1831 || DECL_NAME (var) == heap_identifier
1832 || DECL_NAME (var) == heap_vec_uninit_identifier
1833 || DECL_NAME (var) == heap_vec_identifier)
1834 return var;
1836 constexpr_global_ctx *global = (constexpr_global_ctx *) data;
1837 if (global->get_value (var))
1838 return var;
1840 if (TYPE_P (*tp))
1841 *walk_subtrees = false;
1842 return NULL_TREE;
1845 /* Subroutine of cxx_eval_call_expression.
1846 We are processing a call expression (either CALL_EXPR or
1847 AGGR_INIT_EXPR) in the context of CTX. Evaluate
1848 all arguments and bind their values to correspondings
1849 parameters, making up the NEW_CALL context. */
1851 static tree
1852 cxx_bind_parameters_in_call (const constexpr_ctx *ctx, tree t, tree fun,
1853 bool *non_constant_p, bool *overflow_p,
1854 bool *non_constant_args)
1856 const int nargs = call_expr_nargs (t);
1857 tree parms = DECL_ARGUMENTS (fun);
1858 int i;
1859 /* We don't record ellipsis args below. */
1860 int nparms = list_length (parms);
1861 int nbinds = nargs < nparms ? nargs : nparms;
1862 tree binds = make_tree_vec (nbinds);
1863 for (i = 0; i < nargs; ++i)
1865 tree x, arg;
1866 tree type = parms ? TREE_TYPE (parms) : void_type_node;
1867 if (parms && DECL_BY_REFERENCE (parms))
1868 type = TREE_TYPE (type);
1869 x = get_nth_callarg (t, i);
1870 /* For member function, the first argument is a pointer to the implied
1871 object. For a constructor, it might still be a dummy object, in
1872 which case we get the real argument from ctx. */
1873 if (i == 0 && DECL_CONSTRUCTOR_P (fun)
1874 && is_dummy_object (x))
1876 x = ctx->object;
1877 x = build_address (x);
1879 if (TREE_ADDRESSABLE (type))
1880 /* Undo convert_for_arg_passing work here. */
1881 x = convert_from_reference (x);
1882 /* Normally we would strip a TARGET_EXPR in an initialization context
1883 such as this, but here we do the elision differently: we keep the
1884 TARGET_EXPR, and use its CONSTRUCTOR as the value of the parm. */
1885 arg = cxx_eval_constant_expression (ctx, x, vc_prvalue,
1886 non_constant_p, overflow_p);
1887 /* Check we aren't dereferencing a null pointer when calling a non-static
1888 member function, which is undefined behaviour. */
1889 if (i == 0 && DECL_OBJECT_MEMBER_FUNCTION_P (fun)
1890 && integer_zerop (arg)
1891 /* But ignore calls from within compiler-generated code, to handle
1892 cases like lambda function pointer conversion operator thunks
1893 which pass NULL as the 'this' pointer. */
1894 && !(TREE_CODE (t) == CALL_EXPR && CALL_FROM_THUNK_P (t)))
1896 if (!ctx->quiet)
1897 error_at (cp_expr_loc_or_input_loc (x),
1898 "dereferencing a null pointer");
1899 *non_constant_p = true;
1901 /* Don't VERIFY_CONSTANT here. */
1902 if (*non_constant_p && ctx->quiet)
1903 break;
1904 /* Just discard ellipsis args after checking their constantitude. */
1905 if (!parms)
1906 continue;
1908 if (!*non_constant_p)
1910 /* Make sure the binding has the same type as the parm. But
1911 only for constant args. */
1912 if (!TYPE_REF_P (type))
1913 arg = adjust_temp_type (type, arg);
1914 if (!TREE_CONSTANT (arg))
1915 *non_constant_args = true;
1916 else if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
1917 /* The destructor needs to see any modifications the callee makes
1918 to the argument. */
1919 *non_constant_args = true;
1920 /* If arg is or contains address of a heap artificial variable or
1921 of a static variable being constructed, avoid caching the
1922 function call, as those variables might be modified by the
1923 function, or might be modified by the callers in between
1924 the cached function and just read by the function. */
1925 else if (!*non_constant_args
1926 && cp_walk_tree (&arg, addr_of_non_const_var, ctx->global,
1927 NULL))
1928 *non_constant_args = true;
1930 /* For virtual calls, adjust the this argument, so that it is
1931 the object on which the method is called, rather than
1932 one of its bases. */
1933 if (i == 0 && DECL_VIRTUAL_P (fun))
1935 tree addr = arg;
1936 STRIP_NOPS (addr);
1937 if (TREE_CODE (addr) == ADDR_EXPR)
1939 tree obj = TREE_OPERAND (addr, 0);
1940 while (TREE_CODE (obj) == COMPONENT_REF
1941 && DECL_FIELD_IS_BASE (TREE_OPERAND (obj, 1))
1942 && !same_type_ignoring_top_level_qualifiers_p
1943 (TREE_TYPE (obj), DECL_CONTEXT (fun)))
1944 obj = TREE_OPERAND (obj, 0);
1945 if (obj != TREE_OPERAND (addr, 0))
1946 arg = build_fold_addr_expr_with_type (obj,
1947 TREE_TYPE (arg));
1950 TREE_VEC_ELT (binds, i) = arg;
1952 parms = TREE_CHAIN (parms);
1955 return binds;
1958 /* Variables and functions to manage constexpr call expansion context.
1959 These do not need to be marked for PCH or GC. */
1961 /* FIXME remember and print actual constant arguments. */
1962 static vec<tree> call_stack;
1963 static int call_stack_tick;
1964 static int last_cx_error_tick;
1966 static int
1967 push_cx_call_context (tree call)
1969 ++call_stack_tick;
1970 if (!EXPR_HAS_LOCATION (call))
1971 SET_EXPR_LOCATION (call, input_location);
1972 call_stack.safe_push (call);
1973 int len = call_stack.length ();
1974 if (len > max_constexpr_depth)
1975 return false;
1976 return len;
1979 static void
1980 pop_cx_call_context (void)
1982 ++call_stack_tick;
1983 call_stack.pop ();
1986 vec<tree>
1987 cx_error_context (void)
1989 vec<tree> r = vNULL;
1990 if (call_stack_tick != last_cx_error_tick
1991 && !call_stack.is_empty ())
1992 r = call_stack;
1993 last_cx_error_tick = call_stack_tick;
1994 return r;
1997 /* E is an operand of a failed assertion, fold it either with or without
1998 constexpr context. */
2000 static tree
2001 fold_operand (tree e, const constexpr_ctx *ctx)
2003 if (ctx)
2005 bool new_non_constant_p = false, new_overflow_p = false;
2006 e = cxx_eval_constant_expression (ctx, e, vc_prvalue,
2007 &new_non_constant_p,
2008 &new_overflow_p);
2010 else
2011 e = fold_non_dependent_expr (e, tf_none, /*manifestly_const_eval=*/true);
2012 return e;
2015 /* If we have a condition in conjunctive normal form (CNF), find the first
2016 failing clause. In other words, given an expression like
2018 true && true && false && true && false
2020 return the first 'false'. EXPR is the expression. */
2022 static tree
2023 find_failing_clause_r (const constexpr_ctx *ctx, tree expr)
2025 if (TREE_CODE (expr) == TRUTH_ANDIF_EXPR)
2027 /* First check the left side... */
2028 tree e = find_failing_clause_r (ctx, TREE_OPERAND (expr, 0));
2029 if (e == NULL_TREE)
2030 /* ...if we didn't find a false clause, check the right side. */
2031 e = find_failing_clause_r (ctx, TREE_OPERAND (expr, 1));
2032 return e;
2034 tree e = contextual_conv_bool (expr, tf_none);
2035 e = fold_operand (e, ctx);
2036 if (integer_zerop (e))
2037 /* This is the failing clause. */
2038 return expr;
2039 return NULL_TREE;
2042 /* Wrapper for find_failing_clause_r. */
2044 tree
2045 find_failing_clause (const constexpr_ctx *ctx, tree expr)
2047 if (TREE_CODE (expr) == TRUTH_ANDIF_EXPR)
2048 if (tree e = find_failing_clause_r (ctx, expr))
2049 expr = e;
2050 return expr;
2053 /* Emit additional diagnostics for failing condition BAD.
2054 Used by finish_static_assert and IFN_ASSUME constexpr diagnostics.
2055 If SHOW_EXPR_P is true, print the condition (because it was
2056 instantiation-dependent). */
2058 void
2059 diagnose_failing_condition (tree bad, location_t cloc, bool show_expr_p,
2060 const constexpr_ctx *ctx /* = nullptr */)
2062 /* Nobody wants to see the artificial (bool) cast. */
2063 bad = tree_strip_nop_conversions (bad);
2064 if (TREE_CODE (bad) == CLEANUP_POINT_EXPR)
2065 bad = TREE_OPERAND (bad, 0);
2067 /* Actually explain the failure if this is a concept check or a
2068 requires-expression. */
2069 if (concept_check_p (bad) || TREE_CODE (bad) == REQUIRES_EXPR)
2070 diagnose_constraints (cloc, bad, NULL_TREE);
2071 else if (COMPARISON_CLASS_P (bad)
2072 && ARITHMETIC_TYPE_P (TREE_TYPE (TREE_OPERAND (bad, 0))))
2074 tree op0 = fold_operand (TREE_OPERAND (bad, 0), ctx);
2075 tree op1 = fold_operand (TREE_OPERAND (bad, 1), ctx);
2076 tree cond = build2 (TREE_CODE (bad), boolean_type_node, op0, op1);
2077 inform (cloc, "the comparison reduces to %qE", cond);
2079 else if (show_expr_p)
2080 inform (cloc, "%qE evaluates to false", bad);
2083 /* Process an assert/assume of ORIG_ARG. If it's not supposed to be evaluated,
2084 do it without changing the current evaluation state. If it evaluates to
2085 false, complain and return false; otherwise, return true. */
2087 static bool
2088 cxx_eval_assert (const constexpr_ctx *ctx, tree arg, const char *msg,
2089 location_t loc, bool evaluated,
2090 bool *non_constant_p, bool *overflow_p)
2092 if (*non_constant_p)
2093 return true;
2095 tree eval;
2096 if (!evaluated)
2098 if (!potential_rvalue_constant_expression (arg))
2099 return true;
2101 constexpr_ctx new_ctx = *ctx;
2102 new_ctx.quiet = true;
2103 bool new_non_constant_p = false, new_overflow_p = false;
2104 /* Avoid modification of existing values. */
2105 modifiable_tracker ms (new_ctx.global);
2106 eval = cxx_eval_constant_expression (&new_ctx, arg, vc_prvalue,
2107 &new_non_constant_p,
2108 &new_overflow_p);
2110 else
2111 eval = cxx_eval_constant_expression (ctx, arg, vc_prvalue,
2112 non_constant_p,
2113 overflow_p);
2114 if (!*non_constant_p && integer_zerop (eval))
2116 if (!ctx->quiet)
2118 /* See if we can find which clause was failing
2119 (for logical AND). */
2120 tree bad = find_failing_clause (ctx, arg);
2121 /* If not, or its location is unusable, fall back to the
2122 previous location. */
2123 location_t cloc = cp_expr_loc_or_loc (bad, loc);
2125 /* Report the error. */
2126 auto_diagnostic_group d;
2127 error_at (cloc, msg);
2128 diagnose_failing_condition (bad, cloc, true, ctx);
2129 return bad;
2131 *non_constant_p = true;
2132 return false;
2135 return true;
2138 /* Evaluate a call T to a GCC internal function when possible and return
2139 the evaluated result or, under the control of CTX, give an error, set
2140 NON_CONSTANT_P, and return the unevaluated call T otherwise. */
2142 static tree
2143 cxx_eval_internal_function (const constexpr_ctx *ctx, tree t,
2144 value_cat lval,
2145 bool *non_constant_p, bool *overflow_p)
2147 enum tree_code opcode = ERROR_MARK;
2149 switch (CALL_EXPR_IFN (t))
2151 case IFN_UBSAN_NULL:
2152 case IFN_UBSAN_BOUNDS:
2153 case IFN_UBSAN_VPTR:
2154 case IFN_FALLTHROUGH:
2155 return void_node;
2157 case IFN_ASSUME:
2158 if (!cxx_eval_assert (ctx, CALL_EXPR_ARG (t, 0),
2159 G_("failed %<assume%> attribute assumption"),
2160 EXPR_LOCATION (t), /*eval*/false,
2161 non_constant_p, overflow_p))
2162 return t;
2163 return void_node;
2165 case IFN_ADD_OVERFLOW:
2166 opcode = PLUS_EXPR;
2167 break;
2168 case IFN_SUB_OVERFLOW:
2169 opcode = MINUS_EXPR;
2170 break;
2171 case IFN_MUL_OVERFLOW:
2172 opcode = MULT_EXPR;
2173 break;
2175 case IFN_LAUNDER:
2176 return cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0),
2177 vc_prvalue, non_constant_p,
2178 overflow_p);
2180 case IFN_VEC_CONVERT:
2182 tree arg = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0),
2183 vc_prvalue, non_constant_p,
2184 overflow_p);
2185 if (TREE_CODE (arg) == VECTOR_CST)
2186 if (tree r = fold_const_call (CFN_VEC_CONVERT, TREE_TYPE (t), arg))
2187 return r;
2189 /* FALLTHRU */
2191 default:
2192 if (!ctx->quiet)
2193 error_at (cp_expr_loc_or_input_loc (t),
2194 "call to internal function %qE", t);
2195 *non_constant_p = true;
2196 return t;
2199 /* Evaluate constant arguments using OPCODE and return a complex
2200 number containing the result and the overflow bit. */
2201 tree arg0 = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0), lval,
2202 non_constant_p, overflow_p);
2203 tree arg1 = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 1), lval,
2204 non_constant_p, overflow_p);
2206 if (TREE_CODE (arg0) == INTEGER_CST && TREE_CODE (arg1) == INTEGER_CST)
2208 location_t loc = cp_expr_loc_or_input_loc (t);
2209 tree type = TREE_TYPE (TREE_TYPE (t));
2210 tree result = fold_binary_loc (loc, opcode, type,
2211 fold_convert_loc (loc, type, arg0),
2212 fold_convert_loc (loc, type, arg1));
2213 tree ovf
2214 = build_int_cst (type, arith_overflowed_p (opcode, type, arg0, arg1));
2215 /* Reset TREE_OVERFLOW to avoid warnings for the overflow. */
2216 if (TREE_OVERFLOW (result))
2217 TREE_OVERFLOW (result) = 0;
2219 return build_complex (TREE_TYPE (t), result, ovf);
2222 *non_constant_p = true;
2223 return t;
2226 /* Clean CONSTRUCTOR_NO_CLEARING from CTOR and its sub-aggregates. */
2228 static void
2229 clear_no_implicit_zero (tree ctor)
2231 if (CONSTRUCTOR_NO_CLEARING (ctor))
2233 CONSTRUCTOR_NO_CLEARING (ctor) = false;
2234 for (auto &e: CONSTRUCTOR_ELTS (ctor))
2235 if (TREE_CODE (e.value) == CONSTRUCTOR)
2236 clear_no_implicit_zero (e.value);
2240 /* Complain about a const object OBJ being modified in a constant expression.
2241 EXPR is the MODIFY_EXPR expression performing the modification. */
2243 static void
2244 modifying_const_object_error (tree expr, tree obj)
2246 location_t loc = cp_expr_loc_or_input_loc (expr);
2247 auto_diagnostic_group d;
2248 error_at (loc, "modifying a const object %qE is not allowed in "
2249 "a constant expression", TREE_OPERAND (expr, 0));
2251 /* Find the underlying object that was declared as const. */
2252 location_t decl_loc = UNKNOWN_LOCATION;
2253 for (tree probe = obj; decl_loc == UNKNOWN_LOCATION; )
2254 switch (TREE_CODE (probe))
2256 case BIT_FIELD_REF:
2257 case COMPONENT_REF:
2259 tree elt = TREE_OPERAND (probe, 1);
2260 if (CP_TYPE_CONST_P (TREE_TYPE (elt)))
2261 decl_loc = DECL_SOURCE_LOCATION (elt);
2262 probe = TREE_OPERAND (probe, 0);
2264 break;
2266 case ARRAY_REF:
2267 case REALPART_EXPR:
2268 case IMAGPART_EXPR:
2269 probe = TREE_OPERAND (probe, 0);
2270 break;
2272 default:
2273 decl_loc = location_of (probe);
2274 break;
2276 inform (decl_loc, "originally declared %<const%> here");
2279 /* Return true if FNDECL is a replaceable global allocation function that
2280 should be useable during constant expression evaluation. */
2282 static inline bool
2283 cxx_replaceable_global_alloc_fn (tree fndecl)
2285 return (cxx_dialect >= cxx20
2286 && IDENTIFIER_NEWDEL_OP_P (DECL_NAME (fndecl))
2287 && CP_DECL_CONTEXT (fndecl) == global_namespace
2288 && (DECL_IS_REPLACEABLE_OPERATOR_NEW_P (fndecl)
2289 || DECL_IS_OPERATOR_DELETE_P (fndecl)));
2292 /* Return true if FNDECL is a placement new function that should be
2293 useable during constant expression evaluation of std::construct_at. */
2295 static inline bool
2296 cxx_placement_new_fn (tree fndecl)
2298 if (cxx_dialect >= cxx20
2299 && IDENTIFIER_NEW_OP_P (DECL_NAME (fndecl))
2300 && CP_DECL_CONTEXT (fndecl) == global_namespace
2301 && !DECL_IS_REPLACEABLE_OPERATOR_NEW_P (fndecl)
2302 && TREE_CODE (TREE_TYPE (fndecl)) == FUNCTION_TYPE)
2304 tree first_arg = TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (fndecl)));
2305 if (TREE_VALUE (first_arg) == ptr_type_node
2306 && TREE_CHAIN (first_arg) == void_list_node)
2307 return true;
2309 return false;
2312 /* Return true if FNDECL is std::construct_at. */
2314 static inline bool
2315 is_std_construct_at (tree fndecl)
2317 if (!decl_in_std_namespace_p (fndecl))
2318 return false;
2320 tree name = DECL_NAME (fndecl);
2321 return name && id_equal (name, "construct_at");
2324 /* Overload for the above taking constexpr_call*. */
2326 static inline bool
2327 is_std_construct_at (const constexpr_call *call)
2329 return (call
2330 && call->fundef
2331 && is_std_construct_at (call->fundef->decl));
2334 /* True if CTX is an instance of std::allocator. */
2336 bool
2337 is_std_allocator (tree ctx)
2339 if (ctx == NULL_TREE || !CLASS_TYPE_P (ctx) || !TYPE_MAIN_DECL (ctx))
2340 return false;
2342 tree decl = TYPE_MAIN_DECL (ctx);
2343 tree name = DECL_NAME (decl);
2344 if (name == NULL_TREE || !id_equal (name, "allocator"))
2345 return false;
2347 return decl_in_std_namespace_p (decl);
2350 /* Return true if FNDECL is std::allocator<T>::{,de}allocate. */
2352 static inline bool
2353 is_std_allocator_allocate (tree fndecl)
2355 tree name = DECL_NAME (fndecl);
2356 if (name == NULL_TREE
2357 || !(id_equal (name, "allocate") || id_equal (name, "deallocate")))
2358 return false;
2360 return is_std_allocator (DECL_CONTEXT (fndecl));
2363 /* Overload for the above taking constexpr_call*. */
2365 static inline bool
2366 is_std_allocator_allocate (const constexpr_call *call)
2368 return (call
2369 && call->fundef
2370 && is_std_allocator_allocate (call->fundef->decl));
2373 /* Return true if FNDECL is std::source_location::current. */
2375 static inline bool
2376 is_std_source_location_current (tree fndecl)
2378 if (!decl_in_std_namespace_p (fndecl))
2379 return false;
2381 tree name = DECL_NAME (fndecl);
2382 if (name == NULL_TREE || !id_equal (name, "current"))
2383 return false;
2385 tree ctx = DECL_CONTEXT (fndecl);
2386 if (ctx == NULL_TREE || !CLASS_TYPE_P (ctx) || !TYPE_MAIN_DECL (ctx))
2387 return false;
2389 name = DECL_NAME (TYPE_MAIN_DECL (ctx));
2390 return name && id_equal (name, "source_location");
2393 /* Overload for the above taking constexpr_call*. */
2395 static inline bool
2396 is_std_source_location_current (const constexpr_call *call)
2398 return (call
2399 && call->fundef
2400 && is_std_source_location_current (call->fundef->decl));
2403 /* Return true if FNDECL is __dynamic_cast. */
2405 static inline bool
2406 cxx_dynamic_cast_fn_p (tree fndecl)
2408 return (cxx_dialect >= cxx20
2409 && id_equal (DECL_NAME (fndecl), "__dynamic_cast")
2410 && CP_DECL_CONTEXT (fndecl) == abi_node);
2413 /* Often, we have an expression in the form of address + offset, e.g.
2414 "&_ZTV1A + 16". Extract the object from it, i.e. "_ZTV1A". */
2416 static tree
2417 extract_obj_from_addr_offset (tree expr)
2419 if (TREE_CODE (expr) == POINTER_PLUS_EXPR)
2420 expr = TREE_OPERAND (expr, 0);
2421 STRIP_NOPS (expr);
2422 if (TREE_CODE (expr) == ADDR_EXPR)
2423 expr = TREE_OPERAND (expr, 0);
2424 return expr;
2427 /* Given a PATH like
2429 g.D.2181.D.2154.D.2102.D.2093
2431 find a component with type TYPE. Return NULL_TREE if not found, and
2432 error_mark_node if the component is not accessible. If STOP is non-null,
2433 this function will return NULL_TREE if STOP is found before TYPE. */
2435 static tree
2436 get_component_with_type (tree path, tree type, tree stop)
2438 while (true)
2440 if (same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (path), type))
2441 /* Found it. */
2442 return path;
2443 else if (stop
2444 && (same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (path),
2445 stop)))
2446 return NULL_TREE;
2447 else if (TREE_CODE (path) == COMPONENT_REF
2448 && DECL_FIELD_IS_BASE (TREE_OPERAND (path, 1)))
2450 /* We need to check that the component we're accessing is in fact
2451 accessible. */
2452 if (TREE_PRIVATE (TREE_OPERAND (path, 1))
2453 || TREE_PROTECTED (TREE_OPERAND (path, 1)))
2454 return error_mark_node;
2455 path = TREE_OPERAND (path, 0);
2457 else
2458 return NULL_TREE;
2462 /* Evaluate a call to __dynamic_cast (permitted by P1327R1).
2464 The declaration of __dynamic_cast is:
2466 void* __dynamic_cast (const void* __src_ptr,
2467 const __class_type_info* __src_type,
2468 const __class_type_info* __dst_type,
2469 ptrdiff_t __src2dst);
2471 where src2dst has the following possible values
2473 >-1: src_type is a unique public non-virtual base of dst_type
2474 dst_ptr + src2dst == src_ptr
2475 -1: unspecified relationship
2476 -2: src_type is not a public base of dst_type
2477 -3: src_type is a multiple public non-virtual base of dst_type
2479 Since literal types can't have virtual bases, we only expect hint >=0,
2480 -2, or -3. */
2482 static tree
2483 cxx_eval_dynamic_cast_fn (const constexpr_ctx *ctx, tree call,
2484 bool *non_constant_p, bool *overflow_p)
2486 /* T will be something like
2487 __dynamic_cast ((B*) b, &_ZTI1B, &_ZTI1D, 8)
2488 dismantle it. */
2489 gcc_assert (call_expr_nargs (call) == 4);
2490 tsubst_flags_t complain = ctx->quiet ? tf_none : tf_warning_or_error;
2491 tree obj = CALL_EXPR_ARG (call, 0);
2492 tree type = CALL_EXPR_ARG (call, 2);
2493 HOST_WIDE_INT hint = int_cst_value (CALL_EXPR_ARG (call, 3));
2494 location_t loc = cp_expr_loc_or_input_loc (call);
2496 /* Get the target type of the dynamic_cast. */
2497 gcc_assert (TREE_CODE (type) == ADDR_EXPR);
2498 type = TREE_OPERAND (type, 0);
2499 type = TREE_TYPE (DECL_NAME (type));
2501 /* TYPE can only be either T* or T&. We can't know which of these it
2502 is by looking at TYPE, but OBJ will be "(T*) x" in the first case,
2503 and something like "(T*)(T&)(T*) x" in the second case. */
2504 bool reference_p = false;
2505 while (CONVERT_EXPR_P (obj) || TREE_CODE (obj) == SAVE_EXPR)
2507 reference_p |= TYPE_REF_P (TREE_TYPE (obj));
2508 obj = TREE_OPERAND (obj, 0);
2511 /* Evaluate the object so that we know its dynamic type. */
2512 obj = cxx_eval_constant_expression (ctx, obj, vc_prvalue, non_constant_p,
2513 overflow_p);
2514 if (*non_constant_p)
2515 return call;
2517 /* We expect OBJ to be in form of &d.D.2102 when HINT == 0,
2518 but when HINT is > 0, it can also be something like
2519 &d.D.2102 + 18446744073709551608, which includes the BINFO_OFFSET. */
2520 obj = extract_obj_from_addr_offset (obj);
2521 const tree objtype = TREE_TYPE (obj);
2522 /* If OBJ doesn't refer to a base field, we're done. */
2523 if (tree t = (TREE_CODE (obj) == COMPONENT_REF
2524 ? TREE_OPERAND (obj, 1) : obj))
2525 if (TREE_CODE (t) != FIELD_DECL || !DECL_FIELD_IS_BASE (t))
2527 if (reference_p)
2529 if (!ctx->quiet)
2531 auto_diagnostic_group d;
2532 error_at (loc, "reference %<dynamic_cast%> failed");
2533 inform (loc, "dynamic type %qT of its operand does "
2534 "not have a base class of type %qT",
2535 objtype, type);
2537 *non_constant_p = true;
2539 return integer_zero_node;
2542 /* [class.cdtor] When a dynamic_cast is used in a constructor ...
2543 or in a destructor ... if the operand of the dynamic_cast refers
2544 to the object under construction or destruction, this object is
2545 considered to be a most derived object that has the type of the
2546 constructor or destructor's class. */
2547 tree vtable = build_vfield_ref (obj, objtype);
2548 vtable = cxx_eval_constant_expression (ctx, vtable, vc_prvalue,
2549 non_constant_p, overflow_p);
2550 if (*non_constant_p)
2551 return call;
2552 /* With -fsanitize=vptr, we initialize all vtable pointers to null,
2553 so it's possible that we got a null pointer now. */
2554 if (integer_zerop (vtable))
2556 if (!ctx->quiet)
2557 error_at (loc, "virtual table pointer is used uninitialized");
2558 *non_constant_p = true;
2559 return integer_zero_node;
2561 /* VTABLE will be &_ZTV1A + 16 or similar, get _ZTV1A. */
2562 vtable = extract_obj_from_addr_offset (vtable);
2563 const tree mdtype = DECL_CONTEXT (vtable);
2565 /* Given dynamic_cast<T>(v),
2567 [expr.dynamic.cast] If C is the class type to which T points or refers,
2568 the runtime check logically executes as follows:
2570 If, in the most derived object pointed (referred) to by v, v points
2571 (refers) to a public base class subobject of a C object, and if only
2572 one object of type C is derived from the subobject pointed (referred)
2573 to by v the result points (refers) to that C object.
2575 In this case, HINT >= 0 or -3. */
2576 if (hint >= 0 || hint == -3)
2578 /* Look for a component with type TYPE. */
2579 tree t = get_component_with_type (obj, type, mdtype);
2580 /* If not accessible, give an error. */
2581 if (t == error_mark_node)
2583 if (reference_p)
2585 if (!ctx->quiet)
2587 auto_diagnostic_group d;
2588 error_at (loc, "reference %<dynamic_cast%> failed");
2589 inform (loc, "static type %qT of its operand is a "
2590 "non-public base class of dynamic type %qT",
2591 objtype, type);
2594 *non_constant_p = true;
2596 return integer_zero_node;
2598 else if (t)
2599 /* The result points to the TYPE object. */
2600 return cp_build_addr_expr (t, complain);
2601 /* Else, TYPE was not found, because the HINT turned out to be wrong.
2602 Fall through to the normal processing. */
2605 /* Otherwise, if v points (refers) to a public base class subobject of the
2606 most derived object, and the type of the most derived object has a base
2607 class, of type C, that is unambiguous and public, the result points
2608 (refers) to the C subobject of the most derived object.
2610 But it can also be an invalid case. */
2612 /* Get the most derived object. */
2613 obj = get_component_with_type (obj, mdtype, NULL_TREE);
2614 if (obj == error_mark_node)
2616 if (reference_p)
2618 if (!ctx->quiet)
2620 auto_diagnostic_group d;
2621 error_at (loc, "reference %<dynamic_cast%> failed");
2622 inform (loc, "static type %qT of its operand is a non-public"
2623 " base class of dynamic type %qT", objtype, mdtype);
2625 *non_constant_p = true;
2627 return integer_zero_node;
2629 else
2630 gcc_assert (obj);
2632 /* Check that the type of the most derived object has a base class
2633 of type TYPE that is unambiguous and public. */
2634 base_kind b_kind;
2635 tree binfo = lookup_base (mdtype, type, ba_check, &b_kind, tf_none);
2636 if (!binfo || binfo == error_mark_node)
2638 if (reference_p)
2640 if (!ctx->quiet)
2642 auto_diagnostic_group d;
2643 error_at (loc, "reference %<dynamic_cast%> failed");
2644 if (b_kind == bk_ambig)
2645 inform (loc, "%qT is an ambiguous base class of dynamic "
2646 "type %qT of its operand", type, mdtype);
2647 else
2648 inform (loc, "dynamic type %qT of its operand does not "
2649 "have an unambiguous public base class %qT",
2650 mdtype, type);
2652 *non_constant_p = true;
2654 return integer_zero_node;
2656 /* If so, return the TYPE subobject of the most derived object. */
2657 obj = convert_to_base_statically (obj, binfo);
2658 return cp_build_addr_expr (obj, complain);
2661 /* Data structure used by replace_decl and replace_decl_r. */
2663 struct replace_decl_data
2665 /* The _DECL we want to replace. */
2666 tree decl;
2667 /* The replacement for DECL. */
2668 tree replacement;
2669 /* Trees we've visited. */
2670 hash_set<tree> *pset;
2671 /* Whether we've performed any replacements. */
2672 bool changed;
2675 /* Helper function for replace_decl, called through cp_walk_tree. */
2677 static tree
2678 replace_decl_r (tree *tp, int *walk_subtrees, void *data)
2680 replace_decl_data *d = (replace_decl_data *) data;
2682 if (*tp == d->decl)
2684 *tp = unshare_expr (d->replacement);
2685 d->changed = true;
2686 *walk_subtrees = 0;
2688 else if (TYPE_P (*tp)
2689 || d->pset->add (*tp))
2690 *walk_subtrees = 0;
2692 return NULL_TREE;
2695 /* Replace every occurrence of DECL with (an unshared copy of)
2696 REPLACEMENT within the expression *TP. Returns true iff a
2697 replacement was performed. */
2699 bool
2700 replace_decl (tree *tp, tree decl, tree replacement)
2702 gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
2703 (TREE_TYPE (decl), TREE_TYPE (replacement)));
2704 hash_set<tree> pset;
2705 replace_decl_data data = { decl, replacement, &pset, false };
2706 cp_walk_tree (tp, replace_decl_r, &data, NULL);
2707 return data.changed;
2710 /* Evaluate the call T to virtual function thunk THUNK_FNDECL. */
2712 static tree
2713 cxx_eval_thunk_call (const constexpr_ctx *ctx, tree t, tree thunk_fndecl,
2714 value_cat lval,
2715 bool *non_constant_p, bool *overflow_p)
2717 tree function = THUNK_TARGET (thunk_fndecl);
2719 if (THUNK_VIRTUAL_OFFSET (thunk_fndecl))
2721 if (!ctx->quiet)
2723 if (!DECL_DECLARED_CONSTEXPR_P (function))
2725 error ("call to non-%<constexpr%> function %qD", function);
2726 explain_invalid_constexpr_fn (function);
2728 else
2729 /* virtual_offset is only set for virtual bases, which make the
2730 class non-literal, so we don't need to handle it here. */
2731 error ("calling constexpr member function %qD through virtual "
2732 "base subobject", function);
2734 *non_constant_p = true;
2735 return t;
2738 tree new_call = copy_node (t);
2739 CALL_EXPR_FN (new_call) = function;
2740 TREE_TYPE (new_call) = TREE_TYPE (TREE_TYPE (function));
2742 tree offset = size_int (THUNK_FIXED_OFFSET (thunk_fndecl));
2744 if (DECL_THIS_THUNK_P (thunk_fndecl))
2746 /* 'this'-adjusting thunk. */
2747 tree this_arg = CALL_EXPR_ARG (t, 0);
2748 this_arg = build2 (POINTER_PLUS_EXPR, TREE_TYPE (this_arg),
2749 this_arg, offset);
2750 CALL_EXPR_ARG (new_call, 0) = this_arg;
2752 else
2753 /* Return-adjusting thunk. */
2754 new_call = build2 (POINTER_PLUS_EXPR, TREE_TYPE (new_call),
2755 new_call, offset);
2757 return cxx_eval_constant_expression (ctx, new_call, lval,
2758 non_constant_p, overflow_p);
2761 /* If OBJECT is of const class type, evaluate it to a CONSTRUCTOR and set
2762 its TREE_READONLY flag according to READONLY_P. Used for constexpr
2763 'tors to detect modifying const objects in a constexpr context. */
2765 static void
2766 cxx_set_object_constness (const constexpr_ctx *ctx, tree object,
2767 bool readonly_p, bool *non_constant_p,
2768 bool *overflow_p)
2770 if (CLASS_TYPE_P (TREE_TYPE (object))
2771 && CP_TYPE_CONST_P (TREE_TYPE (object)))
2773 /* Subobjects might not be stored in ctx->global->values but we
2774 can get its CONSTRUCTOR by evaluating *this. */
2775 tree e = cxx_eval_constant_expression (ctx, object, vc_prvalue,
2776 non_constant_p, overflow_p);
2777 if (TREE_CODE (e) == CONSTRUCTOR && !*non_constant_p)
2778 TREE_READONLY (e) = readonly_p;
2782 /* Subroutine of cxx_eval_constant_expression.
2783 Evaluate the call expression tree T in the context of OLD_CALL expression
2784 evaluation. */
2786 static tree
2787 cxx_eval_call_expression (const constexpr_ctx *ctx, tree t,
2788 value_cat lval,
2789 bool *non_constant_p, bool *overflow_p)
2791 /* Handle concept checks separately. */
2792 if (concept_check_p (t))
2793 return evaluate_concept_check (t);
2795 location_t loc = cp_expr_loc_or_input_loc (t);
2796 tree fun = get_function_named_in_call (t);
2797 constexpr_call new_call
2798 = { NULL, NULL, NULL, 0, ctx->manifestly_const_eval };
2799 int depth_ok;
2801 if (fun == NULL_TREE)
2802 return cxx_eval_internal_function (ctx, t, lval,
2803 non_constant_p, overflow_p);
2805 if (TREE_CODE (fun) != FUNCTION_DECL)
2807 /* Might be a constexpr function pointer. */
2808 fun = cxx_eval_constant_expression (ctx, fun, vc_prvalue,
2809 non_constant_p, overflow_p);
2810 STRIP_NOPS (fun);
2811 if (TREE_CODE (fun) == ADDR_EXPR)
2812 fun = TREE_OPERAND (fun, 0);
2813 /* For TARGET_VTABLE_USES_DESCRIPTORS targets, there is no
2814 indirection, the called expression is a pointer into the
2815 virtual table which should contain FDESC_EXPR. Extract the
2816 FUNCTION_DECL from there. */
2817 else if (TARGET_VTABLE_USES_DESCRIPTORS
2818 && TREE_CODE (fun) == POINTER_PLUS_EXPR
2819 && TREE_CODE (TREE_OPERAND (fun, 0)) == ADDR_EXPR
2820 && TREE_CODE (TREE_OPERAND (fun, 1)) == INTEGER_CST)
2822 tree d = TREE_OPERAND (TREE_OPERAND (fun, 0), 0);
2823 if (VAR_P (d)
2824 && DECL_VTABLE_OR_VTT_P (d)
2825 && TREE_CODE (TREE_TYPE (d)) == ARRAY_TYPE
2826 && TREE_TYPE (TREE_TYPE (d)) == vtable_entry_type
2827 && DECL_INITIAL (d)
2828 && TREE_CODE (DECL_INITIAL (d)) == CONSTRUCTOR)
2830 tree i = int_const_binop (TRUNC_DIV_EXPR, TREE_OPERAND (fun, 1),
2831 TYPE_SIZE_UNIT (vtable_entry_type));
2832 HOST_WIDE_INT idx = find_array_ctor_elt (DECL_INITIAL (d), i);
2833 if (idx >= 0)
2835 tree fdesc
2836 = (*CONSTRUCTOR_ELTS (DECL_INITIAL (d)))[idx].value;
2837 if (TREE_CODE (fdesc) == FDESC_EXPR
2838 && integer_zerop (TREE_OPERAND (fdesc, 1)))
2839 fun = TREE_OPERAND (fdesc, 0);
2844 if (TREE_CODE (fun) != FUNCTION_DECL)
2846 if (!ctx->quiet && !*non_constant_p)
2847 error_at (loc, "expression %qE does not designate a %<constexpr%> "
2848 "function", fun);
2849 *non_constant_p = true;
2850 return t;
2852 if (DECL_CLONED_FUNCTION_P (fun) && !DECL_DELETING_DESTRUCTOR_P (fun))
2853 fun = DECL_CLONED_FUNCTION (fun);
2855 if (is_ubsan_builtin_p (fun))
2856 return void_node;
2858 if (fndecl_built_in_p (fun))
2859 return cxx_eval_builtin_function_call (ctx, t, fun,
2860 lval, non_constant_p, overflow_p);
2861 if (DECL_THUNK_P (fun))
2862 return cxx_eval_thunk_call (ctx, t, fun, lval, non_constant_p, overflow_p);
2863 if (!maybe_constexpr_fn (fun))
2865 if (TREE_CODE (t) == CALL_EXPR
2866 && cxx_replaceable_global_alloc_fn (fun)
2867 && (CALL_FROM_NEW_OR_DELETE_P (t)
2868 || is_std_allocator_allocate (ctx->call)))
2870 const bool new_op_p = IDENTIFIER_NEW_OP_P (DECL_NAME (fun));
2871 const int nargs = call_expr_nargs (t);
2872 tree arg0 = NULL_TREE;
2873 for (int i = 0; i < nargs; ++i)
2875 tree arg = CALL_EXPR_ARG (t, i);
2876 arg = cxx_eval_constant_expression (ctx, arg, vc_prvalue,
2877 non_constant_p, overflow_p);
2878 /* Deleting a non-constant pointer has a better error message
2879 below. */
2880 if (new_op_p || i != 0)
2881 VERIFY_CONSTANT (arg);
2882 if (i == 0)
2883 arg0 = arg;
2885 gcc_assert (arg0);
2886 if (new_op_p)
2888 tree type = build_array_type_nelts (char_type_node,
2889 tree_to_uhwi (arg0));
2890 tree var = build_decl (loc, VAR_DECL,
2891 (IDENTIFIER_OVL_OP_FLAGS (DECL_NAME (fun))
2892 & OVL_OP_FLAG_VEC)
2893 ? heap_vec_uninit_identifier
2894 : heap_uninit_identifier,
2895 type);
2896 DECL_ARTIFICIAL (var) = 1;
2897 TREE_STATIC (var) = 1;
2898 // Temporarily register the artificial var in varpool,
2899 // so that comparisons of its address against NULL are folded
2900 // through nonzero_address even with
2901 // -fno-delete-null-pointer-checks or that comparison of
2902 // addresses of different heap artificial vars is folded too.
2903 // See PR98988 and PR99031.
2904 varpool_node::finalize_decl (var);
2905 ctx->global->heap_vars.safe_push (var);
2906 ctx->global->put_value (var, NULL_TREE);
2907 return fold_convert (ptr_type_node, build_address (var));
2909 else
2911 STRIP_NOPS (arg0);
2912 if (TREE_CODE (arg0) == ADDR_EXPR
2913 && VAR_P (TREE_OPERAND (arg0, 0)))
2915 tree var = TREE_OPERAND (arg0, 0);
2916 if (DECL_NAME (var) == heap_uninit_identifier
2917 || DECL_NAME (var) == heap_identifier)
2919 if (IDENTIFIER_OVL_OP_FLAGS (DECL_NAME (fun))
2920 & OVL_OP_FLAG_VEC)
2922 if (!ctx->quiet)
2924 auto_diagnostic_group d;
2925 error_at (loc, "array deallocation of object "
2926 "allocated with non-array "
2927 "allocation");
2928 inform (DECL_SOURCE_LOCATION (var),
2929 "allocation performed here");
2931 *non_constant_p = true;
2932 return t;
2934 DECL_NAME (var) = heap_deleted_identifier;
2935 ctx->global->destroy_value (var);
2936 ctx->global->heap_dealloc_count++;
2937 return void_node;
2939 else if (DECL_NAME (var) == heap_vec_uninit_identifier
2940 || DECL_NAME (var) == heap_vec_identifier)
2942 if ((IDENTIFIER_OVL_OP_FLAGS (DECL_NAME (fun))
2943 & OVL_OP_FLAG_VEC) == 0)
2945 if (!ctx->quiet)
2947 auto_diagnostic_group d;
2948 error_at (loc, "non-array deallocation of "
2949 "object allocated with array "
2950 "allocation");
2951 inform (DECL_SOURCE_LOCATION (var),
2952 "allocation performed here");
2954 *non_constant_p = true;
2955 return t;
2957 DECL_NAME (var) = heap_deleted_identifier;
2958 ctx->global->destroy_value (var);
2959 ctx->global->heap_dealloc_count++;
2960 return void_node;
2962 else if (DECL_NAME (var) == heap_deleted_identifier)
2964 if (!ctx->quiet)
2965 error_at (loc, "deallocation of already deallocated "
2966 "storage");
2967 *non_constant_p = true;
2968 return t;
2971 if (!ctx->quiet)
2972 error_at (loc, "deallocation of storage that was "
2973 "not previously allocated");
2974 *non_constant_p = true;
2975 return t;
2978 /* Allow placement new in std::construct_at, just return the second
2979 argument. */
2980 if (TREE_CODE (t) == CALL_EXPR
2981 && cxx_placement_new_fn (fun)
2982 && is_std_construct_at (ctx->call))
2984 const int nargs = call_expr_nargs (t);
2985 tree arg1 = NULL_TREE;
2986 for (int i = 0; i < nargs; ++i)
2988 tree arg = CALL_EXPR_ARG (t, i);
2989 arg = cxx_eval_constant_expression (ctx, arg, vc_prvalue,
2990 non_constant_p, overflow_p);
2991 if (i == 1)
2992 arg1 = arg;
2993 else
2994 VERIFY_CONSTANT (arg);
2996 gcc_assert (arg1);
2997 return arg1;
2999 else if (cxx_dynamic_cast_fn_p (fun))
3000 return cxx_eval_dynamic_cast_fn (ctx, t, non_constant_p, overflow_p);
3002 if (!ctx->quiet)
3004 if (!lambda_static_thunk_p (fun))
3005 error_at (loc, "call to non-%<constexpr%> function %qD", fun);
3006 explain_invalid_constexpr_fn (fun);
3008 *non_constant_p = true;
3009 return t;
3012 constexpr_ctx new_ctx = *ctx;
3013 if (DECL_CONSTRUCTOR_P (fun) && !ctx->object
3014 && TREE_CODE (t) == AGGR_INIT_EXPR)
3016 /* We want to have an initialization target for an AGGR_INIT_EXPR.
3017 If we don't already have one in CTX, use the AGGR_INIT_EXPR_SLOT. */
3018 new_ctx.object = AGGR_INIT_EXPR_SLOT (t);
3019 tree ctor = new_ctx.ctor = build_constructor (DECL_CONTEXT (fun), NULL);
3020 CONSTRUCTOR_NO_CLEARING (ctor) = true;
3021 ctx->global->put_value (new_ctx.object, ctor);
3022 ctx = &new_ctx;
3025 /* We used to shortcut trivial constructor/op= here, but nowadays
3026 we can only get a trivial function here with -fno-elide-constructors. */
3027 gcc_checking_assert (!trivial_fn_p (fun)
3028 || !flag_elide_constructors
3029 /* We don't elide constructors when processing
3030 a noexcept-expression. */
3031 || cp_noexcept_operand);
3033 bool non_constant_args = false;
3034 new_call.bindings
3035 = cxx_bind_parameters_in_call (ctx, t, fun, non_constant_p,
3036 overflow_p, &non_constant_args);
3038 /* We build up the bindings list before we know whether we already have this
3039 call cached. If we don't end up saving these bindings, ggc_free them when
3040 this function exits. */
3041 class free_bindings
3043 tree *bindings;
3044 public:
3045 free_bindings (tree &b): bindings (&b) { }
3046 ~free_bindings () { if (bindings) ggc_free (*bindings); }
3047 void preserve () { bindings = NULL; }
3048 } fb (new_call.bindings);
3050 if (*non_constant_p)
3051 return t;
3053 /* We can't defer instantiating the function any longer. */
3054 if (!DECL_INITIAL (fun)
3055 && (DECL_TEMPLOID_INSTANTIATION (fun) || DECL_DEFAULTED_FN (fun))
3056 && !uid_sensitive_constexpr_evaluation_p ())
3058 location_t save_loc = input_location;
3059 input_location = loc;
3060 ++function_depth;
3061 if (ctx->manifestly_const_eval == mce_true)
3062 FNDECL_MANIFESTLY_CONST_EVALUATED (fun) = true;
3063 if (DECL_TEMPLOID_INSTANTIATION (fun))
3064 instantiate_decl (fun, /*defer_ok*/false, /*expl_inst*/false);
3065 else
3066 synthesize_method (fun);
3067 --function_depth;
3068 input_location = save_loc;
3071 /* If in direct recursive call, optimize definition search. */
3072 if (ctx && ctx->call && ctx->call->fundef && ctx->call->fundef->decl == fun)
3073 new_call.fundef = ctx->call->fundef;
3074 else
3076 new_call.fundef = retrieve_constexpr_fundef (fun);
3077 if (new_call.fundef == NULL || new_call.fundef->body == NULL
3078 || new_call.fundef->result == error_mark_node
3079 || fun == current_function_decl)
3081 if (!ctx->quiet)
3083 /* We need to check for current_function_decl here in case we're
3084 being called during cp_fold_function, because at that point
3085 DECL_INITIAL is set properly and we have a fundef but we
3086 haven't lowered invisirefs yet (c++/70344). */
3087 if (DECL_INITIAL (fun) == error_mark_node
3088 || fun == current_function_decl)
3089 error_at (loc, "%qD called in a constant expression before its "
3090 "definition is complete", fun);
3091 else if (DECL_INITIAL (fun))
3093 /* The definition of fun was somehow unsuitable. But pretend
3094 that lambda static thunks don't exist. */
3095 if (!lambda_static_thunk_p (fun))
3096 error_at (loc, "%qD called in a constant expression", fun);
3097 explain_invalid_constexpr_fn (fun);
3099 else
3100 error_at (loc, "%qD used before its definition", fun);
3102 *non_constant_p = true;
3103 return t;
3107 depth_ok = push_cx_call_context (t);
3109 /* Remember the object we are constructing or destructing. */
3110 tree new_obj = NULL_TREE;
3111 if (DECL_CONSTRUCTOR_P (fun) || DECL_DESTRUCTOR_P (fun))
3113 /* In a cdtor, it should be the first `this' argument.
3114 At this point it has already been evaluated in the call
3115 to cxx_bind_parameters_in_call. */
3116 new_obj = TREE_VEC_ELT (new_call.bindings, 0);
3117 new_obj = cxx_fold_indirect_ref (ctx, loc, DECL_CONTEXT (fun), new_obj);
3119 if (ctx->call && ctx->call->fundef
3120 && DECL_CONSTRUCTOR_P (ctx->call->fundef->decl))
3122 tree cur_obj = TREE_VEC_ELT (ctx->call->bindings, 0);
3123 STRIP_NOPS (cur_obj);
3124 if (TREE_CODE (cur_obj) == ADDR_EXPR)
3125 cur_obj = TREE_OPERAND (cur_obj, 0);
3126 if (new_obj == cur_obj)
3127 /* We're calling the target constructor of a delegating
3128 constructor, or accessing a base subobject through a
3129 NOP_EXPR as part of a call to a base constructor, so
3130 there is no new (sub)object. */
3131 new_obj = NULL_TREE;
3135 tree result = NULL_TREE;
3137 constexpr_call *entry = NULL;
3138 if (depth_ok && !non_constant_args && ctx->strict)
3140 new_call.hash = constexpr_fundef_hasher::hash (new_call.fundef);
3141 new_call.hash
3142 = iterative_hash_template_arg (new_call.bindings, new_call.hash);
3143 new_call.hash
3144 = iterative_hash_object (ctx->manifestly_const_eval, new_call.hash);
3146 /* If we have seen this call before, we are done. */
3147 maybe_initialize_constexpr_call_table ();
3148 bool insert = depth_ok < constexpr_cache_depth;
3149 constexpr_call **slot
3150 = constexpr_call_table->find_slot (&new_call,
3151 insert ? INSERT : NO_INSERT);
3152 entry = slot ? *slot : NULL;
3153 if (entry == NULL)
3155 /* Only cache up to constexpr_cache_depth to limit memory use. */
3156 if (insert)
3158 /* We need to keep a pointer to the entry, not just the slot, as
3159 the slot can move during evaluation of the body. */
3160 *slot = entry = ggc_alloc<constexpr_call> ();
3161 *entry = new_call;
3162 fb.preserve ();
3165 /* Calls that are in progress have their result set to NULL, so that we
3166 can detect circular dependencies. Now that we only cache up to
3167 constexpr_cache_depth this won't catch circular dependencies that
3168 start deeper, but they'll hit the recursion or ops limit. */
3169 else if (entry->result == NULL)
3171 if (!ctx->quiet)
3172 error ("call has circular dependency");
3173 *non_constant_p = true;
3174 entry->result = result = error_mark_node;
3176 else
3177 result = entry->result;
3180 if (!depth_ok)
3182 if (!ctx->quiet)
3183 error ("%<constexpr%> evaluation depth exceeds maximum of %d (use "
3184 "%<-fconstexpr-depth=%> to increase the maximum)",
3185 max_constexpr_depth);
3186 *non_constant_p = true;
3187 result = error_mark_node;
3189 else
3191 bool cacheable = !!entry;
3192 if (result && result != error_mark_node)
3193 /* OK */;
3194 else if (!DECL_SAVED_TREE (fun))
3196 /* When at_eof >= 3, cgraph has started throwing away
3197 DECL_SAVED_TREE, so fail quietly. FIXME we get here because of
3198 late code generation for VEC_INIT_EXPR, which needs to be
3199 completely reconsidered. */
3200 gcc_assert (at_eof >= 3 && ctx->quiet);
3201 *non_constant_p = true;
3203 else if (tree copy = get_fundef_copy (new_call.fundef))
3205 tree body, parms, res;
3206 releasing_vec ctors;
3208 /* Reuse or create a new unshared copy of this function's body. */
3209 body = TREE_PURPOSE (copy);
3210 parms = TREE_VALUE (copy);
3211 res = TREE_TYPE (copy);
3213 /* Associate the bindings with the remapped parms. */
3214 tree bound = new_call.bindings;
3215 tree remapped = parms;
3216 for (int i = 0; i < TREE_VEC_LENGTH (bound); ++i)
3218 tree arg = TREE_VEC_ELT (bound, i);
3219 if (entry)
3221 /* Unshare args going into the hash table to separate them
3222 from the caller's context, for better GC and to avoid
3223 problems with verify_gimple. */
3224 arg = unshare_expr_without_location (arg);
3225 TREE_VEC_ELT (bound, i) = arg;
3227 /* And then unshare again so the callee doesn't change the
3228 argument values in the hash table. XXX Could we unshare
3229 lazily in cxx_eval_store_expression? */
3230 arg = unshare_constructor (arg);
3231 if (TREE_CODE (arg) == CONSTRUCTOR)
3232 vec_safe_push (ctors, arg);
3234 ctx->global->put_value (remapped, arg);
3235 remapped = DECL_CHAIN (remapped);
3237 for (; remapped; remapped = TREE_CHAIN (remapped))
3238 if (DECL_NAME (remapped) == in_charge_identifier)
3240 /* FIXME destructors unnecessarily have in-charge parameters
3241 even in classes without vbases, map it to 0 for now. */
3242 gcc_assert (!CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fun)));
3243 ctx->global->put_value (remapped, integer_zero_node);
3245 else
3247 gcc_assert (seen_error ());
3248 *non_constant_p = true;
3250 /* Add the RESULT_DECL to the values map, too. */
3251 gcc_assert (!DECL_BY_REFERENCE (res));
3252 ctx->global->put_value (res, NULL_TREE);
3254 /* Remember the current call we're evaluating. */
3255 constexpr_ctx call_ctx = *ctx;
3256 call_ctx.call = &new_call;
3257 unsigned save_heap_alloc_count = ctx->global->heap_vars.length ();
3258 unsigned save_heap_dealloc_count = ctx->global->heap_dealloc_count;
3260 /* Make sure we fold std::is_constant_evaluated to true in an
3261 immediate function. */
3262 if (DECL_IMMEDIATE_FUNCTION_P (fun))
3263 call_ctx.manifestly_const_eval = mce_true;
3265 /* If this is a constexpr destructor, the object's const and volatile
3266 semantics are no longer in effect; see [class.dtor]p5. */
3267 if (new_obj && DECL_DESTRUCTOR_P (fun))
3268 cxx_set_object_constness (ctx, new_obj, /*readonly_p=*/false,
3269 non_constant_p, overflow_p);
3271 /* If this is a constructor, we are beginning the lifetime of the
3272 object we are initializing. */
3273 if (new_obj
3274 && DECL_CONSTRUCTOR_P (fun)
3275 && TREE_CODE (new_obj) == COMPONENT_REF
3276 && TREE_CODE (TREE_TYPE (TREE_OPERAND (new_obj, 0))) == UNION_TYPE)
3278 tree activate = build2 (INIT_EXPR, TREE_TYPE (new_obj),
3279 new_obj,
3280 build_constructor (TREE_TYPE (new_obj),
3281 NULL));
3282 cxx_eval_constant_expression (ctx, activate,
3283 lval, non_constant_p, overflow_p);
3284 ggc_free (activate);
3287 tree jump_target = NULL_TREE;
3288 cxx_eval_constant_expression (&call_ctx, body,
3289 vc_discard, non_constant_p, overflow_p,
3290 &jump_target);
3292 if (DECL_CONSTRUCTOR_P (fun))
3293 /* This can be null for a subobject constructor call, in
3294 which case what we care about is the initialization
3295 side-effects rather than the value. We could get at the
3296 value by evaluating *this, but we don't bother; there's
3297 no need to put such a call in the hash table. */
3298 result = lval ? ctx->object : ctx->ctor;
3299 else if (VOID_TYPE_P (TREE_TYPE (res)))
3300 result = void_node;
3301 else
3303 result = ctx->global->get_value (res);
3304 if (result == NULL_TREE && !*non_constant_p
3305 && !DECL_DESTRUCTOR_P (fun))
3307 if (!ctx->quiet)
3308 error ("%<constexpr%> call flows off the end "
3309 "of the function");
3310 *non_constant_p = true;
3314 /* At this point, the object's constructor will have run, so
3315 the object is no longer under construction, and its possible
3316 'const' semantics now apply. Make a note of this fact by
3317 marking the CONSTRUCTOR TREE_READONLY. */
3318 if (new_obj && DECL_CONSTRUCTOR_P (fun))
3319 cxx_set_object_constness (ctx, new_obj, /*readonly_p=*/true,
3320 non_constant_p, overflow_p);
3322 /* Remove the parms/result from the values map. */
3323 destroy_value_checked (ctx, res, non_constant_p);
3324 for (tree parm = parms; parm; parm = TREE_CHAIN (parm))
3325 destroy_value_checked (ctx, parm, non_constant_p);
3327 /* Free any parameter CONSTRUCTORs we aren't returning directly. */
3328 while (!ctors->is_empty ())
3330 tree c = ctors->pop ();
3331 if (c != result)
3332 free_constructor (c);
3335 /* Make the unshared function copy we used available for re-use. */
3336 save_fundef_copy (fun, copy);
3338 /* If the call allocated some heap object that hasn't been
3339 deallocated during the call, or if it deallocated some heap
3340 object it has not allocated, the call isn't really stateless
3341 for the constexpr evaluation and should not be cached.
3342 It is fine if the call allocates something and deallocates it
3343 too. */
3344 if (cacheable
3345 && (save_heap_alloc_count != ctx->global->heap_vars.length ()
3346 || (save_heap_dealloc_count
3347 != ctx->global->heap_dealloc_count)))
3349 tree heap_var;
3350 unsigned int i;
3351 if ((ctx->global->heap_vars.length ()
3352 - ctx->global->heap_dealloc_count)
3353 != save_heap_alloc_count - save_heap_dealloc_count)
3354 cacheable = false;
3355 else
3356 FOR_EACH_VEC_ELT_FROM (ctx->global->heap_vars, i, heap_var,
3357 save_heap_alloc_count)
3358 if (DECL_NAME (heap_var) != heap_deleted_identifier)
3360 cacheable = false;
3361 break;
3365 /* Rewrite all occurrences of the function's RESULT_DECL with the
3366 current object under construction. */
3367 if (!*non_constant_p && ctx->object
3368 && CLASS_TYPE_P (TREE_TYPE (res))
3369 && !is_empty_class (TREE_TYPE (res)))
3370 if (replace_decl (&result, res, ctx->object))
3371 cacheable = false;
3373 /* Only cache a permitted result of a constant expression. */
3374 if (cacheable && !reduced_constant_expression_p (result))
3375 cacheable = false;
3377 else
3378 /* Couldn't get a function copy to evaluate. */
3379 *non_constant_p = true;
3381 if (result == error_mark_node)
3382 *non_constant_p = true;
3383 if (*non_constant_p || *overflow_p)
3384 result = error_mark_node;
3385 else if (!result)
3386 result = void_node;
3387 if (entry)
3388 entry->result = cacheable ? result : error_mark_node;
3391 /* The result of a constexpr function must be completely initialized.
3393 However, in C++20, a constexpr constructor doesn't necessarily have
3394 to initialize all the fields, so we don't clear CONSTRUCTOR_NO_CLEARING
3395 in order to detect reading an unitialized object in constexpr instead
3396 of value-initializing it. (reduced_constant_expression_p is expected to
3397 take care of clearing the flag.) */
3398 if (TREE_CODE (result) == CONSTRUCTOR
3399 && (cxx_dialect < cxx20
3400 || !DECL_CONSTRUCTOR_P (fun)))
3401 clear_no_implicit_zero (result);
3403 pop_cx_call_context ();
3404 return result;
3407 /* Return true if T is a valid constant initializer. If a CONSTRUCTOR
3408 initializes all the members, the CONSTRUCTOR_NO_CLEARING flag will be
3409 cleared.
3410 FIXME speed this up, it's taking 16% of compile time on sieve testcase. */
3412 bool
3413 reduced_constant_expression_p (tree t)
3415 if (t == NULL_TREE)
3416 return false;
3418 switch (TREE_CODE (t))
3420 case PTRMEM_CST:
3421 /* Even if we can't lower this yet, it's constant. */
3422 return true;
3424 case CONSTRUCTOR:
3425 /* And we need to handle PTRMEM_CST wrapped in a CONSTRUCTOR. */
3426 tree field;
3427 if (!AGGREGATE_TYPE_P (TREE_TYPE (t)))
3428 /* A constant vector would be folded to VECTOR_CST.
3429 A CONSTRUCTOR of scalar type means uninitialized. */
3430 return false;
3431 if (CONSTRUCTOR_NO_CLEARING (t))
3433 if (TREE_CODE (TREE_TYPE (t)) == ARRAY_TYPE)
3435 /* There must be a valid constant initializer at every array
3436 index. */
3437 tree min = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (t)));
3438 tree max = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (t)));
3439 tree cursor = min;
3440 for (auto &e: CONSTRUCTOR_ELTS (t))
3442 if (!reduced_constant_expression_p (e.value))
3443 return false;
3444 if (array_index_cmp (cursor, e.index) != 0)
3445 return false;
3446 if (TREE_CODE (e.index) == RANGE_EXPR)
3447 cursor = TREE_OPERAND (e.index, 1);
3448 cursor = int_const_binop (PLUS_EXPR, cursor, size_one_node);
3450 if (find_array_ctor_elt (t, max) == -1)
3451 return false;
3452 goto ok;
3454 else if (cxx_dialect >= cxx20
3455 && TREE_CODE (TREE_TYPE (t)) == UNION_TYPE)
3457 if (CONSTRUCTOR_NELTS (t) == 0)
3458 /* An initialized union has a constructor element. */
3459 return false;
3460 /* And it only initializes one member. */
3461 field = NULL_TREE;
3463 else
3464 field = next_subobject_field (TYPE_FIELDS (TREE_TYPE (t)));
3466 else
3467 field = NULL_TREE;
3468 for (auto &e: CONSTRUCTOR_ELTS (t))
3470 /* If VAL is null, we're in the middle of initializing this
3471 element. */
3472 if (!reduced_constant_expression_p (e.value))
3473 return false;
3474 /* We want to remove initializers for empty fields in a struct to
3475 avoid confusing output_constructor. */
3476 if (is_empty_field (e.index)
3477 && TREE_CODE (TREE_TYPE (t)) == RECORD_TYPE)
3478 return false;
3479 /* Check for non-empty fields between initialized fields when
3480 CONSTRUCTOR_NO_CLEARING. */
3481 for (; field && e.index != field;
3482 field = next_subobject_field (DECL_CHAIN (field)))
3483 if (!is_really_empty_class (TREE_TYPE (field),
3484 /*ignore_vptr*/false))
3485 return false;
3486 if (field)
3487 field = next_subobject_field (DECL_CHAIN (field));
3489 /* There could be a non-empty field at the end. */
3490 for (; field; field = next_subobject_field (DECL_CHAIN (field)))
3491 if (!is_really_empty_class (TREE_TYPE (field), /*ignore_vptr*/false))
3492 return false;
3494 if (CONSTRUCTOR_NO_CLEARING (t))
3495 /* All the fields are initialized. */
3496 CONSTRUCTOR_NO_CLEARING (t) = false;
3497 return true;
3499 default:
3500 /* FIXME are we calling this too much? */
3501 return initializer_constant_valid_p (t, TREE_TYPE (t)) != NULL_TREE;
3505 /* *TP was not deemed constant by reduced_constant_expression_p. Explain
3506 why and suggest what could be done about it. */
3508 static tree
3509 verify_constant_explain_r (tree *tp, int *walk_subtrees, void *)
3511 bool ref_p = false;
3513 /* No need to look into types or unevaluated operands. */
3514 if (TYPE_P (*tp) || unevaluated_p (TREE_CODE (*tp)))
3516 *walk_subtrees = false;
3517 return NULL_TREE;
3520 switch (TREE_CODE (*tp))
3522 CASE_CONVERT:
3523 if (TREE_CODE (TREE_OPERAND (*tp, 0)) != ADDR_EXPR)
3524 break;
3525 ref_p = TYPE_REF_P (TREE_TYPE (*tp));
3526 *tp = TREE_OPERAND (*tp, 0);
3527 gcc_fallthrough ();
3528 case ADDR_EXPR:
3530 tree op = TREE_OPERAND (*tp, 0);
3531 if (VAR_P (op)
3532 && DECL_DECLARED_CONSTEXPR_P (op)
3533 && !TREE_STATIC (op)
3534 /* ??? We should also say something about temporaries. */
3535 && !DECL_ARTIFICIAL (op))
3537 if (ref_p)
3538 inform (location_of (*tp), "reference to %qD is not a constant "
3539 "expression", op);
3540 else
3541 inform (location_of (*tp), "pointer to %qD is not a constant "
3542 "expression", op);
3543 const location_t op_loc = DECL_SOURCE_LOCATION (op);
3544 rich_location richloc (line_table, op_loc);
3545 richloc.add_fixit_insert_before (op_loc, "static ");
3546 inform (&richloc,
3547 "address of non-static constexpr variable %qD may differ on "
3548 "each invocation of the enclosing function; add %<static%> "
3549 "to give it a constant address", op);
3551 break;
3553 default:
3554 break;
3557 return NULL_TREE;
3560 /* Some expressions may have constant operands but are not constant
3561 themselves, such as 1/0. Call this function to check for that
3562 condition.
3564 We only call this in places that require an arithmetic constant, not in
3565 places where we might have a non-constant expression that can be a
3566 component of a constant expression, such as the address of a constexpr
3567 variable that might be dereferenced later. */
3569 static bool
3570 verify_constant (tree t, bool allow_non_constant, bool *non_constant_p,
3571 bool *overflow_p)
3573 if (!*non_constant_p && !reduced_constant_expression_p (t)
3574 && t != void_node)
3576 if (!allow_non_constant)
3578 auto_diagnostic_group d;
3579 error_at (cp_expr_loc_or_input_loc (t),
3580 "%q+E is not a constant expression", t);
3581 cp_walk_tree_without_duplicates (&t, verify_constant_explain_r,
3582 nullptr);
3584 *non_constant_p = true;
3586 if (TREE_OVERFLOW_P (t))
3588 if (!allow_non_constant)
3590 permerror (input_location, "overflow in constant expression");
3591 /* If we're being permissive (and are in an enforcing
3592 context), ignore the overflow. */
3593 if (flag_permissive)
3594 return *non_constant_p;
3596 *overflow_p = true;
3598 return *non_constant_p;
3601 /* Check whether the shift operation with code CODE and type TYPE on LHS
3602 and RHS is undefined. If it is, give an error with an explanation,
3603 and return true; return false otherwise. */
3605 static bool
3606 cxx_eval_check_shift_p (location_t loc, const constexpr_ctx *ctx,
3607 enum tree_code code, tree type, tree lhs, tree rhs)
3609 if ((code != LSHIFT_EXPR && code != RSHIFT_EXPR)
3610 || TREE_CODE (lhs) != INTEGER_CST
3611 || TREE_CODE (rhs) != INTEGER_CST)
3612 return false;
3614 tree lhstype = TREE_TYPE (lhs);
3615 unsigned HOST_WIDE_INT uprec = TYPE_PRECISION (TREE_TYPE (lhs));
3617 /* [expr.shift] The behavior is undefined if the right operand
3618 is negative, or greater than or equal to the length in bits
3619 of the promoted left operand. */
3620 if (tree_int_cst_sgn (rhs) == -1)
3622 if (!ctx->quiet)
3623 permerror (loc, "right operand of shift expression %q+E is negative",
3624 build2_loc (loc, code, type, lhs, rhs));
3625 return (!flag_permissive || ctx->quiet);
3627 if (compare_tree_int (rhs, uprec) >= 0)
3629 if (!ctx->quiet)
3630 permerror (loc, "right operand of shift expression %q+E is greater "
3631 "than or equal to the precision %wu of the left operand",
3632 build2_loc (loc, code, type, lhs, rhs), uprec);
3633 return (!flag_permissive || ctx->quiet);
3636 /* The value of E1 << E2 is E1 left-shifted E2 bit positions; [...]
3637 if E1 has a signed type and non-negative value, and E1x2^E2 is
3638 representable in the corresponding unsigned type of the result type,
3639 then that value, converted to the result type, is the resulting value;
3640 otherwise, the behavior is undefined.
3641 For C++20:
3642 The value of E1 << E2 is the unique value congruent to E1 x 2^E2 modulo
3643 2^N, where N is the range exponent of the type of the result. */
3644 if (code == LSHIFT_EXPR
3645 && !TYPE_OVERFLOW_WRAPS (lhstype)
3646 && cxx_dialect >= cxx11
3647 && cxx_dialect < cxx20)
3649 if (tree_int_cst_sgn (lhs) == -1)
3651 if (!ctx->quiet)
3652 permerror (loc,
3653 "left operand of shift expression %q+E is negative",
3654 build2_loc (loc, code, type, lhs, rhs));
3655 return (!flag_permissive || ctx->quiet);
3657 /* For signed x << y the following:
3658 (unsigned) x >> ((prec (lhs) - 1) - y)
3659 if > 1, is undefined. The right-hand side of this formula
3660 is the highest bit of the LHS that can be set (starting from 0),
3661 so that the shift doesn't overflow. We then right-shift the LHS
3662 to see whether any other bit is set making the original shift
3663 undefined -- the result is not representable in the corresponding
3664 unsigned type. */
3665 tree t = build_int_cst (unsigned_type_node, uprec - 1);
3666 t = fold_build2 (MINUS_EXPR, unsigned_type_node, t, rhs);
3667 tree ulhs = fold_convert (unsigned_type_for (lhstype), lhs);
3668 t = fold_build2 (RSHIFT_EXPR, TREE_TYPE (ulhs), ulhs, t);
3669 if (tree_int_cst_lt (integer_one_node, t))
3671 if (!ctx->quiet)
3672 permerror (loc, "shift expression %q+E overflows",
3673 build2_loc (loc, code, type, lhs, rhs));
3674 return (!flag_permissive || ctx->quiet);
3677 return false;
3680 /* Subroutine of cxx_eval_constant_expression.
3681 Attempt to reduce the unary expression tree T to a compile time value.
3682 If successful, return the value. Otherwise issue a diagnostic
3683 and return error_mark_node. */
3685 static tree
3686 cxx_eval_unary_expression (const constexpr_ctx *ctx, tree t,
3687 bool /*lval*/,
3688 bool *non_constant_p, bool *overflow_p)
3690 tree r;
3691 tree orig_arg = TREE_OPERAND (t, 0);
3692 tree arg = cxx_eval_constant_expression (ctx, orig_arg, vc_prvalue,
3693 non_constant_p, overflow_p);
3694 VERIFY_CONSTANT (arg);
3695 location_t loc = EXPR_LOCATION (t);
3696 enum tree_code code = TREE_CODE (t);
3697 tree type = TREE_TYPE (t);
3698 r = fold_unary_loc (loc, code, type, arg);
3699 if (r == NULL_TREE)
3701 if (arg == orig_arg)
3702 r = t;
3703 else
3704 r = build1_loc (loc, code, type, arg);
3706 VERIFY_CONSTANT (r);
3707 return r;
3710 /* Helper function for cxx_eval_binary_expression. Try to optimize
3711 original POINTER_PLUS_EXPR T, LHS p+ RHS, return NULL_TREE if the
3712 generic folding should be used. */
3714 static tree
3715 cxx_fold_pointer_plus_expression (const constexpr_ctx *ctx, tree t,
3716 tree lhs, tree rhs, bool *non_constant_p,
3717 bool *overflow_p)
3719 STRIP_NOPS (lhs);
3720 if (TREE_CODE (lhs) != ADDR_EXPR)
3721 return NULL_TREE;
3723 lhs = TREE_OPERAND (lhs, 0);
3725 /* &A[i] p+ j => &A[i + j] */
3726 if (TREE_CODE (lhs) == ARRAY_REF
3727 && TREE_CODE (TREE_OPERAND (lhs, 1)) == INTEGER_CST
3728 && TREE_CODE (rhs) == INTEGER_CST
3729 && TYPE_SIZE_UNIT (TREE_TYPE (lhs))
3730 && TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (lhs))) == INTEGER_CST)
3732 tree orig_type = TREE_TYPE (t);
3733 location_t loc = EXPR_LOCATION (t);
3734 tree type = TREE_TYPE (lhs);
3736 t = fold_convert_loc (loc, ssizetype, TREE_OPERAND (lhs, 1));
3737 tree nelts = array_type_nelts_top (TREE_TYPE (TREE_OPERAND (lhs, 0)));
3738 nelts = cxx_eval_constant_expression (ctx, nelts, vc_prvalue,
3739 non_constant_p, overflow_p);
3740 if (*non_constant_p)
3741 return NULL_TREE;
3742 /* Don't fold an out-of-bound access. */
3743 if (!tree_int_cst_le (t, nelts))
3744 return NULL_TREE;
3745 rhs = cp_fold_convert (ssizetype, rhs);
3746 /* Don't fold if rhs can't be divided exactly by TYPE_SIZE_UNIT.
3747 constexpr int A[1]; ... (char *)&A[0] + 1 */
3748 if (!integer_zerop (fold_build2_loc (loc, TRUNC_MOD_EXPR, sizetype,
3749 rhs, TYPE_SIZE_UNIT (type))))
3750 return NULL_TREE;
3751 /* Make sure to treat the second operand of POINTER_PLUS_EXPR
3752 as signed. */
3753 rhs = fold_build2_loc (loc, EXACT_DIV_EXPR, ssizetype, rhs,
3754 TYPE_SIZE_UNIT (type));
3755 t = size_binop_loc (loc, PLUS_EXPR, rhs, t);
3756 t = build4_loc (loc, ARRAY_REF, type, TREE_OPERAND (lhs, 0),
3757 t, NULL_TREE, NULL_TREE);
3758 t = cp_build_addr_expr (t, tf_warning_or_error);
3759 t = cp_fold_convert (orig_type, t);
3760 return cxx_eval_constant_expression (ctx, t, vc_prvalue,
3761 non_constant_p, overflow_p);
3764 return NULL_TREE;
3767 /* Try to fold expressions like
3768 (struct S *) (&a[0].D.2378 + 12)
3769 into
3770 &MEM <struct T> [(void *)&a + 12B]
3771 This is something normally done by gimple_fold_stmt_to_constant_1
3772 on GIMPLE, but is undesirable on GENERIC if we are e.g. going to
3773 dereference the address because some details are lost.
3774 For pointer comparisons we want such folding though so that
3775 match.pd address_compare optimization works. */
3777 static tree
3778 cxx_maybe_fold_addr_pointer_plus (tree t)
3780 while (CONVERT_EXPR_P (t)
3781 && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (t, 0))))
3782 t = TREE_OPERAND (t, 0);
3783 if (TREE_CODE (t) != POINTER_PLUS_EXPR)
3784 return NULL_TREE;
3785 tree op0 = TREE_OPERAND (t, 0);
3786 tree op1 = TREE_OPERAND (t, 1);
3787 if (TREE_CODE (op1) != INTEGER_CST)
3788 return NULL_TREE;
3789 while (CONVERT_EXPR_P (op0)
3790 && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (op0, 0))))
3791 op0 = TREE_OPERAND (op0, 0);
3792 if (TREE_CODE (op0) != ADDR_EXPR)
3793 return NULL_TREE;
3794 op1 = fold_convert (ptr_type_node, op1);
3795 tree r = fold_build2 (MEM_REF, TREE_TYPE (TREE_TYPE (op0)), op0, op1);
3796 return build1_loc (EXPR_LOCATION (t), ADDR_EXPR, TREE_TYPE (op0), r);
3799 /* Subroutine of cxx_eval_constant_expression.
3800 Like cxx_eval_unary_expression, except for binary expressions. */
3802 static tree
3803 cxx_eval_binary_expression (const constexpr_ctx *ctx, tree t,
3804 value_cat lval,
3805 bool *non_constant_p, bool *overflow_p)
3807 tree r = NULL_TREE;
3808 tree orig_lhs = TREE_OPERAND (t, 0);
3809 tree orig_rhs = TREE_OPERAND (t, 1);
3810 tree lhs, rhs;
3811 lhs = cxx_eval_constant_expression (ctx, orig_lhs, vc_prvalue,
3812 non_constant_p, overflow_p);
3813 /* Don't VERIFY_CONSTANT here, it's unnecessary and will break pointer
3814 subtraction. */
3815 if (*non_constant_p)
3816 return t;
3817 rhs = cxx_eval_constant_expression (ctx, orig_rhs, vc_prvalue,
3818 non_constant_p, overflow_p);
3819 if (*non_constant_p)
3820 return t;
3822 location_t loc = EXPR_LOCATION (t);
3823 enum tree_code code = TREE_CODE (t);
3824 tree type = TREE_TYPE (t);
3826 if (code == EQ_EXPR || code == NE_EXPR)
3828 bool is_code_eq = (code == EQ_EXPR);
3830 if (TREE_CODE (lhs) == PTRMEM_CST
3831 && TREE_CODE (rhs) == PTRMEM_CST)
3833 tree lmem = PTRMEM_CST_MEMBER (lhs);
3834 tree rmem = PTRMEM_CST_MEMBER (rhs);
3835 bool eq;
3836 if (TREE_CODE (lmem) == TREE_CODE (rmem)
3837 && TREE_CODE (lmem) == FIELD_DECL
3838 && TREE_CODE (DECL_CONTEXT (lmem)) == UNION_TYPE
3839 && same_type_p (DECL_CONTEXT (lmem),
3840 DECL_CONTEXT (rmem)))
3841 /* If both refer to (possibly different) members of the same union
3842 (12.3), they compare equal. */
3843 eq = true;
3844 else
3845 eq = cp_tree_equal (lhs, rhs);
3846 r = constant_boolean_node (eq == is_code_eq, type);
3848 else if ((TREE_CODE (lhs) == PTRMEM_CST
3849 || TREE_CODE (rhs) == PTRMEM_CST)
3850 && (null_member_pointer_value_p (lhs)
3851 || null_member_pointer_value_p (rhs)))
3852 r = constant_boolean_node (!is_code_eq, type);
3853 else if (TREE_CODE (lhs) == PTRMEM_CST)
3854 lhs = cplus_expand_constant (lhs);
3855 else if (TREE_CODE (rhs) == PTRMEM_CST)
3856 rhs = cplus_expand_constant (rhs);
3858 if (r == NULL_TREE
3859 && TREE_CODE_CLASS (code) == tcc_comparison
3860 && POINTER_TYPE_P (TREE_TYPE (lhs)))
3862 if (tree lhso = cxx_maybe_fold_addr_pointer_plus (lhs))
3863 lhs = fold_convert (TREE_TYPE (lhs), lhso);
3864 if (tree rhso = cxx_maybe_fold_addr_pointer_plus (rhs))
3865 rhs = fold_convert (TREE_TYPE (rhs), rhso);
3867 if (code == POINTER_PLUS_EXPR && !*non_constant_p
3868 && integer_zerop (lhs) && !integer_zerop (rhs))
3870 if (!ctx->quiet)
3871 error ("arithmetic involving a null pointer in %qE", lhs);
3872 *non_constant_p = true;
3873 return t;
3875 else if (code == POINTER_PLUS_EXPR)
3876 r = cxx_fold_pointer_plus_expression (ctx, t, lhs, rhs, non_constant_p,
3877 overflow_p);
3878 else if (code == SPACESHIP_EXPR)
3880 r = genericize_spaceship (loc, type, lhs, rhs);
3881 return cxx_eval_constant_expression (ctx, r, lval, non_constant_p,
3882 overflow_p);
3885 if (r == NULL_TREE)
3887 if (ctx->manifestly_const_eval == mce_true
3888 && (flag_constexpr_fp_except
3889 || TREE_CODE (type) != REAL_TYPE))
3891 auto ofcc = make_temp_override (folding_cxx_constexpr, true);
3892 r = fold_binary_initializer_loc (loc, code, type, lhs, rhs);
3894 else
3895 r = fold_binary_loc (loc, code, type, lhs, rhs);
3898 if (r == NULL_TREE
3899 && (code == LSHIFT_EXPR || code == RSHIFT_EXPR)
3900 && TREE_CODE (lhs) == INTEGER_CST
3901 && TREE_CODE (rhs) == INTEGER_CST
3902 && wi::neg_p (wi::to_wide (rhs)))
3904 /* For diagnostics and -fpermissive emulate previous behavior of
3905 handling shifts by negative amount. */
3906 tree nrhs = const_unop (NEGATE_EXPR, TREE_TYPE (rhs), rhs);
3907 if (nrhs)
3908 r = fold_binary_loc (loc,
3909 code == LSHIFT_EXPR ? RSHIFT_EXPR : LSHIFT_EXPR,
3910 type, lhs, nrhs);
3913 if (r == NULL_TREE)
3915 if (lhs == orig_lhs && rhs == orig_rhs)
3916 r = t;
3917 else
3918 r = build2_loc (loc, code, type, lhs, rhs);
3920 else if (cxx_eval_check_shift_p (loc, ctx, code, type, lhs, rhs))
3921 *non_constant_p = true;
3922 /* Don't VERIFY_CONSTANT if this might be dealing with a pointer to
3923 a local array in a constexpr function. */
3924 bool ptr = INDIRECT_TYPE_P (TREE_TYPE (lhs));
3925 if (!ptr)
3926 VERIFY_CONSTANT (r);
3927 return r;
3930 /* Subroutine of cxx_eval_constant_expression.
3931 Attempt to evaluate condition expressions. */
3933 static tree
3934 cxx_eval_conditional_expression (const constexpr_ctx *ctx, tree t,
3935 value_cat lval,
3936 bool *non_constant_p, bool *overflow_p,
3937 tree *jump_target)
3939 tree val = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
3940 vc_prvalue,
3941 non_constant_p, overflow_p);
3942 VERIFY_CONSTANT (val);
3943 if (TREE_CODE (t) == IF_STMT && IF_STMT_CONSTEVAL_P (t))
3945 /* Evaluate the condition as if it was
3946 if (__builtin_is_constant_evaluated ()), i.e. defer it if not
3947 ctx->manifestly_const_eval (as sometimes we try to constant evaluate
3948 without manifestly_const_eval even expressions or parts thereof which
3949 will later be manifestly const_eval evaluated), otherwise fold it to
3950 true. */
3951 if (ctx->manifestly_const_eval == mce_unknown)
3953 *non_constant_p = true;
3954 return t;
3956 val = constant_boolean_node (ctx->manifestly_const_eval == mce_true,
3957 boolean_type_node);
3959 /* Don't VERIFY_CONSTANT the other operands. */
3960 const bool zero_p = integer_zerop (val);
3961 if (zero_p)
3962 val = TREE_OPERAND (t, 2);
3963 else
3964 val = TREE_OPERAND (t, 1);
3965 if (TREE_CODE (t) == IF_STMT && !val)
3966 val = void_node;
3968 /* P2564: a subexpression of a manifestly constant-evaluated expression
3969 or conversion is an immediate function context. */
3970 if (ctx->manifestly_const_eval != mce_true
3971 && !in_immediate_context ()
3972 && cp_fold_immediate (&TREE_OPERAND (t, zero_p ? 1 : 2),
3973 ctx->manifestly_const_eval))
3975 *non_constant_p = true;
3976 return t;
3979 /* A TARGET_EXPR may be nested inside another TARGET_EXPR, but still
3980 serve as the initializer for the same object as the outer TARGET_EXPR,
3981 as in
3982 A a = true ? A{} : A{};
3983 so strip the inner TARGET_EXPR so we don't materialize a temporary. */
3984 if (TREE_CODE (val) == TARGET_EXPR)
3985 val = TARGET_EXPR_INITIAL (val);
3986 return cxx_eval_constant_expression (ctx, val, lval, non_constant_p,
3987 overflow_p, jump_target);
3990 /* Subroutine of cxx_eval_constant_expression.
3991 Attempt to evaluate vector condition expressions. Unlike
3992 cxx_eval_conditional_expression, VEC_COND_EXPR acts like a normal
3993 ternary arithmetics operation, where all 3 arguments have to be
3994 evaluated as constants and then folding computes the result from
3995 them. */
3997 static tree
3998 cxx_eval_vector_conditional_expression (const constexpr_ctx *ctx, tree t,
3999 bool *non_constant_p, bool *overflow_p)
4001 tree arg1 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
4002 vc_prvalue,
4003 non_constant_p, overflow_p);
4004 VERIFY_CONSTANT (arg1);
4005 tree arg2 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
4006 vc_prvalue,
4007 non_constant_p, overflow_p);
4008 VERIFY_CONSTANT (arg2);
4009 tree arg3 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 2),
4010 vc_prvalue,
4011 non_constant_p, overflow_p);
4012 VERIFY_CONSTANT (arg3);
4013 location_t loc = EXPR_LOCATION (t);
4014 tree type = TREE_TYPE (t);
4015 tree r = fold_ternary_loc (loc, VEC_COND_EXPR, type, arg1, arg2, arg3);
4016 if (r == NULL_TREE)
4018 if (arg1 == TREE_OPERAND (t, 0)
4019 && arg2 == TREE_OPERAND (t, 1)
4020 && arg3 == TREE_OPERAND (t, 2))
4021 r = t;
4022 else
4023 r = build3_loc (loc, VEC_COND_EXPR, type, arg1, arg2, arg3);
4025 VERIFY_CONSTANT (r);
4026 return r;
4029 /* Returns less than, equal to, or greater than zero if KEY is found to be
4030 less than, to match, or to be greater than the constructor_elt's INDEX. */
4032 static int
4033 array_index_cmp (tree key, tree index)
4035 gcc_assert (TREE_CODE (key) == INTEGER_CST);
4037 switch (TREE_CODE (index))
4039 case INTEGER_CST:
4040 return tree_int_cst_compare (key, index);
4041 case RANGE_EXPR:
4043 tree lo = TREE_OPERAND (index, 0);
4044 tree hi = TREE_OPERAND (index, 1);
4045 if (tree_int_cst_lt (key, lo))
4046 return -1;
4047 else if (tree_int_cst_lt (hi, key))
4048 return 1;
4049 else
4050 return 0;
4052 default:
4053 gcc_unreachable ();
4057 /* Returns the index of the constructor_elt of ARY which matches DINDEX, or -1
4058 if none. If INSERT is true, insert a matching element rather than fail. */
4060 static HOST_WIDE_INT
4061 find_array_ctor_elt (tree ary, tree dindex, bool insert)
4063 if (tree_int_cst_sgn (dindex) < 0)
4064 return -1;
4066 unsigned HOST_WIDE_INT i = tree_to_uhwi (dindex);
4067 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ary);
4068 unsigned HOST_WIDE_INT len = vec_safe_length (elts);
4070 unsigned HOST_WIDE_INT end = len;
4071 unsigned HOST_WIDE_INT begin = 0;
4073 /* If the last element of the CONSTRUCTOR has its own index, we can assume
4074 that the same is true of the other elements and index directly. */
4075 if (end > 0)
4077 tree cindex = (*elts)[end - 1].index;
4078 if (cindex == NULL_TREE)
4080 /* Verify that if the last index is missing, all indexes
4081 are missing. */
4082 if (flag_checking)
4083 for (unsigned int j = 0; j < len - 1; ++j)
4084 gcc_assert ((*elts)[j].index == NULL_TREE);
4085 if (i < end)
4086 return i;
4087 else
4089 begin = end;
4090 if (i == end)
4091 /* If the element is to be added right at the end,
4092 make sure it is added with cleared index too. */
4093 dindex = NULL_TREE;
4094 else if (insert)
4095 /* Otherwise, in order not to break the assumption
4096 that CONSTRUCTOR either has all indexes or none,
4097 we need to add indexes to all elements. */
4098 for (unsigned int j = 0; j < len; ++j)
4099 (*elts)[j].index = build_int_cst (TREE_TYPE (dindex), j);
4102 else if (TREE_CODE (cindex) == INTEGER_CST
4103 && compare_tree_int (cindex, end - 1) == 0)
4105 if (i < end)
4106 return i;
4107 else
4108 begin = end;
4112 /* Otherwise, find a matching index by means of a binary search. */
4113 while (begin != end)
4115 unsigned HOST_WIDE_INT middle = (begin + end) / 2;
4116 constructor_elt &elt = (*elts)[middle];
4117 tree idx = elt.index;
4119 int cmp = array_index_cmp (dindex, idx);
4120 if (cmp < 0)
4121 end = middle;
4122 else if (cmp > 0)
4123 begin = middle + 1;
4124 else
4126 if (insert && TREE_CODE (idx) == RANGE_EXPR)
4128 /* We need to split the range. */
4129 constructor_elt e;
4130 tree lo = TREE_OPERAND (idx, 0);
4131 tree hi = TREE_OPERAND (idx, 1);
4132 tree value = elt.value;
4133 dindex = fold_convert (sizetype, dindex);
4134 if (tree_int_cst_lt (lo, dindex))
4136 /* There are still some lower elts; shorten the range. */
4137 tree new_hi = int_const_binop (MINUS_EXPR, dindex,
4138 size_one_node);
4139 if (tree_int_cst_equal (lo, new_hi))
4140 /* Only one element left, no longer a range. */
4141 elt.index = lo;
4142 else
4143 TREE_OPERAND (idx, 1) = new_hi;
4144 /* Append the element we want to insert. */
4145 ++middle;
4146 e.index = dindex;
4147 e.value = unshare_constructor (value);
4148 vec_safe_insert (CONSTRUCTOR_ELTS (ary), middle, e);
4150 else
4151 /* No lower elts, the range elt is now ours. */
4152 elt.index = dindex;
4154 if (tree_int_cst_lt (dindex, hi))
4156 /* There are still some higher elts; append a range. */
4157 tree new_lo = int_const_binop (PLUS_EXPR, dindex,
4158 size_one_node);
4159 if (tree_int_cst_equal (new_lo, hi))
4160 e.index = hi;
4161 else
4162 e.index = build2 (RANGE_EXPR, sizetype, new_lo, hi);
4163 e.value = unshare_constructor (value);
4164 vec_safe_insert (CONSTRUCTOR_ELTS (ary), middle + 1, e);
4167 return middle;
4171 if (insert)
4173 constructor_elt e = { dindex, NULL_TREE };
4174 vec_safe_insert (CONSTRUCTOR_ELTS (ary), end, e);
4175 return end;
4178 return -1;
4181 /* Return a pointer to the constructor_elt of CTOR which matches INDEX. If no
4182 matching constructor_elt exists, then add one to CTOR.
4184 As an optimization, if POS_HINT is non-negative then it is used as a guess
4185 for the (integer) index of the matching constructor_elt within CTOR. */
4187 static constructor_elt *
4188 get_or_insert_ctor_field (tree ctor, tree index, int pos_hint = -1)
4190 /* Check the hint first. */
4191 if (pos_hint >= 0 && (unsigned)pos_hint < CONSTRUCTOR_NELTS (ctor)
4192 && CONSTRUCTOR_ELT (ctor, pos_hint)->index == index)
4193 return CONSTRUCTOR_ELT (ctor, pos_hint);
4195 tree type = TREE_TYPE (ctor);
4196 if (TREE_CODE (type) == VECTOR_TYPE && index == NULL_TREE)
4198 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (ctor), index, NULL_TREE);
4199 return &CONSTRUCTOR_ELTS (ctor)->last();
4201 else if (TREE_CODE (type) == ARRAY_TYPE || TREE_CODE (type) == VECTOR_TYPE)
4203 if (TREE_CODE (index) == RANGE_EXPR)
4205 /* Support for RANGE_EXPR index lookups is currently limited to
4206 accessing an existing element via POS_HINT, or appending a new
4207 element to the end of CTOR. ??? Support for other access
4208 patterns may also be needed. */
4209 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ctor);
4210 if (vec_safe_length (elts))
4212 tree lo = TREE_OPERAND (index, 0);
4213 gcc_assert (array_index_cmp (elts->last().index, lo) < 0);
4215 CONSTRUCTOR_APPEND_ELT (elts, index, NULL_TREE);
4216 return &elts->last();
4219 HOST_WIDE_INT i = find_array_ctor_elt (ctor, index, /*insert*/true);
4220 gcc_assert (i >= 0);
4221 constructor_elt *cep = CONSTRUCTOR_ELT (ctor, i);
4222 gcc_assert (cep->index == NULL_TREE
4223 || TREE_CODE (cep->index) != RANGE_EXPR);
4224 return cep;
4226 else
4228 gcc_assert (TREE_CODE (index) == FIELD_DECL
4229 && (same_type_ignoring_top_level_qualifiers_p
4230 (DECL_CONTEXT (index), TREE_TYPE (ctor))));
4232 /* We must keep the CONSTRUCTOR's ELTS in FIELD order.
4233 Usually we meet initializers in that order, but it is
4234 possible for base types to be placed not in program
4235 order. */
4236 tree fields = TYPE_FIELDS (DECL_CONTEXT (index));
4237 unsigned HOST_WIDE_INT idx = 0;
4238 constructor_elt *cep = NULL;
4240 /* Check if we're changing the active member of a union. */
4241 if (TREE_CODE (type) == UNION_TYPE && CONSTRUCTOR_NELTS (ctor)
4242 && CONSTRUCTOR_ELT (ctor, 0)->index != index)
4243 vec_safe_truncate (CONSTRUCTOR_ELTS (ctor), 0);
4244 /* If the bit offset of INDEX is larger than that of the last
4245 constructor_elt, then we can just immediately append a new
4246 constructor_elt to the end of CTOR. */
4247 else if (CONSTRUCTOR_NELTS (ctor)
4248 && tree_int_cst_compare (bit_position (index),
4249 bit_position (CONSTRUCTOR_ELTS (ctor)
4250 ->last().index)) > 0)
4252 idx = CONSTRUCTOR_NELTS (ctor);
4253 goto insert;
4256 /* Otherwise, we need to iterate over CTOR to find or insert INDEX
4257 appropriately. */
4259 for (; vec_safe_iterate (CONSTRUCTOR_ELTS (ctor), idx, &cep);
4260 idx++, fields = DECL_CHAIN (fields))
4262 if (index == cep->index)
4263 goto found;
4265 /* The field we're initializing must be on the field
4266 list. Look to see if it is present before the
4267 field the current ELT initializes. */
4268 for (; fields != cep->index; fields = DECL_CHAIN (fields))
4269 if (index == fields)
4270 goto insert;
4272 /* We fell off the end of the CONSTRUCTOR, so insert a new
4273 entry at the end. */
4275 insert:
4277 constructor_elt ce = { index, NULL_TREE };
4279 vec_safe_insert (CONSTRUCTOR_ELTS (ctor), idx, ce);
4280 cep = CONSTRUCTOR_ELT (ctor, idx);
4282 found:;
4284 return cep;
4288 /* Under the control of CTX, issue a detailed diagnostic for
4289 an out-of-bounds subscript INDEX into the expression ARRAY. */
4291 static void
4292 diag_array_subscript (location_t loc, const constexpr_ctx *ctx, tree array, tree index)
4294 if (!ctx->quiet)
4296 tree arraytype = TREE_TYPE (array);
4298 /* Convert the unsigned array subscript to a signed integer to avoid
4299 printing huge numbers for small negative values. */
4300 tree sidx = fold_convert (ssizetype, index);
4301 STRIP_ANY_LOCATION_WRAPPER (array);
4302 if (DECL_P (array))
4304 auto_diagnostic_group d;
4305 if (TYPE_DOMAIN (arraytype))
4306 error_at (loc, "array subscript value %qE is outside the bounds "
4307 "of array %qD of type %qT", sidx, array, arraytype);
4308 else
4309 error_at (loc, "nonzero array subscript %qE is used with array %qD of "
4310 "type %qT with unknown bounds", sidx, array, arraytype);
4311 inform (DECL_SOURCE_LOCATION (array), "declared here");
4313 else if (TYPE_DOMAIN (arraytype))
4314 error_at (loc, "array subscript value %qE is outside the bounds "
4315 "of array type %qT", sidx, arraytype);
4316 else
4317 error_at (loc, "nonzero array subscript %qE is used with array of type %qT "
4318 "with unknown bounds", sidx, arraytype);
4322 /* Return the number of elements for TYPE (which is an ARRAY_TYPE or
4323 a VECTOR_TYPE). */
4325 static tree
4326 get_array_or_vector_nelts (const constexpr_ctx *ctx, tree type,
4327 bool *non_constant_p, bool *overflow_p)
4329 tree nelts;
4330 if (TREE_CODE (type) == ARRAY_TYPE)
4332 if (TYPE_DOMAIN (type))
4333 nelts = array_type_nelts_top (type);
4334 else
4335 nelts = size_zero_node;
4337 else if (VECTOR_TYPE_P (type))
4338 nelts = size_int (TYPE_VECTOR_SUBPARTS (type));
4339 else
4340 gcc_unreachable ();
4342 /* For VLAs, the number of elements won't be an integer constant. */
4343 nelts = cxx_eval_constant_expression (ctx, nelts, vc_prvalue,
4344 non_constant_p, overflow_p);
4345 return nelts;
4348 /* Extract element INDEX consisting of CHARS_PER_ELT chars from
4349 STRING_CST STRING. */
4351 static tree
4352 extract_string_elt (tree string, unsigned chars_per_elt, unsigned index)
4354 tree type = cv_unqualified (TREE_TYPE (TREE_TYPE (string)));
4355 tree r;
4357 if (chars_per_elt == 1)
4358 r = build_int_cst (type, TREE_STRING_POINTER (string)[index]);
4359 else
4361 const unsigned char *ptr
4362 = ((const unsigned char *)TREE_STRING_POINTER (string)
4363 + index * chars_per_elt);
4364 r = native_interpret_expr (type, ptr, chars_per_elt);
4366 return r;
4369 /* Subroutine of cxx_eval_array_reference. T is an ARRAY_REF; evaluate the
4370 subscript, diagnose any problems with it, and return the result. */
4372 static tree
4373 eval_and_check_array_index (const constexpr_ctx *ctx,
4374 tree t, bool allow_one_past,
4375 bool *non_constant_p, bool *overflow_p)
4377 location_t loc = cp_expr_loc_or_input_loc (t);
4378 tree ary = TREE_OPERAND (t, 0);
4379 t = TREE_OPERAND (t, 1);
4380 tree index = cxx_eval_constant_expression (ctx, t, vc_prvalue,
4381 non_constant_p, overflow_p);
4382 VERIFY_CONSTANT (index);
4384 if (!tree_fits_shwi_p (index)
4385 || tree_int_cst_sgn (index) < 0)
4387 diag_array_subscript (loc, ctx, ary, index);
4388 *non_constant_p = true;
4389 return t;
4392 tree nelts = get_array_or_vector_nelts (ctx, TREE_TYPE (ary), non_constant_p,
4393 overflow_p);
4394 VERIFY_CONSTANT (nelts);
4395 if (allow_one_past
4396 ? !tree_int_cst_le (index, nelts)
4397 : !tree_int_cst_lt (index, nelts))
4399 diag_array_subscript (loc, ctx, ary, index);
4400 *non_constant_p = true;
4401 return t;
4404 return index;
4407 /* Subroutine of cxx_eval_constant_expression.
4408 Attempt to reduce a reference to an array slot. */
4410 static tree
4411 cxx_eval_array_reference (const constexpr_ctx *ctx, tree t,
4412 value_cat lval,
4413 bool *non_constant_p, bool *overflow_p)
4415 tree oldary = TREE_OPERAND (t, 0);
4416 tree ary = cxx_eval_constant_expression (ctx, oldary,
4417 lval,
4418 non_constant_p, overflow_p);
4419 if (*non_constant_p)
4420 return t;
4421 if (!lval
4422 && TREE_CODE (ary) == VIEW_CONVERT_EXPR
4423 && VECTOR_TYPE_P (TREE_TYPE (TREE_OPERAND (ary, 0)))
4424 && TREE_TYPE (t) == TREE_TYPE (TREE_TYPE (TREE_OPERAND (ary, 0))))
4425 ary = TREE_OPERAND (ary, 0);
4427 tree oldidx = TREE_OPERAND (t, 1);
4428 tree index = eval_and_check_array_index (ctx, t, lval,
4429 non_constant_p, overflow_p);
4430 if (*non_constant_p)
4431 return t;
4433 if (lval && ary == oldary && index == oldidx)
4434 return t;
4435 else if (lval == vc_discard)
4436 return t;
4437 else if (lval)
4438 return build4 (ARRAY_REF, TREE_TYPE (t), ary, index, NULL, NULL);
4440 unsigned len = 0, elem_nchars = 1;
4441 tree elem_type = TREE_TYPE (TREE_TYPE (ary));
4442 if (TREE_CODE (ary) == CONSTRUCTOR)
4443 len = CONSTRUCTOR_NELTS (ary);
4444 else if (TREE_CODE (ary) == STRING_CST)
4446 elem_nchars = (TYPE_PRECISION (elem_type)
4447 / TYPE_PRECISION (char_type_node));
4448 len = (unsigned) TREE_STRING_LENGTH (ary) / elem_nchars;
4450 else if (TREE_CODE (ary) == VECTOR_CST)
4451 /* We don't create variable-length VECTOR_CSTs. */
4452 len = VECTOR_CST_NELTS (ary).to_constant ();
4453 else
4455 /* We can't do anything with other tree codes, so use
4456 VERIFY_CONSTANT to complain and fail. */
4457 VERIFY_CONSTANT (ary);
4458 gcc_unreachable ();
4461 bool found;
4462 HOST_WIDE_INT i = 0;
4463 if (TREE_CODE (ary) == CONSTRUCTOR)
4465 HOST_WIDE_INT ix = find_array_ctor_elt (ary, index);
4466 found = (ix >= 0);
4467 if (found)
4468 i = ix;
4470 else
4472 i = tree_to_shwi (index);
4473 found = (i < len);
4476 if (found)
4478 tree r;
4479 if (TREE_CODE (ary) == CONSTRUCTOR)
4480 r = (*CONSTRUCTOR_ELTS (ary))[i].value;
4481 else if (TREE_CODE (ary) == VECTOR_CST)
4482 r = VECTOR_CST_ELT (ary, i);
4483 else
4484 r = extract_string_elt (ary, elem_nchars, i);
4486 if (r)
4487 /* Don't VERIFY_CONSTANT here. */
4488 return r;
4490 /* Otherwise the element doesn't have a value yet. */
4493 /* Not found. */
4495 if (is_really_empty_class (elem_type, /*ignore_vptr*/false))
4496 return build_constructor (elem_type, NULL);
4498 if (TREE_CODE (ary) == CONSTRUCTOR
4499 && CONSTRUCTOR_NO_CLEARING (ary))
4501 /* 'ary' is part of the aggregate initializer we're currently
4502 building; if there's no initializer for this element yet,
4503 that's an error. */
4504 if (!ctx->quiet)
4505 error ("accessing uninitialized array element");
4506 *non_constant_p = true;
4507 return t;
4510 /* If it's within the array bounds but doesn't have an explicit
4511 initializer, it's initialized from {}. But use build_value_init
4512 directly for non-aggregates to avoid creating a garbage CONSTRUCTOR. */
4513 tree val;
4514 constexpr_ctx new_ctx;
4515 if (CP_AGGREGATE_TYPE_P (elem_type))
4517 tree empty_ctor = build_constructor (init_list_type_node, NULL);
4518 val = digest_init (elem_type, empty_ctor, tf_warning_or_error);
4520 else
4521 val = build_value_init (elem_type, tf_warning_or_error);
4523 /* Create a new constructor only if we don't already have a suitable one. */
4524 const bool new_ctor = (!SCALAR_TYPE_P (elem_type)
4525 && (!ctx->ctor
4526 || !same_type_ignoring_top_level_qualifiers_p
4527 (elem_type, TREE_TYPE (ctx->ctor))));
4528 if (new_ctor)
4530 new_ctx = *ctx;
4531 /* We clear the object here. We used to replace it with T, but that
4532 caused problems (101371, 108158); and anyway, T is the initializer,
4533 not the target object. */
4534 new_ctx.object = NULL_TREE;
4535 new_ctx.ctor = build_constructor (elem_type, NULL);
4536 ctx = &new_ctx;
4538 t = cxx_eval_constant_expression (ctx, val, lval, non_constant_p,
4539 overflow_p);
4540 if (new_ctor && t != ctx->ctor)
4541 free_constructor (ctx->ctor);
4542 return t;
4545 /* Subroutine of cxx_eval_constant_expression.
4546 Attempt to reduce a field access of a value of class type. */
4548 static tree
4549 cxx_eval_component_reference (const constexpr_ctx *ctx, tree t,
4550 value_cat lval,
4551 bool *non_constant_p, bool *overflow_p)
4553 unsigned HOST_WIDE_INT i;
4554 tree field;
4555 tree value;
4556 tree part = TREE_OPERAND (t, 1);
4557 tree orig_whole = TREE_OPERAND (t, 0);
4558 tree whole = cxx_eval_constant_expression (ctx, orig_whole,
4559 lval,
4560 non_constant_p, overflow_p);
4561 if (*non_constant_p)
4562 return t;
4563 if (INDIRECT_REF_P (whole)
4564 && integer_zerop (TREE_OPERAND (whole, 0)))
4566 if (!ctx->quiet)
4567 error ("dereferencing a null pointer in %qE", orig_whole);
4568 *non_constant_p = true;
4569 return t;
4572 if (TREE_CODE (whole) == PTRMEM_CST)
4573 whole = cplus_expand_constant (whole);
4574 if (whole == orig_whole)
4575 return t;
4576 if (lval == vc_discard)
4577 return t;
4578 if (lval)
4579 return fold_build3 (COMPONENT_REF, TREE_TYPE (t),
4580 whole, part, NULL_TREE);
4581 /* Don't VERIFY_CONSTANT here; we only want to check that we got a
4582 CONSTRUCTOR. */
4583 if (TREE_CODE (whole) != CONSTRUCTOR)
4585 if (!ctx->quiet)
4586 error ("%qE is not a constant expression", orig_whole);
4587 *non_constant_p = true;
4588 return t;
4590 if ((cxx_dialect < cxx14 || CONSTRUCTOR_MUTABLE_POISON (whole))
4591 && DECL_MUTABLE_P (part))
4593 if (!ctx->quiet)
4594 error ("mutable %qD is not usable in a constant expression", part);
4595 *non_constant_p = true;
4596 return t;
4599 bool pmf = TYPE_PTRMEMFUNC_P (TREE_TYPE (whole));
4600 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
4602 /* Use name match for PMF fields, as a variant will have a
4603 different FIELD_DECL with a different type. */
4604 if (pmf ? DECL_NAME (field) == DECL_NAME (part)
4605 : field == part)
4607 if (value)
4609 STRIP_ANY_LOCATION_WRAPPER (value);
4610 return value;
4612 else
4613 /* We're in the middle of initializing it. */
4614 break;
4617 if (TREE_CODE (TREE_TYPE (whole)) == UNION_TYPE)
4619 if (CONSTRUCTOR_NELTS (whole) > 0)
4621 /* DR 1188 says we don't have to deal with this. */
4622 if (!ctx->quiet)
4624 constructor_elt *cep = CONSTRUCTOR_ELT (whole, 0);
4625 if (cep->value == NULL_TREE)
4626 error ("accessing uninitialized member %qD", part);
4627 else
4628 error ("accessing %qD member instead of initialized %qD member "
4629 "in constant expression", part, cep->index);
4631 *non_constant_p = true;
4632 return t;
4634 else if (!CONSTRUCTOR_NO_CLEARING (whole))
4636 /* Value-initialized union, check if looking at the first member. */
4637 tree first = next_aggregate_field (TYPE_FIELDS (TREE_TYPE (whole)));
4638 if (first != part)
4640 if (!ctx->quiet)
4641 error ("accessing %qD member instead of initialized %qD "
4642 "member in constant expression", part, first);
4643 *non_constant_p = true;
4644 return t;
4649 /* We only create a CONSTRUCTOR for a subobject when we modify it, so empty
4650 classes never get represented; throw together a value now. */
4651 if (is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
4652 return build_constructor (TREE_TYPE (t), NULL);
4654 gcc_assert (DECL_CONTEXT (part) == TYPE_MAIN_VARIANT (TREE_TYPE (whole)));
4656 if (CONSTRUCTOR_NO_CLEARING (whole))
4658 /* 'whole' is part of the aggregate initializer we're currently
4659 building; if there's no initializer for this member yet, that's an
4660 error. */
4661 if (!ctx->quiet)
4662 error ("accessing uninitialized member %qD", part);
4663 *non_constant_p = true;
4664 return t;
4667 /* If there's no explicit init for this field, it's value-initialized. */
4668 value = build_value_init (TREE_TYPE (t), tf_warning_or_error);
4669 return cxx_eval_constant_expression (ctx, value,
4670 lval,
4671 non_constant_p, overflow_p);
4674 /* Subroutine of cxx_eval_constant_expression.
4675 Attempt to reduce a field access of a value of class type that is
4676 expressed as a BIT_FIELD_REF. */
4678 static tree
4679 cxx_eval_bit_field_ref (const constexpr_ctx *ctx, tree t,
4680 value_cat lval,
4681 bool *non_constant_p, bool *overflow_p)
4683 tree orig_whole = TREE_OPERAND (t, 0);
4684 tree retval, fldval, utype, mask;
4685 bool fld_seen = false;
4686 HOST_WIDE_INT istart, isize;
4687 tree whole = cxx_eval_constant_expression (ctx, orig_whole,
4688 lval,
4689 non_constant_p, overflow_p);
4690 tree start, field, value;
4691 unsigned HOST_WIDE_INT i;
4693 if (whole == orig_whole)
4694 return t;
4695 /* Don't VERIFY_CONSTANT here; we only want to check that we got a
4696 CONSTRUCTOR. */
4697 if (!*non_constant_p
4698 && TREE_CODE (whole) != VECTOR_CST
4699 && TREE_CODE (whole) != CONSTRUCTOR)
4701 if (!ctx->quiet)
4702 error ("%qE is not a constant expression", orig_whole);
4703 *non_constant_p = true;
4705 if (*non_constant_p)
4706 return t;
4708 if (TREE_CODE (whole) == VECTOR_CST || !INTEGRAL_TYPE_P (TREE_TYPE (t)))
4710 if (tree r = fold_ternary (BIT_FIELD_REF, TREE_TYPE (t), whole,
4711 TREE_OPERAND (t, 1), TREE_OPERAND (t, 2)))
4712 return r;
4713 if (!ctx->quiet)
4714 error ("%qE is not a constant expression", orig_whole);
4715 *non_constant_p = true;
4716 return t;
4719 start = TREE_OPERAND (t, 2);
4720 istart = tree_to_shwi (start);
4721 isize = tree_to_shwi (TREE_OPERAND (t, 1));
4722 utype = TREE_TYPE (t);
4723 if (!TYPE_UNSIGNED (utype))
4724 utype = build_nonstandard_integer_type (TYPE_PRECISION (utype), 1);
4725 retval = build_int_cst (utype, 0);
4726 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
4728 tree bitpos = bit_position (field);
4729 STRIP_ANY_LOCATION_WRAPPER (value);
4730 if (bitpos == start && DECL_SIZE (field) == TREE_OPERAND (t, 1))
4731 return value;
4732 if (TREE_CODE (TREE_TYPE (field)) == INTEGER_TYPE
4733 && TREE_CODE (value) == INTEGER_CST
4734 && tree_fits_shwi_p (bitpos)
4735 && tree_fits_shwi_p (DECL_SIZE (field)))
4737 HOST_WIDE_INT bit = tree_to_shwi (bitpos);
4738 HOST_WIDE_INT sz = tree_to_shwi (DECL_SIZE (field));
4739 HOST_WIDE_INT shift;
4740 if (bit >= istart && bit + sz <= istart + isize)
4742 fldval = fold_convert (utype, value);
4743 mask = build_int_cst_type (utype, -1);
4744 mask = fold_build2 (LSHIFT_EXPR, utype, mask,
4745 size_int (TYPE_PRECISION (utype) - sz));
4746 mask = fold_build2 (RSHIFT_EXPR, utype, mask,
4747 size_int (TYPE_PRECISION (utype) - sz));
4748 fldval = fold_build2 (BIT_AND_EXPR, utype, fldval, mask);
4749 shift = bit - istart;
4750 if (BYTES_BIG_ENDIAN)
4751 shift = TYPE_PRECISION (utype) - shift - sz;
4752 fldval = fold_build2 (LSHIFT_EXPR, utype, fldval,
4753 size_int (shift));
4754 retval = fold_build2 (BIT_IOR_EXPR, utype, retval, fldval);
4755 fld_seen = true;
4759 if (fld_seen)
4760 return fold_convert (TREE_TYPE (t), retval);
4761 gcc_unreachable ();
4762 return error_mark_node;
4765 /* Helper for cxx_eval_bit_cast.
4766 Check [bit.cast]/3 rules, bit_cast is constexpr only if the To and From
4767 types and types of all subobjects have is_union_v<T>, is_pointer_v<T>,
4768 is_member_pointer_v<T>, is_volatile_v<T> false and has no non-static
4769 data members of reference type. */
4771 static bool
4772 check_bit_cast_type (const constexpr_ctx *ctx, location_t loc, tree type,
4773 tree orig_type)
4775 if (TREE_CODE (type) == UNION_TYPE)
4777 if (!ctx->quiet)
4779 if (type == orig_type)
4780 error_at (loc, "%qs is not a constant expression because %qT is "
4781 "a union type", "__builtin_bit_cast", type);
4782 else
4783 error_at (loc, "%qs is not a constant expression because %qT "
4784 "contains a union type", "__builtin_bit_cast",
4785 orig_type);
4787 return true;
4789 if (TREE_CODE (type) == POINTER_TYPE)
4791 if (!ctx->quiet)
4793 if (type == orig_type)
4794 error_at (loc, "%qs is not a constant expression because %qT is "
4795 "a pointer type", "__builtin_bit_cast", type);
4796 else
4797 error_at (loc, "%qs is not a constant expression because %qT "
4798 "contains a pointer type", "__builtin_bit_cast",
4799 orig_type);
4801 return true;
4803 if (TREE_CODE (type) == REFERENCE_TYPE)
4805 if (!ctx->quiet)
4807 if (type == orig_type)
4808 error_at (loc, "%qs is not a constant expression because %qT is "
4809 "a reference type", "__builtin_bit_cast", type);
4810 else
4811 error_at (loc, "%qs is not a constant expression because %qT "
4812 "contains a reference type", "__builtin_bit_cast",
4813 orig_type);
4815 return true;
4817 if (TYPE_PTRMEM_P (type))
4819 if (!ctx->quiet)
4821 if (type == orig_type)
4822 error_at (loc, "%qs is not a constant expression because %qT is "
4823 "a pointer to member type", "__builtin_bit_cast",
4824 type);
4825 else
4826 error_at (loc, "%qs is not a constant expression because %qT "
4827 "contains a pointer to member type",
4828 "__builtin_bit_cast", orig_type);
4830 return true;
4832 if (TYPE_VOLATILE (type))
4834 if (!ctx->quiet)
4836 if (type == orig_type)
4837 error_at (loc, "%qs is not a constant expression because %qT is "
4838 "volatile", "__builtin_bit_cast", type);
4839 else
4840 error_at (loc, "%qs is not a constant expression because %qT "
4841 "contains a volatile subobject",
4842 "__builtin_bit_cast", orig_type);
4844 return true;
4846 if (TREE_CODE (type) == RECORD_TYPE)
4847 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
4848 if (TREE_CODE (field) == FIELD_DECL
4849 && check_bit_cast_type (ctx, loc, TREE_TYPE (field), orig_type))
4850 return true;
4851 return false;
4854 /* Helper function for cxx_eval_bit_cast. For unsigned char or
4855 std::byte members of CONSTRUCTOR (recursively) if they contain
4856 some indeterminate bits (as set in MASK), remove the ctor elts,
4857 mark the CONSTRUCTOR as CONSTRUCTOR_NO_CLEARING and clear the
4858 bits in MASK. */
4860 static void
4861 clear_uchar_or_std_byte_in_mask (location_t loc, tree t, unsigned char *mask)
4863 if (TREE_CODE (t) != CONSTRUCTOR)
4864 return;
4866 unsigned i, j = 0;
4867 tree index, value;
4868 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (t), i, index, value)
4870 tree type = TREE_TYPE (value);
4871 if (TREE_CODE (TREE_TYPE (t)) != ARRAY_TYPE
4872 && DECL_BIT_FIELD_TYPE (index) != NULL_TREE)
4874 if (is_byte_access_type_not_plain_char (DECL_BIT_FIELD_TYPE (index)))
4876 HOST_WIDE_INT fldsz = TYPE_PRECISION (TREE_TYPE (index));
4877 gcc_assert (fldsz != 0);
4878 HOST_WIDE_INT pos = int_byte_position (index);
4879 HOST_WIDE_INT bpos
4880 = tree_to_uhwi (DECL_FIELD_BIT_OFFSET (index));
4881 bpos %= BITS_PER_UNIT;
4882 HOST_WIDE_INT end
4883 = ROUND_UP (bpos + fldsz, BITS_PER_UNIT) / BITS_PER_UNIT;
4884 gcc_assert (end == 1 || end == 2);
4885 unsigned char *p = mask + pos;
4886 unsigned char mask_save[2];
4887 mask_save[0] = mask[pos];
4888 mask_save[1] = end == 2 ? mask[pos + 1] : 0;
4889 if (BYTES_BIG_ENDIAN != WORDS_BIG_ENDIAN)
4890 sorry_at (loc, "PDP11 bit-field handling unsupported"
4891 " in %qs", "__builtin_bit_cast");
4892 else if (BYTES_BIG_ENDIAN)
4894 /* Big endian. */
4895 if (bpos + fldsz <= BITS_PER_UNIT)
4896 *p &= ~(((1 << fldsz) - 1)
4897 << (BITS_PER_UNIT - bpos - fldsz));
4898 else
4900 gcc_assert (bpos);
4901 *p &= ~(((1U << BITS_PER_UNIT) - 1) >> bpos);
4902 p++;
4903 fldsz -= BITS_PER_UNIT - bpos;
4904 gcc_assert (fldsz && fldsz < BITS_PER_UNIT);
4905 *p &= ((1U << BITS_PER_UNIT) - 1) >> fldsz;
4908 else
4910 /* Little endian. */
4911 if (bpos + fldsz <= BITS_PER_UNIT)
4912 *p &= ~(((1 << fldsz) - 1) << bpos);
4913 else
4915 gcc_assert (bpos);
4916 *p &= ~(((1 << BITS_PER_UNIT) - 1) << bpos);
4917 p++;
4918 fldsz -= BITS_PER_UNIT - bpos;
4919 gcc_assert (fldsz && fldsz < BITS_PER_UNIT);
4920 *p &= ~((1 << fldsz) - 1);
4923 if (mask_save[0] != mask[pos]
4924 || (end == 2 && mask_save[1] != mask[pos + 1]))
4926 CONSTRUCTOR_NO_CLEARING (t) = 1;
4927 continue;
4931 else if (is_byte_access_type_not_plain_char (type))
4933 HOST_WIDE_INT pos;
4934 if (TREE_CODE (TREE_TYPE (t)) == ARRAY_TYPE)
4935 pos = tree_to_shwi (index);
4936 else
4937 pos = int_byte_position (index);
4938 if (mask[pos])
4940 CONSTRUCTOR_NO_CLEARING (t) = 1;
4941 mask[pos] = 0;
4942 continue;
4945 if (TREE_CODE (value) == CONSTRUCTOR)
4947 HOST_WIDE_INT pos;
4948 if (TREE_CODE (TREE_TYPE (t)) == ARRAY_TYPE)
4949 pos = tree_to_shwi (index)
4950 * tree_to_shwi (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (t))));
4951 else
4952 pos = int_byte_position (index);
4953 clear_uchar_or_std_byte_in_mask (loc, value, mask + pos);
4955 if (i != j)
4957 CONSTRUCTOR_ELT (t, j)->index = index;
4958 CONSTRUCTOR_ELT (t, j)->value = value;
4960 ++j;
4962 if (CONSTRUCTOR_NELTS (t) != j)
4963 vec_safe_truncate (CONSTRUCTOR_ELTS (t), j);
4966 /* Subroutine of cxx_eval_constant_expression.
4967 Attempt to evaluate a BIT_CAST_EXPR. */
4969 static tree
4970 cxx_eval_bit_cast (const constexpr_ctx *ctx, tree t, bool *non_constant_p,
4971 bool *overflow_p)
4973 if (check_bit_cast_type (ctx, EXPR_LOCATION (t), TREE_TYPE (t),
4974 TREE_TYPE (t))
4975 || check_bit_cast_type (ctx, cp_expr_loc_or_loc (TREE_OPERAND (t, 0),
4976 EXPR_LOCATION (t)),
4977 TREE_TYPE (TREE_OPERAND (t, 0)),
4978 TREE_TYPE (TREE_OPERAND (t, 0))))
4980 *non_constant_p = true;
4981 return t;
4984 tree op = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), vc_prvalue,
4985 non_constant_p, overflow_p);
4986 if (*non_constant_p)
4987 return t;
4989 location_t loc = EXPR_LOCATION (t);
4990 if (BITS_PER_UNIT != 8 || CHAR_BIT != 8)
4992 if (!ctx->quiet)
4993 sorry_at (loc, "%qs cannot be constant evaluated on the target",
4994 "__builtin_bit_cast");
4995 *non_constant_p = true;
4996 return t;
4999 if (!tree_fits_shwi_p (TYPE_SIZE_UNIT (TREE_TYPE (t))))
5001 if (!ctx->quiet)
5002 sorry_at (loc, "%qs cannot be constant evaluated because the "
5003 "type is too large", "__builtin_bit_cast");
5004 *non_constant_p = true;
5005 return t;
5008 HOST_WIDE_INT len = tree_to_shwi (TYPE_SIZE_UNIT (TREE_TYPE (t)));
5009 if (len < 0 || (int) len != len)
5011 if (!ctx->quiet)
5012 sorry_at (loc, "%qs cannot be constant evaluated because the "
5013 "type is too large", "__builtin_bit_cast");
5014 *non_constant_p = true;
5015 return t;
5018 unsigned char buf[64];
5019 unsigned char *ptr, *mask;
5020 size_t alen = (size_t) len * 2;
5021 if (alen <= sizeof (buf))
5022 ptr = buf;
5023 else
5024 ptr = XNEWVEC (unsigned char, alen);
5025 mask = ptr + (size_t) len;
5026 /* At the beginning consider everything indeterminate. */
5027 memset (mask, ~0, (size_t) len);
5029 if (native_encode_initializer (op, ptr, len, 0, mask) != len)
5031 if (!ctx->quiet)
5032 sorry_at (loc, "%qs cannot be constant evaluated because the "
5033 "argument cannot be encoded", "__builtin_bit_cast");
5034 *non_constant_p = true;
5035 if (ptr != buf)
5036 XDELETE (ptr);
5037 return t;
5040 tree r = NULL_TREE;
5041 if (can_native_interpret_type_p (TREE_TYPE (t)))
5043 r = native_interpret_expr (TREE_TYPE (t), ptr, len);
5044 if (is_byte_access_type_not_plain_char (TREE_TYPE (t)))
5046 gcc_assert (len == 1);
5047 if (mask[0])
5049 memset (mask, 0, len);
5050 r = build_constructor (TREE_TYPE (r), NULL);
5051 CONSTRUCTOR_NO_CLEARING (r) = 1;
5055 else if (TREE_CODE (TREE_TYPE (t)) == RECORD_TYPE)
5057 r = native_interpret_aggregate (TREE_TYPE (t), ptr, 0, len);
5058 if (r != NULL_TREE)
5060 clear_type_padding_in_mask (TREE_TYPE (t), mask);
5061 clear_uchar_or_std_byte_in_mask (loc, r, mask);
5062 if (CHECKING_P)
5064 tree e = cxx_eval_bare_aggregate (ctx, r, vc_prvalue,
5065 non_constant_p, overflow_p);
5066 gcc_checking_assert (e == r);
5067 r = e;
5072 if (r != NULL_TREE)
5074 for (int i = 0; i < len; i++)
5075 if (mask[i])
5077 if (!ctx->quiet)
5078 error_at (loc, "%qs accessing uninitialized byte at offset %d",
5079 "__builtin_bit_cast", i);
5080 *non_constant_p = true;
5081 r = t;
5082 break;
5084 if (ptr != buf)
5085 XDELETE (ptr);
5086 return r;
5089 if (!ctx->quiet)
5090 sorry_at (loc, "%qs cannot be constant evaluated because the "
5091 "argument cannot be interpreted", "__builtin_bit_cast");
5092 *non_constant_p = true;
5093 if (ptr != buf)
5094 XDELETE (ptr);
5095 return t;
5098 /* Subroutine of cxx_eval_constant_expression.
5099 Evaluate a short-circuited logical expression T in the context
5100 of a given constexpr CALL. BAILOUT_VALUE is the value for
5101 early return. CONTINUE_VALUE is used here purely for
5102 sanity check purposes. */
5104 static tree
5105 cxx_eval_logical_expression (const constexpr_ctx *ctx, tree t,
5106 tree bailout_value, tree continue_value,
5107 bool *non_constant_p, bool *overflow_p)
5109 tree r;
5110 tree lhs = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
5111 vc_prvalue, non_constant_p,
5112 overflow_p);
5113 VERIFY_CONSTANT (lhs);
5114 if (tree_int_cst_equal (lhs, bailout_value))
5115 return lhs;
5116 gcc_assert (tree_int_cst_equal (lhs, continue_value));
5117 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
5118 vc_prvalue, non_constant_p,
5119 overflow_p);
5120 VERIFY_CONSTANT (r);
5121 return r;
5124 /* REF is a COMPONENT_REF designating a particular field. V is a vector of
5125 CONSTRUCTOR elements to initialize (part of) an object containing that
5126 field. Return a pointer to the constructor_elt corresponding to the
5127 initialization of the field. */
5129 static constructor_elt *
5130 base_field_constructor_elt (vec<constructor_elt, va_gc> *v, tree ref)
5132 tree aggr = TREE_OPERAND (ref, 0);
5133 tree field = TREE_OPERAND (ref, 1);
5134 HOST_WIDE_INT i;
5135 constructor_elt *ce;
5137 gcc_assert (TREE_CODE (ref) == COMPONENT_REF);
5139 if (TREE_CODE (aggr) == COMPONENT_REF)
5141 constructor_elt *base_ce
5142 = base_field_constructor_elt (v, aggr);
5143 v = CONSTRUCTOR_ELTS (base_ce->value);
5146 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
5147 if (ce->index == field)
5148 return ce;
5150 gcc_unreachable ();
5151 return NULL;
5154 /* Some of the expressions fed to the constexpr mechanism are calls to
5155 constructors, which have type void. In that case, return the type being
5156 initialized by the constructor. */
5158 static tree
5159 initialized_type (tree t)
5161 if (TYPE_P (t))
5162 return t;
5163 tree type = TREE_TYPE (t);
5164 if (TREE_CODE (t) == CALL_EXPR)
5166 /* A constructor call has void type, so we need to look deeper. */
5167 tree fn = get_function_named_in_call (t);
5168 if (fn && TREE_CODE (fn) == FUNCTION_DECL
5169 && DECL_CXX_CONSTRUCTOR_P (fn))
5170 type = DECL_CONTEXT (fn);
5172 else if (TREE_CODE (t) == COMPOUND_EXPR)
5173 return initialized_type (TREE_OPERAND (t, 1));
5174 else if (TREE_CODE (t) == AGGR_INIT_EXPR)
5175 type = TREE_TYPE (AGGR_INIT_EXPR_SLOT (t));
5176 return cv_unqualified (type);
5179 /* We're about to initialize element INDEX of an array or class from VALUE.
5180 Set up NEW_CTX appropriately by adjusting .object to refer to the
5181 subobject and creating a new CONSTRUCTOR if the element is itself
5182 a class or array. */
5184 static void
5185 init_subob_ctx (const constexpr_ctx *ctx, constexpr_ctx &new_ctx,
5186 tree index, tree &value)
5188 new_ctx = *ctx;
5190 if (index && TREE_CODE (index) != INTEGER_CST
5191 && TREE_CODE (index) != FIELD_DECL
5192 && TREE_CODE (index) != RANGE_EXPR)
5193 /* This won't have an element in the new CONSTRUCTOR. */
5194 return;
5196 tree type = initialized_type (value);
5197 if (!AGGREGATE_TYPE_P (type) && !VECTOR_TYPE_P (type))
5198 /* A non-aggregate member doesn't get its own CONSTRUCTOR. */
5199 return;
5200 if (VECTOR_TYPE_P (type)
5201 && VECTOR_TYPE_P (TREE_TYPE (ctx->ctor))
5202 && index == NULL_TREE)
5203 /* A vector inside of a vector CONSTRUCTOR, e.g. when a larger
5204 vector is constructed from smaller vectors, doesn't get its own
5205 CONSTRUCTOR either. */
5206 return;
5208 /* The sub-aggregate initializer might contain a placeholder;
5209 update object to refer to the subobject and ctor to refer to
5210 the (newly created) sub-initializer. */
5211 if (ctx->object)
5213 if (index == NULL_TREE || TREE_CODE (index) == RANGE_EXPR)
5214 /* There's no well-defined subobject for this index. */
5215 new_ctx.object = NULL_TREE;
5216 else
5217 new_ctx.object = build_ctor_subob_ref (index, type, ctx->object);
5220 if (is_empty_class (type))
5221 /* Leave ctor null for an empty subobject, they aren't represented in the
5222 result of evaluation. */
5223 new_ctx.ctor = NULL_TREE;
5224 else
5226 tree elt = build_constructor (type, NULL);
5227 CONSTRUCTOR_NO_CLEARING (elt) = true;
5228 new_ctx.ctor = elt;
5231 if (TREE_CODE (value) == TARGET_EXPR)
5232 /* Avoid creating another CONSTRUCTOR when we expand the TARGET_EXPR. */
5233 value = TARGET_EXPR_INITIAL (value);
5236 /* We're about to process an initializer for a class or array TYPE. Make
5237 sure that CTX is set up appropriately. */
5239 static void
5240 verify_ctor_sanity (const constexpr_ctx *ctx, tree type)
5242 /* We don't bother building a ctor for an empty base subobject. */
5243 if (is_empty_class (type))
5244 return;
5246 /* We're in the middle of an initializer that might involve placeholders;
5247 our caller should have created a CONSTRUCTOR for us to put the
5248 initializer into. We will either return that constructor or T. */
5249 gcc_assert (ctx->ctor);
5250 gcc_assert (same_type_ignoring_top_level_qualifiers_p
5251 (type, TREE_TYPE (ctx->ctor)));
5252 /* We used to check that ctx->ctor was empty, but that isn't the case when
5253 the object is zero-initialized before calling the constructor. */
5254 if (ctx->object)
5256 tree otype = TREE_TYPE (ctx->object);
5257 gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, otype)
5258 /* Handle flexible array members. */
5259 || (TREE_CODE (otype) == ARRAY_TYPE
5260 && TYPE_DOMAIN (otype) == NULL_TREE
5261 && TREE_CODE (type) == ARRAY_TYPE
5262 && (same_type_ignoring_top_level_qualifiers_p
5263 (TREE_TYPE (type), TREE_TYPE (otype)))));
5265 gcc_assert (!ctx->object || !DECL_P (ctx->object)
5266 || ctx->global->get_value (ctx->object) == ctx->ctor);
5269 /* Subroutine of cxx_eval_constant_expression.
5270 The expression tree T denotes a C-style array or a C-style
5271 aggregate. Reduce it to a constant expression. */
5273 static tree
5274 cxx_eval_bare_aggregate (const constexpr_ctx *ctx, tree t,
5275 value_cat lval,
5276 bool *non_constant_p, bool *overflow_p)
5278 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
5279 bool changed = false;
5280 gcc_assert (!BRACE_ENCLOSED_INITIALIZER_P (t));
5281 tree type = TREE_TYPE (t);
5283 constexpr_ctx new_ctx;
5284 if (TYPE_PTRMEMFUNC_P (type) || VECTOR_TYPE_P (type))
5286 /* We don't really need the ctx->ctor business for a PMF or
5287 vector, but it's simpler to use the same code. */
5288 new_ctx = *ctx;
5289 new_ctx.ctor = build_constructor (type, NULL);
5290 new_ctx.object = NULL_TREE;
5291 ctx = &new_ctx;
5293 verify_ctor_sanity (ctx, type);
5294 vec<constructor_elt, va_gc> **p = nullptr;
5295 if (ctx->ctor)
5297 p = &CONSTRUCTOR_ELTS (ctx->ctor);
5298 vec_alloc (*p, vec_safe_length (v));
5299 if (CONSTRUCTOR_PLACEHOLDER_BOUNDARY (t))
5300 CONSTRUCTOR_PLACEHOLDER_BOUNDARY (ctx->ctor) = 1;
5303 unsigned i;
5304 tree index, value;
5305 bool constant_p = true;
5306 bool side_effects_p = false;
5307 FOR_EACH_CONSTRUCTOR_ELT (v, i, index, value)
5309 tree orig_value = value;
5310 init_subob_ctx (ctx, new_ctx, index, value);
5311 /* Like in cxx_eval_store_expression, omit entries for empty fields. */
5312 bool no_slot = new_ctx.ctor == NULL_TREE;
5313 int pos_hint = -1;
5314 if (new_ctx.ctor != ctx->ctor && !no_slot)
5316 /* If we built a new CONSTRUCTOR, attach it now so that other
5317 initializers can refer to it. */
5318 constructor_elt *cep = get_or_insert_ctor_field (ctx->ctor, index);
5319 cep->value = new_ctx.ctor;
5320 pos_hint = cep - (*p)->begin();
5322 else if (TREE_CODE (type) == UNION_TYPE)
5323 /* Otherwise if we're constructing a non-aggregate union member, set
5324 the active union member now so that we can later detect and diagnose
5325 if its initializer attempts to activate another member. */
5326 get_or_insert_ctor_field (ctx->ctor, index);
5327 tree elt = cxx_eval_constant_expression (&new_ctx, value,
5328 lval,
5329 non_constant_p, overflow_p);
5330 /* Don't VERIFY_CONSTANT here. */
5331 if (ctx->quiet && *non_constant_p)
5332 break;
5333 if (elt != orig_value)
5334 changed = true;
5336 if (!TREE_CONSTANT (elt))
5337 constant_p = false;
5338 if (TREE_SIDE_EFFECTS (elt))
5339 side_effects_p = true;
5340 if (index && TREE_CODE (index) == COMPONENT_REF)
5342 /* This is an initialization of a vfield inside a base
5343 subaggregate that we already initialized; push this
5344 initialization into the previous initialization. */
5345 constructor_elt *inner = base_field_constructor_elt (*p, index);
5346 inner->value = elt;
5347 changed = true;
5349 else if (no_slot)
5350 /* This is an initializer for an empty field; now that we've
5351 checked that it's constant, we can ignore it. */
5352 changed = true;
5353 else if (index
5354 && (TREE_CODE (index) == NOP_EXPR
5355 || TREE_CODE (index) == POINTER_PLUS_EXPR))
5357 /* Old representation of empty bases. FIXME remove. */
5358 gcc_checking_assert (false);
5359 gcc_assert (is_empty_class (TREE_TYPE (TREE_TYPE (index))));
5360 changed = true;
5362 else
5364 if (TREE_CODE (type) == UNION_TYPE
5365 && (*p)->last().index != index)
5366 /* The initializer erroneously changed the active union member that
5367 we're initializing. */
5368 gcc_assert (*non_constant_p);
5369 else
5371 /* The initializer might have mutated the underlying CONSTRUCTOR,
5372 so recompute the location of the target constructer_elt. */
5373 constructor_elt *cep
5374 = get_or_insert_ctor_field (ctx->ctor, index, pos_hint);
5375 cep->value = elt;
5378 /* Adding or replacing an element might change the ctor's flags. */
5379 TREE_CONSTANT (ctx->ctor) = constant_p;
5380 TREE_SIDE_EFFECTS (ctx->ctor) = side_effects_p;
5383 if (*non_constant_p)
5384 return t;
5385 if (!changed)
5387 if (VECTOR_TYPE_P (type))
5388 t = fold (t);
5389 return t;
5391 t = ctx->ctor;
5392 if (!t)
5393 t = build_constructor (type, NULL);
5394 /* We're done building this CONSTRUCTOR, so now we can interpret an
5395 element without an explicit initializer as value-initialized. */
5396 CONSTRUCTOR_NO_CLEARING (t) = false;
5397 TREE_CONSTANT (t) = constant_p;
5398 TREE_SIDE_EFFECTS (t) = side_effects_p;
5399 if (VECTOR_TYPE_P (type))
5400 t = fold (t);
5401 return t;
5404 /* Subroutine of cxx_eval_constant_expression.
5405 The expression tree T is a VEC_INIT_EXPR which denotes the desired
5406 initialization of a non-static data member of array type. Reduce it to a
5407 CONSTRUCTOR.
5409 Note that apart from value-initialization (when VALUE_INIT is true),
5410 this is only intended to support value-initialization and the
5411 initializations done by defaulted constructors for classes with
5412 non-static data members of array type. In this case, VEC_INIT_EXPR_INIT
5413 will either be NULL_TREE for the default constructor, or a COMPONENT_REF
5414 for the copy/move constructor. */
5416 static tree
5417 cxx_eval_vec_init_1 (const constexpr_ctx *ctx, tree atype, tree init,
5418 bool value_init, value_cat lval,
5419 bool *non_constant_p, bool *overflow_p)
5421 tree elttype = TREE_TYPE (atype);
5422 verify_ctor_sanity (ctx, atype);
5423 vec<constructor_elt, va_gc> **p = &CONSTRUCTOR_ELTS (ctx->ctor);
5424 bool pre_init = false;
5425 unsigned HOST_WIDE_INT i;
5426 tsubst_flags_t complain = ctx->quiet ? tf_none : tf_warning_or_error;
5428 if (init && TREE_CODE (init) == CONSTRUCTOR)
5429 return cxx_eval_bare_aggregate (ctx, init, lval,
5430 non_constant_p, overflow_p);
5432 /* For the default constructor, build up a call to the default
5433 constructor of the element type. We only need to handle class types
5434 here, as for a constructor to be constexpr, all members must be
5435 initialized, which for a defaulted default constructor means they must
5436 be of a class type with a constexpr default constructor. */
5437 if (TREE_CODE (elttype) == ARRAY_TYPE)
5438 /* We only do this at the lowest level. */;
5439 else if (value_init)
5441 init = build_value_init (elttype, complain);
5442 pre_init = true;
5444 else if (!init)
5446 releasing_vec argvec;
5447 init = build_special_member_call (NULL_TREE, complete_ctor_identifier,
5448 &argvec, elttype, LOOKUP_NORMAL,
5449 complain);
5450 init = build_aggr_init_expr (elttype, init);
5451 pre_init = true;
5454 bool zeroed_out = false;
5455 if (!CONSTRUCTOR_NO_CLEARING (ctx->ctor))
5457 /* We're initializing an array object that had been zero-initialized
5458 earlier. Truncate ctx->ctor, and propagate its zeroed state by
5459 clearing CONSTRUCTOR_NO_CLEARING on each of the aggregate element
5460 initializers we append to it. */
5461 gcc_checking_assert (initializer_zerop (ctx->ctor));
5462 zeroed_out = true;
5463 vec_safe_truncate (*p, 0);
5466 tree nelts = get_array_or_vector_nelts (ctx, atype, non_constant_p,
5467 overflow_p);
5468 unsigned HOST_WIDE_INT max = tree_to_uhwi (nelts);
5469 for (i = 0; i < max; ++i)
5471 tree idx = build_int_cst (size_type_node, i);
5472 tree eltinit;
5473 bool reuse = false;
5474 constexpr_ctx new_ctx;
5475 init_subob_ctx (ctx, new_ctx, idx, pre_init ? init : elttype);
5476 bool no_slot = new_ctx.ctor == NULL_TREE;
5477 if (new_ctx.ctor != ctx->ctor && !no_slot)
5479 if (zeroed_out)
5480 CONSTRUCTOR_NO_CLEARING (new_ctx.ctor) = false;
5481 CONSTRUCTOR_APPEND_ELT (*p, idx, new_ctx.ctor);
5483 if (TREE_CODE (elttype) == ARRAY_TYPE)
5485 /* A multidimensional array; recurse. */
5486 if (value_init || init == NULL_TREE)
5488 eltinit = NULL_TREE;
5489 reuse = i == 0;
5491 else
5492 eltinit = cp_build_array_ref (input_location, init, idx, complain);
5493 eltinit = cxx_eval_vec_init_1 (&new_ctx, elttype, eltinit, value_init,
5494 lval,
5495 non_constant_p, overflow_p);
5497 else if (pre_init)
5499 /* Initializing an element using value or default initialization
5500 we just pre-built above. */
5501 if (init == void_node)
5502 /* Trivial default-init, don't do anything to the CONSTRUCTOR. */
5503 return ctx->ctor;
5504 eltinit = cxx_eval_constant_expression (&new_ctx, init, lval,
5505 non_constant_p, overflow_p);
5506 reuse = i == 0;
5508 else
5510 /* Copying an element. */
5511 eltinit = cp_build_array_ref (input_location, init, idx, complain);
5512 if (!lvalue_p (init))
5513 eltinit = move (eltinit);
5514 eltinit = (perform_implicit_conversion_flags
5515 (elttype, eltinit, complain,
5516 LOOKUP_IMPLICIT|LOOKUP_NO_NARROWING));
5517 eltinit = cxx_eval_constant_expression (&new_ctx, eltinit, lval,
5518 non_constant_p, overflow_p);
5520 if (*non_constant_p)
5521 break;
5522 if (no_slot)
5524 /* This is an initializer for an empty subobject; now that we've
5525 checked that it's constant, we can ignore it. */
5526 gcc_checking_assert (i == 0);
5527 break;
5529 else if (new_ctx.ctor != ctx->ctor)
5531 /* We appended this element above; update the value. */
5532 gcc_assert ((*p)->last().index == idx);
5533 (*p)->last().value = eltinit;
5535 else
5536 CONSTRUCTOR_APPEND_ELT (*p, idx, eltinit);
5537 /* Reuse the result of cxx_eval_constant_expression call
5538 from the first iteration to all others if it is a constant
5539 initializer that doesn't require relocations. */
5540 if (reuse
5541 && max > 1
5542 && (eltinit == NULL_TREE
5543 || (initializer_constant_valid_p (eltinit, TREE_TYPE (eltinit))
5544 == null_pointer_node)))
5546 if (new_ctx.ctor != ctx->ctor)
5547 eltinit = new_ctx.ctor;
5548 tree range = build2 (RANGE_EXPR, size_type_node,
5549 build_int_cst (size_type_node, 1),
5550 build_int_cst (size_type_node, max - 1));
5551 CONSTRUCTOR_APPEND_ELT (*p, range, unshare_constructor (eltinit));
5552 break;
5554 else if (i == 0)
5555 vec_safe_reserve (*p, max);
5558 if (!*non_constant_p)
5560 init = ctx->ctor;
5561 CONSTRUCTOR_NO_CLEARING (init) = false;
5563 return init;
5566 static tree
5567 cxx_eval_vec_init (const constexpr_ctx *ctx, tree t,
5568 value_cat lval,
5569 bool *non_constant_p, bool *overflow_p)
5571 tree atype = TREE_TYPE (t);
5572 tree init = VEC_INIT_EXPR_INIT (t);
5573 bool value_init = VEC_INIT_EXPR_VALUE_INIT (t);
5574 if (!init || !BRACE_ENCLOSED_INITIALIZER_P (init))
5576 else if (CONSTRUCTOR_NELTS (init) == 0
5577 && !CP_AGGREGATE_TYPE_P (strip_array_types (atype)))
5579 /* Handle {} as value-init. */
5580 init = NULL_TREE;
5581 value_init = true;
5583 else
5585 /* This is a more complicated case, like needing to loop over trailing
5586 elements; call build_vec_init and evaluate the result. */
5587 tsubst_flags_t complain = ctx->quiet ? tf_none : tf_warning_or_error;
5588 constexpr_ctx new_ctx = *ctx;
5589 if (!ctx->object)
5591 /* We want to have an initialization target for an VEC_INIT_EXPR.
5592 If we don't already have one in CTX, use the VEC_INIT_EXPR_SLOT. */
5593 new_ctx.object = VEC_INIT_EXPR_SLOT (t);
5594 tree ctor = new_ctx.ctor = build_constructor (atype, NULL);
5595 CONSTRUCTOR_NO_CLEARING (ctor) = true;
5596 ctx->global->put_value (new_ctx.object, ctor);
5597 ctx = &new_ctx;
5599 init = expand_vec_init_expr (ctx->object, t, complain);
5600 return cxx_eval_constant_expression (ctx, init, lval, non_constant_p,
5601 overflow_p);
5603 tree r = cxx_eval_vec_init_1 (ctx, atype, init, value_init,
5604 lval, non_constant_p, overflow_p);
5605 if (*non_constant_p)
5606 return t;
5607 else
5608 return r;
5611 /* Like same_type_ignoring_top_level_qualifiers_p, but also handle the case
5612 where the desired type is an array of unknown bounds because the variable
5613 has had its bounds deduced since the wrapping expression was created. */
5615 static bool
5616 same_type_ignoring_tlq_and_bounds_p (tree type1, tree type2)
5618 while (TREE_CODE (type1) == ARRAY_TYPE
5619 && TREE_CODE (type2) == ARRAY_TYPE
5620 && (!TYPE_DOMAIN (type1) || !TYPE_DOMAIN (type2)))
5622 type1 = TREE_TYPE (type1);
5623 type2 = TREE_TYPE (type2);
5625 return same_type_ignoring_top_level_qualifiers_p (type1, type2);
5628 /* Try to determine the currently active union member for an expression
5629 with UNION_TYPE. If it can be determined, return the FIELD_DECL,
5630 otherwise return NULL_TREE. */
5632 static tree
5633 cxx_union_active_member (const constexpr_ctx *ctx, tree t)
5635 constexpr_ctx new_ctx = *ctx;
5636 new_ctx.quiet = true;
5637 bool non_constant_p = false, overflow_p = false;
5638 tree ctor = cxx_eval_constant_expression (&new_ctx, t, vc_prvalue,
5639 &non_constant_p,
5640 &overflow_p);
5641 if (TREE_CODE (ctor) == CONSTRUCTOR
5642 && CONSTRUCTOR_NELTS (ctor) == 1
5643 && CONSTRUCTOR_ELT (ctor, 0)->index
5644 && TREE_CODE (CONSTRUCTOR_ELT (ctor, 0)->index) == FIELD_DECL)
5645 return CONSTRUCTOR_ELT (ctor, 0)->index;
5646 return NULL_TREE;
5649 /* Helper function for cxx_fold_indirect_ref_1, called recursively. */
5651 static tree
5652 cxx_fold_indirect_ref_1 (const constexpr_ctx *ctx, location_t loc, tree type,
5653 tree op, unsigned HOST_WIDE_INT off, bool *empty_base)
5655 tree optype = TREE_TYPE (op);
5656 unsigned HOST_WIDE_INT const_nunits;
5657 if (off == 0 && similar_type_p (optype, type))
5658 return op;
5659 else if (TREE_CODE (optype) == COMPLEX_TYPE
5660 && similar_type_p (type, TREE_TYPE (optype)))
5662 /* *(foo *)&complexfoo => __real__ complexfoo */
5663 if (off == 0)
5664 return build1_loc (loc, REALPART_EXPR, type, op);
5665 /* ((foo*)&complexfoo)[1] => __imag__ complexfoo */
5666 else if (tree_to_uhwi (TYPE_SIZE_UNIT (type)) == off)
5667 return build1_loc (loc, IMAGPART_EXPR, type, op);
5669 /* ((foo*)&vectorfoo)[x] => BIT_FIELD_REF<vectorfoo,...> */
5670 else if (VECTOR_TYPE_P (optype)
5671 && similar_type_p (type, TREE_TYPE (optype))
5672 && TYPE_VECTOR_SUBPARTS (optype).is_constant (&const_nunits))
5674 unsigned HOST_WIDE_INT part_width = tree_to_uhwi (TYPE_SIZE_UNIT (type));
5675 unsigned HOST_WIDE_INT max_offset = part_width * const_nunits;
5676 if (off < max_offset && off % part_width == 0)
5678 tree index = bitsize_int (off * BITS_PER_UNIT);
5679 return build3_loc (loc, BIT_FIELD_REF, type, op,
5680 TYPE_SIZE (type), index);
5683 /* ((foo *)&fooarray)[x] => fooarray[x] */
5684 else if (TREE_CODE (optype) == ARRAY_TYPE
5685 && tree_fits_uhwi_p (TYPE_SIZE_UNIT (TREE_TYPE (optype)))
5686 && !integer_zerop (TYPE_SIZE_UNIT (TREE_TYPE (optype))))
5688 tree type_domain = TYPE_DOMAIN (optype);
5689 tree min_val = size_zero_node;
5690 if (type_domain && TYPE_MIN_VALUE (type_domain))
5691 min_val = TYPE_MIN_VALUE (type_domain);
5692 unsigned HOST_WIDE_INT el_sz
5693 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (optype)));
5694 unsigned HOST_WIDE_INT idx = off / el_sz;
5695 unsigned HOST_WIDE_INT rem = off % el_sz;
5696 if (tree_fits_uhwi_p (min_val))
5698 tree index = size_int (idx + tree_to_uhwi (min_val));
5699 op = build4_loc (loc, ARRAY_REF, TREE_TYPE (optype), op, index,
5700 NULL_TREE, NULL_TREE);
5701 return cxx_fold_indirect_ref_1 (ctx, loc, type, op, rem,
5702 empty_base);
5705 /* ((foo *)&struct_with_foo_field)[x] => COMPONENT_REF */
5706 else if (TREE_CODE (optype) == RECORD_TYPE
5707 || TREE_CODE (optype) == UNION_TYPE)
5709 if (TREE_CODE (optype) == UNION_TYPE)
5710 /* For unions prefer the currently active member. */
5711 if (tree field = cxx_union_active_member (ctx, op))
5713 unsigned HOST_WIDE_INT el_sz
5714 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (field)));
5715 if (off < el_sz)
5717 tree cop = build3 (COMPONENT_REF, TREE_TYPE (field),
5718 op, field, NULL_TREE);
5719 if (tree ret = cxx_fold_indirect_ref_1 (ctx, loc, type, cop,
5720 off, empty_base))
5721 return ret;
5725 /* Handle conversion to "as base" type. */
5726 if (CLASS_TYPE_P (optype)
5727 && CLASSTYPE_AS_BASE (optype) == type)
5728 return op;
5730 /* Handle conversion to an empty base class, which is represented with a
5731 NOP_EXPR. Do this before spelunking into the non-empty subobjects,
5732 which is likely to be a waste of time (109678). */
5733 if (is_empty_class (type)
5734 && CLASS_TYPE_P (optype)
5735 && lookup_base (optype, type, ba_any, NULL, tf_none, off))
5737 if (empty_base)
5738 *empty_base = true;
5739 return op;
5742 for (tree field = TYPE_FIELDS (optype);
5743 field; field = DECL_CHAIN (field))
5744 if (TREE_CODE (field) == FIELD_DECL
5745 && TREE_TYPE (field) != error_mark_node
5746 && tree_fits_uhwi_p (TYPE_SIZE_UNIT (TREE_TYPE (field))))
5748 tree pos = byte_position (field);
5749 if (!tree_fits_uhwi_p (pos))
5750 continue;
5751 unsigned HOST_WIDE_INT upos = tree_to_uhwi (pos);
5752 unsigned HOST_WIDE_INT el_sz
5753 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (field)));
5754 if (upos <= off && off < upos + el_sz)
5756 tree cop = build3 (COMPONENT_REF, TREE_TYPE (field),
5757 op, field, NULL_TREE);
5758 if (tree ret = cxx_fold_indirect_ref_1 (ctx, loc, type, cop,
5759 off - upos,
5760 empty_base))
5761 return ret;
5766 return NULL_TREE;
5769 /* A less strict version of fold_indirect_ref_1, which requires cv-quals to
5770 match. We want to be less strict for simple *& folding; if we have a
5771 non-const temporary that we access through a const pointer, that should
5772 work. We handle this here rather than change fold_indirect_ref_1
5773 because we're dealing with things like ADDR_EXPR of INTEGER_CST which
5774 don't really make sense outside of constant expression evaluation. Also
5775 we want to allow folding to COMPONENT_REF, which could cause trouble
5776 with TBAA in fold_indirect_ref_1. */
5778 static tree
5779 cxx_fold_indirect_ref (const constexpr_ctx *ctx, location_t loc, tree type,
5780 tree op0, bool *empty_base /* = NULL*/)
5782 tree sub = op0;
5783 tree subtype;
5785 /* STRIP_NOPS, but stop if REINTERPRET_CAST_P. */
5786 while (CONVERT_EXPR_P (sub) || TREE_CODE (sub) == NON_LVALUE_EXPR
5787 || TREE_CODE (sub) == VIEW_CONVERT_EXPR)
5789 if (TREE_CODE (sub) == NOP_EXPR
5790 && REINTERPRET_CAST_P (sub))
5791 return NULL_TREE;
5792 sub = TREE_OPERAND (sub, 0);
5795 subtype = TREE_TYPE (sub);
5796 if (!INDIRECT_TYPE_P (subtype))
5797 return NULL_TREE;
5799 /* Canonicalizes the given OBJ/OFF pair by iteratively absorbing
5800 the innermost component into the offset until it would make the
5801 offset positive, so that cxx_fold_indirect_ref_1 can identify
5802 more folding opportunities. */
5803 auto canonicalize_obj_off = [] (tree& obj, tree& off) {
5804 while (TREE_CODE (obj) == COMPONENT_REF
5805 && (tree_int_cst_sign_bit (off) || integer_zerop (off)))
5807 tree field = TREE_OPERAND (obj, 1);
5808 tree pos = byte_position (field);
5809 if (integer_zerop (off) && integer_nonzerop (pos))
5810 /* If the offset is already 0, keep going as long as the
5811 component is at position 0. */
5812 break;
5813 off = int_const_binop (PLUS_EXPR, off, pos);
5814 obj = TREE_OPERAND (obj, 0);
5818 if (TREE_CODE (sub) == ADDR_EXPR)
5820 tree op = TREE_OPERAND (sub, 0);
5821 tree optype = TREE_TYPE (op);
5823 /* *&CONST_DECL -> to the value of the const decl. */
5824 if (TREE_CODE (op) == CONST_DECL)
5825 return DECL_INITIAL (op);
5826 /* *&p => p; make sure to handle *&"str"[cst] here. */
5827 if (similar_type_p (optype, type))
5829 tree fop = fold_read_from_constant_string (op);
5830 if (fop)
5831 return fop;
5832 else
5833 return op;
5835 else
5837 tree off = integer_zero_node;
5838 canonicalize_obj_off (op, off);
5839 gcc_assert (integer_zerop (off));
5840 return cxx_fold_indirect_ref_1 (ctx, loc, type, op, 0, empty_base);
5843 else if (TREE_CODE (sub) == POINTER_PLUS_EXPR
5844 && tree_fits_uhwi_p (TREE_OPERAND (sub, 1)))
5846 tree op00 = TREE_OPERAND (sub, 0);
5847 tree off = TREE_OPERAND (sub, 1);
5849 STRIP_NOPS (op00);
5850 if (TREE_CODE (op00) == ADDR_EXPR)
5852 tree obj = TREE_OPERAND (op00, 0);
5853 canonicalize_obj_off (obj, off);
5854 return cxx_fold_indirect_ref_1 (ctx, loc, type, obj,
5855 tree_to_uhwi (off), empty_base);
5858 /* *(foo *)fooarrptr => (*fooarrptr)[0] */
5859 else if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
5860 && similar_type_p (type, TREE_TYPE (TREE_TYPE (subtype))))
5862 tree type_domain;
5863 tree min_val = size_zero_node;
5864 tree newsub
5865 = cxx_fold_indirect_ref (ctx, loc, TREE_TYPE (subtype), sub, NULL);
5866 if (newsub)
5867 sub = newsub;
5868 else
5869 sub = build1_loc (loc, INDIRECT_REF, TREE_TYPE (subtype), sub);
5870 type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
5871 if (type_domain && TYPE_MIN_VALUE (type_domain))
5872 min_val = TYPE_MIN_VALUE (type_domain);
5873 return build4_loc (loc, ARRAY_REF, type, sub, min_val, NULL_TREE,
5874 NULL_TREE);
5877 return NULL_TREE;
5880 static tree
5881 cxx_eval_indirect_ref (const constexpr_ctx *ctx, tree t,
5882 value_cat lval,
5883 bool *non_constant_p, bool *overflow_p)
5885 tree orig_op0 = TREE_OPERAND (t, 0);
5886 bool empty_base = false;
5888 /* We can handle a MEM_REF like an INDIRECT_REF, if MEM_REF's second
5889 operand is an integer-zero. Otherwise reject the MEM_REF for now. */
5891 if (TREE_CODE (t) == MEM_REF
5892 && (!TREE_OPERAND (t, 1) || !integer_zerop (TREE_OPERAND (t, 1))))
5894 gcc_assert (ctx->quiet);
5895 *non_constant_p = true;
5896 return t;
5899 /* First try to simplify it directly. */
5900 tree r = cxx_fold_indirect_ref (ctx, EXPR_LOCATION (t), TREE_TYPE (t),
5901 orig_op0, &empty_base);
5902 if (!r)
5904 /* If that didn't work, evaluate the operand first. */
5905 tree op0 = cxx_eval_constant_expression (ctx, orig_op0,
5906 vc_prvalue, non_constant_p,
5907 overflow_p);
5908 /* Don't VERIFY_CONSTANT here. */
5909 if (*non_constant_p)
5910 return t;
5912 if (!lval && integer_zerop (op0))
5914 if (!ctx->quiet)
5915 error ("dereferencing a null pointer");
5916 *non_constant_p = true;
5917 return t;
5920 r = cxx_fold_indirect_ref (ctx, EXPR_LOCATION (t), TREE_TYPE (t), op0,
5921 &empty_base);
5922 if (r == NULL_TREE)
5924 /* We couldn't fold to a constant value. Make sure it's not
5925 something we should have been able to fold. */
5926 tree sub = op0;
5927 STRIP_NOPS (sub);
5928 if (TREE_CODE (sub) == ADDR_EXPR)
5930 gcc_assert (!similar_type_p
5931 (TREE_TYPE (TREE_TYPE (sub)), TREE_TYPE (t)));
5932 /* DR 1188 says we don't have to deal with this. */
5933 if (!ctx->quiet)
5934 error_at (cp_expr_loc_or_input_loc (t),
5935 "accessing value of %qE through a %qT glvalue in a "
5936 "constant expression", build_fold_indirect_ref (sub),
5937 TREE_TYPE (t));
5938 *non_constant_p = true;
5939 return t;
5942 if (lval == vc_glvalue && op0 != orig_op0)
5943 return build1 (INDIRECT_REF, TREE_TYPE (t), op0);
5944 if (!lval)
5945 VERIFY_CONSTANT (t);
5946 return t;
5950 r = cxx_eval_constant_expression (ctx, r,
5951 lval, non_constant_p, overflow_p);
5952 if (*non_constant_p)
5953 return t;
5955 /* If we're pulling out the value of an empty base, just return an empty
5956 CONSTRUCTOR. */
5957 if (empty_base && !lval)
5959 r = build_constructor (TREE_TYPE (t), NULL);
5960 TREE_CONSTANT (r) = true;
5963 return r;
5966 /* Complain about R, a DECL that is accessed outside its lifetime. */
5968 static void
5969 outside_lifetime_error (location_t loc, tree r)
5971 auto_diagnostic_group d;
5972 if (DECL_NAME (r) == heap_deleted_identifier)
5974 /* Provide a more accurate message for deleted variables. */
5975 error_at (loc, "use of allocated storage after deallocation "
5976 "in a constant expression");
5977 inform (DECL_SOURCE_LOCATION (r), "allocated here");
5979 else
5981 error_at (loc, "accessing %qE outside its lifetime", r);
5982 inform (DECL_SOURCE_LOCATION (r), "declared here");
5986 /* Complain about R, a VAR_DECL, not being usable in a constant expression.
5987 FUNDEF_P is true if we're checking a constexpr function body.
5988 Shared between potential_constant_expression and
5989 cxx_eval_constant_expression. */
5991 static void
5992 non_const_var_error (location_t loc, tree r, bool fundef_p)
5994 auto_diagnostic_group d;
5995 tree type = TREE_TYPE (r);
5996 if (DECL_NAME (r) == heap_uninit_identifier
5997 || DECL_NAME (r) == heap_identifier
5998 || DECL_NAME (r) == heap_vec_uninit_identifier
5999 || DECL_NAME (r) == heap_vec_identifier)
6001 if (constexpr_error (loc, fundef_p, "the content of uninitialized "
6002 "storage is not usable in a constant expression"))
6003 inform (DECL_SOURCE_LOCATION (r), "allocated here");
6004 return;
6006 if (DECL_NAME (r) == heap_deleted_identifier)
6008 if (constexpr_error (loc, fundef_p, "use of allocated storage after "
6009 "deallocation in a constant expression"))
6010 inform (DECL_SOURCE_LOCATION (r), "allocated here");
6011 return;
6013 if (!constexpr_error (loc, fundef_p, "the value of %qD is not usable in "
6014 "a constant expression", r))
6015 return;
6016 /* Avoid error cascade. */
6017 if (DECL_INITIAL (r) == error_mark_node)
6018 return;
6019 if (DECL_DECLARED_CONSTEXPR_P (r))
6020 inform (DECL_SOURCE_LOCATION (r),
6021 "%qD used in its own initializer", r);
6022 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
6024 if (!CP_TYPE_CONST_P (type))
6025 inform (DECL_SOURCE_LOCATION (r),
6026 "%q#D is not const", r);
6027 else if (CP_TYPE_VOLATILE_P (type))
6028 inform (DECL_SOURCE_LOCATION (r),
6029 "%q#D is volatile", r);
6030 else if (!DECL_INITIAL (r)
6031 || !TREE_CONSTANT (DECL_INITIAL (r))
6032 || !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r))
6033 inform (DECL_SOURCE_LOCATION (r),
6034 "%qD was not initialized with a constant "
6035 "expression", r);
6036 else
6037 gcc_unreachable ();
6039 else if (TYPE_REF_P (type))
6040 inform (DECL_SOURCE_LOCATION (r),
6041 "%qD was not initialized with a constant "
6042 "expression", r);
6043 else
6045 if (cxx_dialect >= cxx11 && !DECL_DECLARED_CONSTEXPR_P (r))
6046 inform (DECL_SOURCE_LOCATION (r),
6047 "%qD was not declared %<constexpr%>", r);
6048 else
6049 inform (DECL_SOURCE_LOCATION (r),
6050 "%qD does not have integral or enumeration type",
6055 /* Subroutine of cxx_eval_constant_expression.
6056 Like cxx_eval_unary_expression, except for trinary expressions. */
6058 static tree
6059 cxx_eval_trinary_expression (const constexpr_ctx *ctx, tree t,
6060 value_cat lval,
6061 bool *non_constant_p, bool *overflow_p)
6063 int i;
6064 tree args[3];
6065 tree val;
6067 for (i = 0; i < 3; i++)
6069 args[i] = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, i),
6070 lval,
6071 non_constant_p, overflow_p);
6072 VERIFY_CONSTANT (args[i]);
6075 val = fold_ternary_loc (EXPR_LOCATION (t), TREE_CODE (t), TREE_TYPE (t),
6076 args[0], args[1], args[2]);
6077 if (val == NULL_TREE)
6078 return t;
6079 VERIFY_CONSTANT (val);
6080 return val;
6083 /* True if T was declared in a function declared to be constexpr, and
6084 therefore potentially constant in C++14. */
6086 bool
6087 var_in_constexpr_fn (tree t)
6089 tree ctx = DECL_CONTEXT (t);
6090 return (ctx && TREE_CODE (ctx) == FUNCTION_DECL
6091 && DECL_DECLARED_CONSTEXPR_P (ctx));
6094 /* True if a function might be constexpr: either a function that was
6095 declared constexpr, or a C++17 lambda op(). */
6097 bool
6098 maybe_constexpr_fn (tree t)
6100 return (DECL_DECLARED_CONSTEXPR_P (t)
6101 || (cxx_dialect >= cxx17 && LAMBDA_FUNCTION_P (t))
6102 || (flag_implicit_constexpr
6103 && DECL_DECLARED_INLINE_P (STRIP_TEMPLATE (t))));
6106 /* True if T was declared in a function that might be constexpr: either a
6107 function that was declared constexpr, or a C++17 lambda op(). */
6109 bool
6110 var_in_maybe_constexpr_fn (tree t)
6112 return (DECL_FUNCTION_SCOPE_P (t)
6113 && maybe_constexpr_fn (DECL_CONTEXT (t)));
6116 /* We're assigning INIT to TARGET. In do_build_copy_constructor and
6117 build_over_call we implement trivial copy of a class with tail padding using
6118 assignment of character arrays, which is valid in normal code, but not in
6119 constexpr evaluation. We don't need to worry about clobbering tail padding
6120 in constexpr evaluation, so strip the type punning. */
6122 static void
6123 maybe_simplify_trivial_copy (tree &target, tree &init)
6125 if (TREE_CODE (target) == MEM_REF
6126 && TREE_CODE (init) == MEM_REF
6127 && TREE_TYPE (target) == TREE_TYPE (init)
6128 && TREE_CODE (TREE_TYPE (target)) == ARRAY_TYPE
6129 && TREE_TYPE (TREE_TYPE (target)) == unsigned_char_type_node)
6131 target = build_fold_indirect_ref (TREE_OPERAND (target, 0));
6132 init = build_fold_indirect_ref (TREE_OPERAND (init, 0));
6136 /* Returns true if REF, which is a COMPONENT_REF, has any fields
6137 of constant type. This does not check for 'mutable', so the
6138 caller is expected to be mindful of that. */
6140 static bool
6141 cref_has_const_field (tree ref)
6143 while (TREE_CODE (ref) == COMPONENT_REF)
6145 if (CP_TYPE_CONST_P (TREE_TYPE (TREE_OPERAND (ref, 1))))
6146 return true;
6147 ref = TREE_OPERAND (ref, 0);
6149 return false;
6152 /* Return true if we are modifying something that is const during constant
6153 expression evaluation. CODE is the code of the statement, OBJ is the
6154 object in question, MUTABLE_P is true if one of the subobjects were
6155 declared mutable. */
6157 static bool
6158 modifying_const_object_p (tree_code code, tree obj, bool mutable_p)
6160 /* If this is initialization, there's no problem. */
6161 if (code != MODIFY_EXPR)
6162 return false;
6164 /* [basic.type.qualifier] "A const object is an object of type
6165 const T or a non-mutable subobject of a const object." */
6166 if (mutable_p)
6167 return false;
6169 if (TREE_READONLY (obj))
6170 return true;
6172 if (CP_TYPE_CONST_P (TREE_TYPE (obj)))
6174 /* Although a COMPONENT_REF may have a const type, we should
6175 only consider it modifying a const object when any of the
6176 field components is const. This can happen when using
6177 constructs such as const_cast<const T &>(m), making something
6178 const even though it wasn't declared const. */
6179 if (TREE_CODE (obj) == COMPONENT_REF)
6180 return cref_has_const_field (obj);
6181 else
6182 return true;
6185 return false;
6188 /* Evaluate an INIT_EXPR or MODIFY_EXPR. */
6190 static tree
6191 cxx_eval_store_expression (const constexpr_ctx *ctx, tree t,
6192 value_cat lval,
6193 bool *non_constant_p, bool *overflow_p)
6195 constexpr_ctx new_ctx = *ctx;
6197 tree init = TREE_OPERAND (t, 1);
6199 if (TREE_CLOBBER_P (init)
6200 && CLOBBER_KIND (init) < CLOBBER_OBJECT_END)
6201 /* Only handle clobbers ending the lifetime of objects. */
6202 return void_node;
6204 /* First we figure out where we're storing to. */
6205 tree target = TREE_OPERAND (t, 0);
6207 maybe_simplify_trivial_copy (target, init);
6209 tree type = TREE_TYPE (target);
6210 bool preeval = SCALAR_TYPE_P (type) || TREE_CODE (t) == MODIFY_EXPR;
6211 if (preeval && !TREE_CLOBBER_P (init))
6213 /* Evaluate the value to be stored without knowing what object it will be
6214 stored in, so that any side-effects happen first. */
6215 if (!SCALAR_TYPE_P (type))
6216 new_ctx.ctor = new_ctx.object = NULL_TREE;
6217 init = cxx_eval_constant_expression (&new_ctx, init, vc_prvalue,
6218 non_constant_p, overflow_p);
6219 if (*non_constant_p)
6220 return t;
6223 bool evaluated = false;
6224 if (lval == vc_glvalue)
6226 /* If we want to return a reference to the target, we need to evaluate it
6227 as a whole; otherwise, only evaluate the innermost piece to avoid
6228 building up unnecessary *_REFs. */
6229 target = cxx_eval_constant_expression (ctx, target, lval,
6230 non_constant_p, overflow_p);
6231 evaluated = true;
6232 if (*non_constant_p)
6233 return t;
6236 /* Find the underlying variable. */
6237 releasing_vec refs;
6238 tree object = NULL_TREE;
6239 /* If we're modifying a const object, save it. */
6240 tree const_object_being_modified = NULL_TREE;
6241 bool mutable_p = false;
6242 for (tree probe = target; object == NULL_TREE; )
6244 switch (TREE_CODE (probe))
6246 case BIT_FIELD_REF:
6247 case COMPONENT_REF:
6248 case ARRAY_REF:
6250 tree ob = TREE_OPERAND (probe, 0);
6251 tree elt = TREE_OPERAND (probe, 1);
6252 if (TREE_CODE (elt) == FIELD_DECL && DECL_MUTABLE_P (elt))
6253 mutable_p = true;
6254 if (TREE_CODE (probe) == ARRAY_REF)
6256 elt = eval_and_check_array_index (ctx, probe, false,
6257 non_constant_p, overflow_p);
6258 if (*non_constant_p)
6259 return t;
6261 /* We don't check modifying_const_object_p for ARRAY_REFs. Given
6262 "int a[10]", an ARRAY_REF "a[2]" can be "const int", even though
6263 the array isn't const. Instead, check "a" in the next iteration;
6264 that will detect modifying "const int a[10]". */
6265 else if (evaluated
6266 && modifying_const_object_p (TREE_CODE (t), probe,
6267 mutable_p)
6268 && const_object_being_modified == NULL_TREE)
6269 const_object_being_modified = probe;
6271 /* Track named member accesses for unions to validate modifications
6272 that change active member. */
6273 if (!evaluated && TREE_CODE (probe) == COMPONENT_REF)
6274 vec_safe_push (refs, probe);
6275 else
6276 vec_safe_push (refs, NULL_TREE);
6278 vec_safe_push (refs, elt);
6279 vec_safe_push (refs, TREE_TYPE (probe));
6280 probe = ob;
6282 break;
6284 case REALPART_EXPR:
6285 gcc_assert (probe == target);
6286 vec_safe_push (refs, NULL_TREE);
6287 vec_safe_push (refs, probe);
6288 vec_safe_push (refs, TREE_TYPE (probe));
6289 probe = TREE_OPERAND (probe, 0);
6290 break;
6292 case IMAGPART_EXPR:
6293 gcc_assert (probe == target);
6294 vec_safe_push (refs, NULL_TREE);
6295 vec_safe_push (refs, probe);
6296 vec_safe_push (refs, TREE_TYPE (probe));
6297 probe = TREE_OPERAND (probe, 0);
6298 break;
6300 default:
6301 if (evaluated)
6302 object = probe;
6303 else
6305 probe = cxx_eval_constant_expression (ctx, probe, vc_glvalue,
6306 non_constant_p, overflow_p);
6307 evaluated = true;
6308 if (*non_constant_p)
6309 return t;
6311 break;
6315 if (modifying_const_object_p (TREE_CODE (t), object, mutable_p)
6316 && const_object_being_modified == NULL_TREE)
6317 const_object_being_modified = object;
6319 if (DECL_P (object)
6320 && TREE_CLOBBER_P (init)
6321 && DECL_NAME (object) == heap_deleted_identifier)
6322 /* Ignore clobbers of deleted allocations for now; we'll get a better error
6323 message later when operator delete is called. */
6324 return void_node;
6326 /* And then find/build up our initializer for the path to the subobject
6327 we're initializing. */
6328 tree *valp;
6329 if (DECL_P (object))
6330 valp = ctx->global->get_value_ptr (object, TREE_CODE (t) == INIT_EXPR);
6331 else
6332 valp = NULL;
6333 if (!valp)
6335 /* A constant-expression cannot modify objects from outside the
6336 constant-expression. */
6337 if (!ctx->quiet)
6339 auto_diagnostic_group d;
6340 if (DECL_P (object) && DECL_NAME (object) == heap_deleted_identifier)
6342 error ("modification of allocated storage after deallocation "
6343 "is not a constant expression");
6344 inform (DECL_SOURCE_LOCATION (object), "allocated here");
6346 else if (DECL_P (object) && ctx->global->is_outside_lifetime (object))
6348 if (TREE_CLOBBER_P (init))
6349 error ("destroying %qE outside its lifetime", object);
6350 else
6351 error ("modification of %qE outside its lifetime "
6352 "is not a constant expression", object);
6353 inform (DECL_SOURCE_LOCATION (object), "declared here");
6355 else
6357 if (TREE_CLOBBER_P (init))
6358 error ("destroying %qE from outside current evaluation "
6359 "is not a constant expression", object);
6360 else
6361 error ("modification of %qE from outside current evaluation "
6362 "is not a constant expression", object);
6365 *non_constant_p = true;
6366 return t;
6369 /* Handle explicit end-of-lifetime. */
6370 if (TREE_CLOBBER_P (init))
6372 if (refs->is_empty ())
6373 ctx->global->destroy_value (object);
6374 return void_node;
6377 type = TREE_TYPE (object);
6378 bool no_zero_init = true;
6380 auto_vec<tree *> ctors;
6381 releasing_vec indexes;
6382 auto_vec<int> index_pos_hints;
6383 bool activated_union_member_p = false;
6384 bool empty_base = false;
6385 while (!refs->is_empty ())
6387 if (*valp == NULL_TREE)
6389 *valp = build_constructor (type, NULL);
6390 CONSTRUCTOR_NO_CLEARING (*valp) = no_zero_init;
6392 else if (STRIP_ANY_LOCATION_WRAPPER (*valp),
6393 TREE_CODE (*valp) == STRING_CST)
6395 /* An array was initialized with a string constant, and now
6396 we're writing into one of its elements. Explode the
6397 single initialization into a set of element
6398 initializations. */
6399 gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
6401 tree string = *valp;
6402 tree elt_type = TREE_TYPE (type);
6403 unsigned chars_per_elt = (TYPE_PRECISION (elt_type)
6404 / TYPE_PRECISION (char_type_node));
6405 unsigned num_elts = TREE_STRING_LENGTH (string) / chars_per_elt;
6406 tree ary_ctor = build_constructor (type, NULL);
6408 vec_safe_reserve (CONSTRUCTOR_ELTS (ary_ctor), num_elts);
6409 for (unsigned ix = 0; ix != num_elts; ix++)
6411 constructor_elt elt =
6413 build_int_cst (size_type_node, ix),
6414 extract_string_elt (string, chars_per_elt, ix)
6416 CONSTRUCTOR_ELTS (ary_ctor)->quick_push (elt);
6419 *valp = ary_ctor;
6422 enum tree_code code = TREE_CODE (type);
6423 tree reftype = refs->pop();
6424 tree index = refs->pop();
6425 bool is_access_expr = refs->pop() != NULL_TREE;
6427 if (code == COMPLEX_TYPE)
6429 if (TREE_CODE (*valp) == COMPLEX_CST)
6430 *valp = build2 (COMPLEX_EXPR, type, TREE_REALPART (*valp),
6431 TREE_IMAGPART (*valp));
6432 else if (TREE_CODE (*valp) == CONSTRUCTOR
6433 && CONSTRUCTOR_NELTS (*valp) == 0
6434 && CONSTRUCTOR_NO_CLEARING (*valp))
6436 tree r = build_constructor (reftype, NULL);
6437 CONSTRUCTOR_NO_CLEARING (r) = 1;
6438 *valp = build2 (COMPLEX_EXPR, type, r, r);
6440 gcc_assert (TREE_CODE (*valp) == COMPLEX_EXPR);
6441 ctors.safe_push (valp);
6442 vec_safe_push (indexes, index);
6443 valp = &TREE_OPERAND (*valp, TREE_CODE (index) == IMAGPART_EXPR);
6444 gcc_checking_assert (refs->is_empty ());
6445 type = reftype;
6446 break;
6449 /* If the value of object is already zero-initialized, any new ctors for
6450 subobjects will also be zero-initialized. */
6451 no_zero_init = CONSTRUCTOR_NO_CLEARING (*valp);
6453 if (code == RECORD_TYPE && is_empty_field (index))
6454 /* Don't build a sub-CONSTRUCTOR for an empty base or field, as they
6455 have no data and might have an offset lower than previously declared
6456 fields, which confuses the middle-end. The code below will notice
6457 that we don't have a CONSTRUCTOR for our inner target and just
6458 return init. */
6460 empty_base = true;
6461 break;
6464 /* If a union is zero-initialized, its first non-static named data member
6465 is zero-initialized (and therefore active). */
6466 if (code == UNION_TYPE
6467 && !no_zero_init
6468 && CONSTRUCTOR_NELTS (*valp) == 0)
6469 if (tree first = next_aggregate_field (TYPE_FIELDS (type)))
6470 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (*valp), first, NULL_TREE);
6472 /* Check for implicit change of active member for a union. */
6473 if (code == UNION_TYPE
6474 && (CONSTRUCTOR_NELTS (*valp) == 0
6475 || CONSTRUCTOR_ELT (*valp, 0)->index != index)
6476 /* An INIT_EXPR of the last member in an access chain is always OK,
6477 but still check implicit change of members earlier on; see
6478 cpp2a/constexpr-union6.C. */
6479 && !(TREE_CODE (t) == INIT_EXPR && refs->is_empty ()))
6481 bool has_active_member = CONSTRUCTOR_NELTS (*valp) != 0;
6482 tree inner = strip_array_types (reftype);
6484 if (has_active_member && cxx_dialect < cxx20)
6486 if (!ctx->quiet)
6487 error_at (cp_expr_loc_or_input_loc (t),
6488 "change of the active member of a union "
6489 "from %qD to %qD is not a constant expression "
6490 "before C++20",
6491 CONSTRUCTOR_ELT (*valp, 0)->index,
6492 index);
6493 *non_constant_p = true;
6495 else if (!is_access_expr
6496 || (TREE_CODE (t) == MODIFY_EXPR
6497 && CLASS_TYPE_P (inner)
6498 && !type_has_non_deleted_trivial_default_ctor (inner)))
6500 /* Diagnose changing active union member after initialization
6501 without a valid member access expression, as described in
6502 [class.union.general] p5. */
6503 if (!ctx->quiet)
6505 auto_diagnostic_group d;
6506 if (has_active_member)
6507 error_at (cp_expr_loc_or_input_loc (t),
6508 "accessing %qD member instead of initialized "
6509 "%qD member in constant expression",
6510 index, CONSTRUCTOR_ELT (*valp, 0)->index);
6511 else
6512 error_at (cp_expr_loc_or_input_loc (t),
6513 "accessing uninitialized member %qD",
6514 index);
6515 if (is_access_expr)
6516 inform (DECL_SOURCE_LOCATION (index),
6517 "%qD does not implicitly begin its lifetime "
6518 "because %qT does not have a non-deleted "
6519 "trivial default constructor, use "
6520 "%<std::construct_at%> instead",
6521 index, inner);
6522 else
6523 inform (DECL_SOURCE_LOCATION (index),
6524 "initializing %qD requires a member access "
6525 "expression as the left operand of the assignment",
6526 index);
6528 *non_constant_p = true;
6530 else if (has_active_member && CONSTRUCTOR_NO_CLEARING (*valp))
6532 /* Diagnose changing the active union member while the union
6533 is in the process of being initialized. */
6534 if (!ctx->quiet)
6535 error_at (cp_expr_loc_or_input_loc (t),
6536 "change of the active member of a union "
6537 "from %qD to %qD during initialization",
6538 CONSTRUCTOR_ELT (*valp, 0)->index,
6539 index);
6540 *non_constant_p = true;
6542 no_zero_init = true;
6545 ctors.safe_push (valp);
6546 vec_safe_push (indexes, index);
6548 constructor_elt *cep
6549 = get_or_insert_ctor_field (*valp, index);
6550 index_pos_hints.safe_push (cep - CONSTRUCTOR_ELTS (*valp)->begin());
6552 if (code == UNION_TYPE)
6553 activated_union_member_p = true;
6555 valp = &cep->value;
6556 type = reftype;
6559 /* For initialization of an empty base, the original target will be
6560 *(base*)this, evaluation of which resolves to the object
6561 argument, which has the derived type rather than the base type. */
6562 if (!empty_base && !(same_type_ignoring_top_level_qualifiers_p
6563 (initialized_type (init), type)))
6565 gcc_assert (is_empty_class (TREE_TYPE (target)));
6566 empty_base = true;
6569 /* Detect modifying a constant object in constexpr evaluation.
6570 We have found a const object that is being modified. Figure out
6571 if we need to issue an error. Consider
6573 struct A {
6574 int n;
6575 constexpr A() : n(1) { n = 2; } // #1
6577 struct B {
6578 const A a;
6579 constexpr B() { a.n = 3; } // #2
6581 constexpr B b{};
6583 #1 is OK, since we're modifying an object under construction, but
6584 #2 is wrong, since "a" is const and has been fully constructed.
6585 To track it, we use the TREE_READONLY bit in the object's CONSTRUCTOR
6586 which means that the object is read-only. For the example above, the
6587 *ctors stack at the point of #2 will look like:
6589 ctors[0] = {.a={.n=2}} TREE_READONLY = 0
6590 ctors[1] = {.n=2} TREE_READONLY = 1
6592 and we're modifying "b.a", so we search the stack and see if the
6593 constructor for "b.a" has already run. */
6594 if (const_object_being_modified)
6596 bool fail = false;
6597 tree const_objtype
6598 = strip_array_types (TREE_TYPE (const_object_being_modified));
6599 if (!CLASS_TYPE_P (const_objtype))
6600 fail = true;
6601 else
6603 /* [class.ctor]p5 "A constructor can be invoked for a const,
6604 volatile, or const volatile object. const and volatile
6605 semantics are not applied on an object under construction.
6606 They come into effect when the constructor for the most
6607 derived object ends." */
6608 for (tree *elt : ctors)
6609 if (same_type_ignoring_top_level_qualifiers_p
6610 (TREE_TYPE (const_object_being_modified), TREE_TYPE (*elt)))
6612 fail = TREE_READONLY (*elt);
6613 break;
6616 if (fail)
6618 if (!ctx->quiet)
6619 modifying_const_object_error (t, const_object_being_modified);
6620 *non_constant_p = true;
6621 return t;
6625 if (!preeval)
6627 /* We're handling an INIT_EXPR of class type, so the value of the
6628 initializer can depend on the object it's initializing. */
6630 /* Create a new CONSTRUCTOR in case evaluation of the initializer
6631 wants to modify it. */
6632 if (*valp == NULL_TREE)
6634 *valp = build_constructor (type, NULL);
6635 CONSTRUCTOR_NO_CLEARING (*valp) = no_zero_init;
6637 new_ctx.ctor = empty_base ? NULL_TREE : *valp;
6638 new_ctx.object = target;
6639 /* Avoid temporary materialization when initializing from a TARGET_EXPR.
6640 We don't need to mess with AGGR_EXPR_SLOT/VEC_INIT_EXPR_SLOT because
6641 expansion of those trees uses ctx instead. */
6642 if (TREE_CODE (init) == TARGET_EXPR)
6643 if (tree tinit = TARGET_EXPR_INITIAL (init))
6644 init = tinit;
6645 init = cxx_eval_constant_expression (&new_ctx, init, vc_prvalue,
6646 non_constant_p, overflow_p);
6647 /* The hash table might have moved since the get earlier, and the
6648 initializer might have mutated the underlying CONSTRUCTORs, so we must
6649 recompute VALP. */
6650 valp = ctx->global->get_value_ptr (object, TREE_CODE (t) == INIT_EXPR);
6651 for (unsigned i = 0; i < vec_safe_length (indexes); i++)
6653 ctors[i] = valp;
6654 constructor_elt *cep
6655 = get_or_insert_ctor_field (*valp, indexes[i], index_pos_hints[i]);
6656 valp = &cep->value;
6660 if (*non_constant_p)
6661 return t;
6663 /* Don't share a CONSTRUCTOR that might be changed later. */
6664 init = unshare_constructor (init);
6666 gcc_checking_assert (!*valp || (same_type_ignoring_top_level_qualifiers_p
6667 (TREE_TYPE (*valp), type)));
6668 if (empty_base)
6670 /* Just evaluate the initializer and return, since there's no actual data
6671 to store, and we didn't build a CONSTRUCTOR. */
6672 if (!*valp)
6674 /* But do make sure we have something in *valp. */
6675 *valp = build_constructor (type, nullptr);
6676 CONSTRUCTOR_NO_CLEARING (*valp) = no_zero_init;
6679 else if (*valp && TREE_CODE (*valp) == CONSTRUCTOR
6680 && TREE_CODE (init) == CONSTRUCTOR)
6682 /* An outer ctx->ctor might be pointing to *valp, so replace
6683 its contents. */
6684 CONSTRUCTOR_ELTS (*valp) = CONSTRUCTOR_ELTS (init);
6685 TREE_CONSTANT (*valp) = TREE_CONSTANT (init);
6686 TREE_SIDE_EFFECTS (*valp) = TREE_SIDE_EFFECTS (init);
6687 CONSTRUCTOR_NO_CLEARING (*valp)
6688 = CONSTRUCTOR_NO_CLEARING (init);
6690 else
6691 *valp = init;
6693 /* After initialization, 'const' semantics apply to the value of the
6694 object. Make a note of this fact by marking the CONSTRUCTOR
6695 TREE_READONLY. */
6696 if (TREE_CODE (t) == INIT_EXPR
6697 && TREE_CODE (*valp) == CONSTRUCTOR
6698 && TYPE_READONLY (type))
6700 if (INDIRECT_REF_P (target)
6701 && (is_this_parameter
6702 (tree_strip_nop_conversions (TREE_OPERAND (target, 0)))))
6703 /* We've just initialized '*this' (perhaps via the target
6704 constructor of a delegating constructor). Leave it up to the
6705 caller that set 'this' to set TREE_READONLY appropriately. */
6706 gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
6707 (TREE_TYPE (target), type) || empty_base);
6708 else
6709 TREE_READONLY (*valp) = true;
6712 /* Update TREE_CONSTANT and TREE_SIDE_EFFECTS on enclosing
6713 CONSTRUCTORs, if any. */
6714 bool c = TREE_CONSTANT (init);
6715 bool s = TREE_SIDE_EFFECTS (init);
6716 if (!indexes->is_empty ())
6718 tree last = indexes->last ();
6719 if (TREE_CODE (last) == REALPART_EXPR
6720 || TREE_CODE (last) == IMAGPART_EXPR)
6722 /* And canonicalize COMPLEX_EXPR into COMPLEX_CST if
6723 possible. */
6724 tree *cexpr = ctors.last ();
6725 if (tree c = const_binop (COMPLEX_EXPR, TREE_TYPE (*cexpr),
6726 TREE_OPERAND (*cexpr, 0),
6727 TREE_OPERAND (*cexpr, 1)))
6728 *cexpr = c;
6729 else
6731 TREE_CONSTANT (*cexpr)
6732 = (TREE_CONSTANT (TREE_OPERAND (*cexpr, 0))
6733 & TREE_CONSTANT (TREE_OPERAND (*cexpr, 1)));
6734 TREE_SIDE_EFFECTS (*cexpr)
6735 = (TREE_SIDE_EFFECTS (TREE_OPERAND (*cexpr, 0))
6736 | TREE_SIDE_EFFECTS (TREE_OPERAND (*cexpr, 1)));
6738 c = TREE_CONSTANT (*cexpr);
6739 s = TREE_SIDE_EFFECTS (*cexpr);
6742 if (!c || s || activated_union_member_p)
6743 for (tree *elt : ctors)
6745 if (TREE_CODE (*elt) != CONSTRUCTOR)
6746 continue;
6747 if (!c)
6748 TREE_CONSTANT (*elt) = false;
6749 if (s)
6750 TREE_SIDE_EFFECTS (*elt) = true;
6751 /* Clear CONSTRUCTOR_NO_CLEARING since we've activated a member of
6752 this union. */
6753 if (TREE_CODE (TREE_TYPE (*elt)) == UNION_TYPE)
6754 CONSTRUCTOR_NO_CLEARING (*elt) = false;
6757 if (lval)
6758 return target;
6759 else
6760 return init;
6763 /* Evaluate a ++ or -- expression. */
6765 static tree
6766 cxx_eval_increment_expression (const constexpr_ctx *ctx, tree t,
6767 value_cat lval,
6768 bool *non_constant_p, bool *overflow_p)
6770 enum tree_code code = TREE_CODE (t);
6771 tree type = TREE_TYPE (t);
6772 tree op = TREE_OPERAND (t, 0);
6773 tree offset = TREE_OPERAND (t, 1);
6774 gcc_assert (TREE_CONSTANT (offset));
6776 /* OFFSET is constant, but perhaps not constant enough. We need to
6777 e.g. bash FLOAT_EXPRs to REAL_CSTs. */
6778 offset = fold_simple (offset);
6780 /* The operand as an lvalue. */
6781 op = cxx_eval_constant_expression (ctx, op, vc_glvalue,
6782 non_constant_p, overflow_p);
6784 /* The operand as an rvalue. */
6785 tree val
6786 = cxx_eval_constant_expression (ctx, op, vc_prvalue,
6787 non_constant_p, overflow_p);
6788 /* Don't VERIFY_CONSTANT if this might be dealing with a pointer to
6789 a local array in a constexpr function. */
6790 bool ptr = INDIRECT_TYPE_P (TREE_TYPE (val));
6791 if (!ptr)
6792 VERIFY_CONSTANT (val);
6794 /* The modified value. */
6795 bool inc = (code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR);
6796 tree mod;
6797 if (INDIRECT_TYPE_P (type))
6799 /* The middle end requires pointers to use POINTER_PLUS_EXPR. */
6800 offset = convert_to_ptrofftype (offset);
6801 if (!inc)
6802 offset = fold_build1 (NEGATE_EXPR, TREE_TYPE (offset), offset);
6803 mod = fold_build2 (POINTER_PLUS_EXPR, type, val, offset);
6805 else if (c_promoting_integer_type_p (type)
6806 && !TYPE_UNSIGNED (type)
6807 && TYPE_PRECISION (type) < TYPE_PRECISION (integer_type_node))
6809 offset = fold_convert (integer_type_node, offset);
6810 mod = fold_convert (integer_type_node, val);
6811 tree t = fold_build2 (inc ? PLUS_EXPR : MINUS_EXPR, integer_type_node,
6812 mod, offset);
6813 mod = fold_convert (type, t);
6814 if (TREE_OVERFLOW_P (mod) && !TREE_OVERFLOW_P (t))
6815 TREE_OVERFLOW (mod) = false;
6817 else
6818 mod = fold_build2 (inc ? PLUS_EXPR : MINUS_EXPR, type, val, offset);
6819 if (!ptr)
6820 VERIFY_CONSTANT (mod);
6822 /* Storing the modified value. */
6823 tree store = build2_loc (cp_expr_loc_or_loc (t, input_location),
6824 MODIFY_EXPR, type, op, mod);
6825 mod = cxx_eval_constant_expression (ctx, store, lval,
6826 non_constant_p, overflow_p);
6827 ggc_free (store);
6828 if (*non_constant_p)
6829 return t;
6831 /* And the value of the expression. */
6832 if (code == PREINCREMENT_EXPR || code == PREDECREMENT_EXPR)
6833 /* Prefix ops are lvalues, but the caller might want an rvalue;
6834 lval has already been taken into account in the store above. */
6835 return mod;
6836 else
6837 /* Postfix ops are rvalues. */
6838 return val;
6841 /* Predicates for the meaning of *jump_target. */
6843 static bool
6844 returns (tree *jump_target)
6846 return *jump_target
6847 && TREE_CODE (*jump_target) == RETURN_EXPR;
6850 static bool
6851 breaks (tree *jump_target)
6853 return *jump_target
6854 && ((TREE_CODE (*jump_target) == LABEL_DECL
6855 && LABEL_DECL_BREAK (*jump_target))
6856 || TREE_CODE (*jump_target) == BREAK_STMT
6857 || TREE_CODE (*jump_target) == EXIT_EXPR);
6860 static bool
6861 continues (tree *jump_target)
6863 return *jump_target
6864 && ((TREE_CODE (*jump_target) == LABEL_DECL
6865 && LABEL_DECL_CONTINUE (*jump_target))
6866 || TREE_CODE (*jump_target) == CONTINUE_STMT);
6870 static bool
6871 switches (tree *jump_target)
6873 return *jump_target
6874 && TREE_CODE (*jump_target) == INTEGER_CST;
6877 /* Subroutine of cxx_eval_statement_list. Determine whether the statement
6878 STMT matches *jump_target. If we're looking for a case label and we see
6879 the default label, note it in ctx->css_state. */
6881 static bool
6882 label_matches (const constexpr_ctx *ctx, tree *jump_target, tree stmt)
6884 switch (TREE_CODE (*jump_target))
6886 case LABEL_DECL:
6887 if (TREE_CODE (stmt) == LABEL_EXPR
6888 && LABEL_EXPR_LABEL (stmt) == *jump_target)
6889 return true;
6890 break;
6892 case INTEGER_CST:
6893 if (TREE_CODE (stmt) == CASE_LABEL_EXPR)
6895 gcc_assert (ctx->css_state != NULL);
6896 if (!CASE_LOW (stmt))
6898 /* default: should appear just once in a SWITCH_EXPR
6899 body (excluding nested SWITCH_EXPR). */
6900 gcc_assert (*ctx->css_state != css_default_seen);
6901 /* When evaluating SWITCH_EXPR body for the second time,
6902 return true for the default: label. */
6903 if (*ctx->css_state == css_default_processing)
6904 return true;
6905 *ctx->css_state = css_default_seen;
6907 else if (CASE_HIGH (stmt))
6909 if (tree_int_cst_le (CASE_LOW (stmt), *jump_target)
6910 && tree_int_cst_le (*jump_target, CASE_HIGH (stmt)))
6911 return true;
6913 else if (tree_int_cst_equal (*jump_target, CASE_LOW (stmt)))
6914 return true;
6916 break;
6918 case BREAK_STMT:
6919 case CONTINUE_STMT:
6920 /* These two are handled directly in cxx_eval_loop_expr by testing
6921 breaks (jump_target) or continues (jump_target). */
6922 break;
6924 default:
6925 gcc_unreachable ();
6927 return false;
6930 /* Evaluate a STATEMENT_LIST for side-effects. Handles various jump
6931 semantics, for switch, break, continue, and return. */
6933 static tree
6934 cxx_eval_statement_list (const constexpr_ctx *ctx, tree t,
6935 bool *non_constant_p, bool *overflow_p,
6936 tree *jump_target)
6938 tree local_target;
6939 /* In a statement-expression we want to return the last value.
6940 For empty statement expression return void_node. */
6941 tree r = void_node;
6942 if (!jump_target)
6944 local_target = NULL_TREE;
6945 jump_target = &local_target;
6947 for (tree_stmt_iterator i = tsi_start (t); !tsi_end_p (i); ++i)
6949 tree stmt = *i;
6951 /* We've found a continue, so skip everything until we reach
6952 the label its jumping to. */
6953 if (continues (jump_target))
6955 if (label_matches (ctx, jump_target, stmt))
6956 /* Found it. */
6957 *jump_target = NULL_TREE;
6958 else
6959 continue;
6961 if (TREE_CODE (stmt) == DEBUG_BEGIN_STMT)
6962 continue;
6964 value_cat lval = vc_discard;
6965 /* The result of a statement-expression is not wrapped in EXPR_STMT. */
6966 if (tsi_one_before_end_p (i) && TREE_CODE (stmt) != EXPR_STMT)
6967 lval = vc_prvalue;
6969 r = cxx_eval_constant_expression (ctx, stmt, lval,
6970 non_constant_p, overflow_p,
6971 jump_target);
6972 if (*non_constant_p)
6973 break;
6974 if (returns (jump_target) || breaks (jump_target))
6975 break;
6977 if (*jump_target && jump_target == &local_target)
6979 /* We aren't communicating the jump to our caller, so give up. We don't
6980 need to support evaluation of jumps out of statement-exprs. */
6981 if (!ctx->quiet)
6982 error_at (cp_expr_loc_or_input_loc (r),
6983 "statement is not a constant expression");
6984 *non_constant_p = true;
6986 return r;
6989 /* Evaluate a LOOP_EXPR for side-effects. Handles break and return
6990 semantics; continue semantics are covered by cxx_eval_statement_list. */
6992 static tree
6993 cxx_eval_loop_expr (const constexpr_ctx *ctx, tree t,
6994 bool *non_constant_p, bool *overflow_p,
6995 tree *jump_target)
6997 tree local_target;
6998 if (!jump_target)
7000 local_target = NULL_TREE;
7001 jump_target = &local_target;
7004 tree body, cond = NULL_TREE, expr = NULL_TREE;
7005 int count = 0;
7006 switch (TREE_CODE (t))
7008 case LOOP_EXPR:
7009 body = LOOP_EXPR_BODY (t);
7010 break;
7011 case DO_STMT:
7012 body = DO_BODY (t);
7013 cond = DO_COND (t);
7014 break;
7015 case WHILE_STMT:
7016 body = WHILE_BODY (t);
7017 cond = WHILE_COND (t);
7018 count = -1;
7019 break;
7020 case FOR_STMT:
7021 if (FOR_INIT_STMT (t))
7022 cxx_eval_constant_expression (ctx, FOR_INIT_STMT (t), vc_discard,
7023 non_constant_p, overflow_p, jump_target);
7024 if (*non_constant_p)
7025 return NULL_TREE;
7026 body = FOR_BODY (t);
7027 cond = FOR_COND (t);
7028 expr = FOR_EXPR (t);
7029 count = -1;
7030 break;
7031 default:
7032 gcc_unreachable ();
7036 if (count != -1)
7038 if (body)
7039 cxx_eval_constant_expression (ctx, body, vc_discard,
7040 non_constant_p, overflow_p,
7041 jump_target);
7042 if (breaks (jump_target))
7044 *jump_target = NULL_TREE;
7045 break;
7048 if (TREE_CODE (t) != LOOP_EXPR && continues (jump_target))
7049 *jump_target = NULL_TREE;
7051 if (expr)
7052 cxx_eval_constant_expression (ctx, expr, vc_prvalue,
7053 non_constant_p, overflow_p,
7054 jump_target);
7057 if (cond)
7059 tree res
7060 = cxx_eval_constant_expression (ctx, cond, vc_prvalue,
7061 non_constant_p, overflow_p,
7062 jump_target);
7063 if (res)
7065 if (verify_constant (res, ctx->quiet, non_constant_p,
7066 overflow_p))
7067 break;
7068 if (integer_zerop (res))
7069 break;
7071 else
7072 gcc_assert (*jump_target);
7075 if (++count >= constexpr_loop_limit)
7077 if (!ctx->quiet)
7078 error_at (cp_expr_loc_or_input_loc (t),
7079 "%<constexpr%> loop iteration count exceeds limit of %d "
7080 "(use %<-fconstexpr-loop-limit=%> to increase the limit)",
7081 constexpr_loop_limit);
7082 *non_constant_p = true;
7083 break;
7086 while (!returns (jump_target)
7087 && !breaks (jump_target)
7088 && !continues (jump_target)
7089 && (!switches (jump_target) || count == 0)
7090 && !*non_constant_p);
7092 return NULL_TREE;
7095 /* Evaluate a SWITCH_EXPR for side-effects. Handles switch and break jump
7096 semantics. */
7098 static tree
7099 cxx_eval_switch_expr (const constexpr_ctx *ctx, tree t,
7100 bool *non_constant_p, bool *overflow_p,
7101 tree *jump_target)
7103 tree cond
7104 = TREE_CODE (t) == SWITCH_STMT ? SWITCH_STMT_COND (t) : SWITCH_COND (t);
7105 cond = cxx_eval_constant_expression (ctx, cond, vc_prvalue,
7106 non_constant_p, overflow_p);
7107 VERIFY_CONSTANT (cond);
7108 *jump_target = cond;
7110 tree body
7111 = TREE_CODE (t) == SWITCH_STMT ? SWITCH_STMT_BODY (t) : SWITCH_BODY (t);
7112 constexpr_ctx new_ctx = *ctx;
7113 constexpr_switch_state css = css_default_not_seen;
7114 new_ctx.css_state = &css;
7115 cxx_eval_constant_expression (&new_ctx, body, vc_discard,
7116 non_constant_p, overflow_p, jump_target);
7117 if (switches (jump_target) && css == css_default_seen)
7119 /* If the SWITCH_EXPR body has default: label, process it once again,
7120 this time instructing label_matches to return true for default:
7121 label on switches (jump_target). */
7122 css = css_default_processing;
7123 cxx_eval_constant_expression (&new_ctx, body, vc_discard,
7124 non_constant_p, overflow_p, jump_target);
7126 if (breaks (jump_target) || switches (jump_target))
7127 *jump_target = NULL_TREE;
7128 return NULL_TREE;
7131 /* Find the object of TYPE under initialization in CTX. */
7133 static tree
7134 lookup_placeholder (const constexpr_ctx *ctx, value_cat lval, tree type)
7136 if (!ctx)
7137 return NULL_TREE;
7139 /* Prefer the outermost matching object, but don't cross
7140 CONSTRUCTOR_PLACEHOLDER_BOUNDARY constructors. */
7141 if (ctx->ctor && !CONSTRUCTOR_PLACEHOLDER_BOUNDARY (ctx->ctor))
7142 if (tree outer_ob = lookup_placeholder (ctx->parent, lval, type))
7143 return outer_ob;
7145 /* We could use ctx->object unconditionally, but using ctx->ctor when we
7146 can is a minor optimization. */
7147 if (!lval && ctx->ctor && same_type_p (TREE_TYPE (ctx->ctor), type))
7148 return ctx->ctor;
7150 if (!ctx->object)
7151 return NULL_TREE;
7153 /* Since an object cannot have a field of its own type, we can search outward
7154 from ctx->object to find the unique containing object of TYPE. */
7155 tree ob = ctx->object;
7156 while (ob)
7158 if (same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (ob), type))
7159 break;
7160 if (handled_component_p (ob))
7161 ob = TREE_OPERAND (ob, 0);
7162 else
7163 ob = NULL_TREE;
7166 return ob;
7169 /* Complain about an attempt to evaluate inline assembly. If FUNDEF_P is
7170 true, we're checking a constexpr function body. */
7172 static void
7173 inline_asm_in_constexpr_error (location_t loc, bool fundef_p)
7175 auto_diagnostic_group d;
7176 if (constexpr_error (loc, fundef_p, "inline assembly is not a "
7177 "constant expression"))
7178 inform (loc, "only unevaluated inline assembly is allowed in a "
7179 "%<constexpr%> function in C++20");
7182 /* We're getting the constant value of DECL in a manifestly constant-evaluated
7183 context; maybe complain about that. */
7185 static void
7186 maybe_warn_about_constant_value (location_t loc, tree decl)
7188 static bool explained = false;
7189 if (cxx_dialect >= cxx17
7190 && warn_interference_size
7191 && !OPTION_SET_P (param_destruct_interfere_size)
7192 && DECL_CONTEXT (decl) == std_node
7193 && id_equal (DECL_NAME (decl), "hardware_destructive_interference_size")
7194 && (LOCATION_FILE (input_location) != main_input_filename
7195 || module_exporting_p ())
7196 && warning_at (loc, OPT_Winterference_size, "use of %qD", decl)
7197 && !explained)
7199 explained = true;
7200 inform (loc, "its value can vary between compiler versions or "
7201 "with different %<-mtune%> or %<-mcpu%> flags");
7202 inform (loc, "if this use is part of a public ABI, change it to "
7203 "instead use a constant variable you define");
7204 inform (loc, "the default value for the current CPU tuning "
7205 "is %d bytes", param_destruct_interfere_size);
7206 inform (loc, "you can stabilize this value with %<--param "
7207 "hardware_destructive_interference_size=%d%>, or disable "
7208 "this warning with %<-Wno-interference-size%>",
7209 param_destruct_interfere_size);
7213 /* For element type ELT_TYPE, return the appropriate type of the heap object
7214 containing such element(s). COOKIE_SIZE is NULL or the size of cookie
7215 in bytes. If COOKIE_SIZE is NULL, return array type
7216 ELT_TYPE[FULL_SIZE / sizeof(ELT_TYPE)], otherwise return
7217 struct { size_t[COOKIE_SIZE/sizeof(size_t)]; ELT_TYPE[N]; }
7218 where N is is computed such that the size of the struct fits into FULL_SIZE.
7219 If ARG_SIZE is non-NULL, it is the first argument to the new operator.
7220 It should be passed if ELT_TYPE is zero sized type in which case FULL_SIZE
7221 will be also 0 and so it is not possible to determine the actual array
7222 size. CTX, NON_CONSTANT_P and OVERFLOW_P are used during constant
7223 expression evaluation of subexpressions of ARG_SIZE. */
7225 static tree
7226 build_new_constexpr_heap_type (const constexpr_ctx *ctx, tree elt_type,
7227 tree cookie_size, tree full_size, tree arg_size,
7228 bool *non_constant_p, bool *overflow_p)
7230 gcc_assert (cookie_size == NULL_TREE || tree_fits_uhwi_p (cookie_size));
7231 gcc_assert (tree_fits_uhwi_p (full_size));
7232 unsigned HOST_WIDE_INT csz = cookie_size ? tree_to_uhwi (cookie_size) : 0;
7233 if (arg_size)
7235 STRIP_NOPS (arg_size);
7236 if (cookie_size)
7238 if (TREE_CODE (arg_size) != PLUS_EXPR)
7239 arg_size = NULL_TREE;
7240 else if (TREE_CODE (TREE_OPERAND (arg_size, 0)) == INTEGER_CST
7241 && tree_int_cst_equal (cookie_size,
7242 TREE_OPERAND (arg_size, 0)))
7244 arg_size = TREE_OPERAND (arg_size, 1);
7245 STRIP_NOPS (arg_size);
7247 else if (TREE_CODE (TREE_OPERAND (arg_size, 1)) == INTEGER_CST
7248 && tree_int_cst_equal (cookie_size,
7249 TREE_OPERAND (arg_size, 1)))
7251 arg_size = TREE_OPERAND (arg_size, 0);
7252 STRIP_NOPS (arg_size);
7254 else
7255 arg_size = NULL_TREE;
7257 if (arg_size && TREE_CODE (arg_size) == MULT_EXPR)
7259 tree op0 = TREE_OPERAND (arg_size, 0);
7260 tree op1 = TREE_OPERAND (arg_size, 1);
7261 if (integer_zerop (op0))
7262 arg_size
7263 = cxx_eval_constant_expression (ctx, op1, vc_prvalue,
7264 non_constant_p, overflow_p);
7265 else if (integer_zerop (op1))
7266 arg_size
7267 = cxx_eval_constant_expression (ctx, op0, vc_prvalue,
7268 non_constant_p, overflow_p);
7269 else
7270 arg_size = NULL_TREE;
7272 else
7273 arg_size = NULL_TREE;
7276 unsigned HOST_WIDE_INT fsz = tree_to_uhwi (arg_size ? arg_size : full_size);
7277 if (!arg_size)
7279 unsigned HOST_WIDE_INT esz = int_size_in_bytes (elt_type);
7280 gcc_assert (fsz >= csz);
7281 fsz -= csz;
7282 if (esz)
7283 fsz /= esz;
7285 tree itype2 = build_index_type (size_int (fsz - 1));
7286 if (!cookie_size)
7287 return build_cplus_array_type (elt_type, itype2);
7288 return build_new_constexpr_heap_type (elt_type, cookie_size, itype2);
7291 /* Attempt to reduce the expression T to a constant value.
7292 On failure, issue diagnostic and return error_mark_node. */
7293 /* FIXME unify with c_fully_fold */
7294 /* FIXME overflow_p is too global */
7296 static tree
7297 cxx_eval_constant_expression (const constexpr_ctx *ctx, tree t,
7298 value_cat lval,
7299 bool *non_constant_p, bool *overflow_p,
7300 tree *jump_target /* = NULL */)
7302 if (jump_target && *jump_target)
7304 /* If we are jumping, ignore all statements/expressions except those
7305 that could have LABEL_EXPR or CASE_LABEL_EXPR in their bodies. */
7306 switch (TREE_CODE (t))
7308 case BIND_EXPR:
7309 case STATEMENT_LIST:
7310 case LOOP_EXPR:
7311 case COND_EXPR:
7312 case IF_STMT:
7313 case DO_STMT:
7314 case WHILE_STMT:
7315 case FOR_STMT:
7316 break;
7317 case LABEL_EXPR:
7318 case CASE_LABEL_EXPR:
7319 if (label_matches (ctx, jump_target, t))
7320 /* Found it. */
7321 *jump_target = NULL_TREE;
7322 return NULL_TREE;
7323 default:
7324 return NULL_TREE;
7327 if (error_operand_p (t))
7329 *non_constant_p = true;
7330 return t;
7333 /* Change the input location to the currently processed expression for
7334 better error messages when a subexpression has no location. */
7335 location_t loc = cp_expr_loc_or_input_loc (t);
7336 iloc_sentinel sentinel (loc);
7338 STRIP_ANY_LOCATION_WRAPPER (t);
7340 if (CONSTANT_CLASS_P (t))
7342 if (TREE_OVERFLOW (t))
7344 if (!ctx->quiet)
7345 permerror (input_location, "overflow in constant expression");
7346 if (!flag_permissive || ctx->quiet)
7347 *overflow_p = true;
7350 if (TREE_CODE (t) == INTEGER_CST
7351 && TYPE_PTR_P (TREE_TYPE (t))
7352 /* INTEGER_CST with pointer-to-method type is only used
7353 for a virtual method in a pointer to member function.
7354 Don't reject those. */
7355 && TREE_CODE (TREE_TYPE (TREE_TYPE (t))) != METHOD_TYPE
7356 && !integer_zerop (t))
7358 if (!ctx->quiet)
7359 error ("value %qE of type %qT is not a constant expression",
7360 t, TREE_TYPE (t));
7361 *non_constant_p = true;
7364 return t;
7367 /* Avoid excessively long constexpr evaluations. */
7368 if (++ctx->global->constexpr_ops_count >= constexpr_ops_limit)
7370 if (!ctx->quiet)
7371 error_at (loc,
7372 "%<constexpr%> evaluation operation count exceeds limit of "
7373 "%wd (use %<-fconstexpr-ops-limit=%> to increase the limit)",
7374 constexpr_ops_limit);
7375 ctx->global->constexpr_ops_count = INTTYPE_MINIMUM (HOST_WIDE_INT);
7376 *non_constant_p = true;
7377 return t;
7380 constexpr_ctx new_ctx;
7381 tree r = t;
7383 tree_code tcode = TREE_CODE (t);
7384 switch (tcode)
7386 case RESULT_DECL:
7387 if (lval)
7388 return t;
7389 /* We ask for an rvalue for the RESULT_DECL when indirecting
7390 through an invisible reference, or in named return value
7391 optimization. */
7392 if (tree v = ctx->global->get_value (t))
7393 return v;
7394 else
7396 if (!ctx->quiet)
7397 error ("%qE is not a constant expression", t);
7398 *non_constant_p = true;
7400 break;
7402 case VAR_DECL:
7403 if (DECL_HAS_VALUE_EXPR_P (t))
7405 if (is_normal_capture_proxy (t)
7406 && current_function_decl == DECL_CONTEXT (t))
7408 /* Function parms aren't constexpr within the function
7409 definition, so don't try to look at the closure. But if the
7410 captured variable is constant, try to evaluate it directly. */
7411 r = DECL_CAPTURED_VARIABLE (t);
7412 tree type = TREE_TYPE (t);
7413 if (TYPE_REF_P (type) != TYPE_REF_P (TREE_TYPE (r)))
7415 /* Adjust r to match the reference-ness of t. */
7416 if (TYPE_REF_P (type))
7417 r = build_address (r);
7418 else
7419 r = convert_from_reference (r);
7422 else
7423 r = DECL_VALUE_EXPR (t);
7424 return cxx_eval_constant_expression (ctx, r, lval, non_constant_p,
7425 overflow_p);
7427 /* fall through */
7428 case CONST_DECL:
7429 /* We used to not check lval for CONST_DECL, but darwin.cc uses
7430 CONST_DECL for aggregate constants. */
7431 if (lval)
7432 return t;
7433 else if (t == ctx->object)
7434 return ctx->ctor;
7435 if (VAR_P (t))
7437 if (tree v = ctx->global->get_value (t))
7439 r = v;
7440 break;
7442 if (ctx->global->is_outside_lifetime (t))
7444 if (!ctx->quiet)
7445 outside_lifetime_error (loc, t);
7446 *non_constant_p = true;
7447 break;
7450 if (ctx->manifestly_const_eval == mce_true)
7451 maybe_warn_about_constant_value (loc, t);
7452 if (COMPLETE_TYPE_P (TREE_TYPE (t))
7453 && is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
7455 /* If the class is empty, we aren't actually loading anything. */
7456 r = build_constructor (TREE_TYPE (t), NULL);
7457 TREE_CONSTANT (r) = true;
7459 else if (ctx->strict)
7460 r = decl_really_constant_value (t, /*unshare_p=*/false);
7461 else
7462 r = decl_constant_value (t, /*unshare_p=*/false);
7463 if (TREE_CODE (r) == TARGET_EXPR
7464 && TREE_CODE (TARGET_EXPR_INITIAL (r)) == CONSTRUCTOR)
7465 r = TARGET_EXPR_INITIAL (r);
7466 if (DECL_P (r)
7467 /* P2280 allows references to unknown. */
7468 && !(VAR_P (t) && TYPE_REF_P (TREE_TYPE (t))))
7470 if (!ctx->quiet)
7471 non_const_var_error (loc, r, /*fundef_p*/false);
7472 *non_constant_p = true;
7474 break;
7476 case DEBUG_BEGIN_STMT:
7477 /* ??? It might be nice to retain this information somehow, so
7478 as to be able to step into a constexpr function call. */
7479 /* Fall through. */
7481 case FUNCTION_DECL:
7482 case TEMPLATE_DECL:
7483 case LABEL_DECL:
7484 case LABEL_EXPR:
7485 case CASE_LABEL_EXPR:
7486 case PREDICT_EXPR:
7487 return t;
7489 case PARM_DECL:
7490 if (lval && !TYPE_REF_P (TREE_TYPE (t)))
7491 /* glvalue use. */;
7492 else if (tree v = ctx->global->get_value (t))
7493 r = v;
7494 else if (lval)
7495 /* Defer in case this is only used for its type. */;
7496 else if (ctx->global->is_outside_lifetime (t))
7498 if (!ctx->quiet)
7499 outside_lifetime_error (loc, t);
7500 *non_constant_p = true;
7501 break;
7503 else if (COMPLETE_TYPE_P (TREE_TYPE (t))
7504 && is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
7506 /* If the class is empty, we aren't actually loading anything. */
7507 r = build_constructor (TREE_TYPE (t), NULL);
7508 TREE_CONSTANT (r) = true;
7510 else if (TYPE_REF_P (TREE_TYPE (t)))
7511 /* P2280 allows references to unknown... */;
7512 else if (is_this_parameter (t))
7513 /* ...as well as the this pointer. */;
7514 else
7516 if (!ctx->quiet)
7517 error ("%qE is not a constant expression", t);
7518 *non_constant_p = true;
7520 break;
7522 case CALL_EXPR:
7523 case AGGR_INIT_EXPR:
7524 r = cxx_eval_call_expression (ctx, t, lval,
7525 non_constant_p, overflow_p);
7526 break;
7528 case DECL_EXPR:
7530 r = DECL_EXPR_DECL (t);
7531 if (TREE_CODE (r) == USING_DECL)
7533 r = void_node;
7534 break;
7537 if (VAR_P (r)
7538 && (TREE_STATIC (r)
7539 || (CP_DECL_THREAD_LOCAL_P (r) && !DECL_REALLY_EXTERN (r)))
7540 /* Allow __FUNCTION__ etc. */
7541 && !DECL_ARTIFICIAL (r)
7542 && !decl_constant_var_p (r))
7544 if (!ctx->quiet)
7546 if (CP_DECL_THREAD_LOCAL_P (r))
7547 error_at (loc, "control passes through definition of %qD "
7548 "with thread storage duration", r);
7549 else
7550 error_at (loc, "control passes through definition of %qD "
7551 "with static storage duration", r);
7553 *non_constant_p = true;
7554 break;
7557 /* make_rtl_for_nonlocal_decl could have deferred emission of
7558 a local static var, but if it appears in a statement expression
7559 which is constant expression evaluated to e.g. just the address
7560 of the variable, its DECL_EXPR will never be seen during
7561 gimple lowering's record_vars_into as the statement expression
7562 will not be in the IL at all. */
7563 if (VAR_P (r)
7564 && TREE_STATIC (r)
7565 && !DECL_REALLY_EXTERN (r)
7566 && DECL_FUNCTION_SCOPE_P (r)
7567 && !var_in_maybe_constexpr_fn (r)
7568 && decl_constant_var_p (r))
7570 varpool_node *node = varpool_node::get (r);
7571 if (node == NULL || !node->definition)
7572 rest_of_decl_compilation (r, 0, at_eof);
7575 if (AGGREGATE_TYPE_P (TREE_TYPE (r))
7576 || VECTOR_TYPE_P (TREE_TYPE (r)))
7578 new_ctx = *ctx;
7579 new_ctx.object = r;
7580 new_ctx.ctor = build_constructor (TREE_TYPE (r), NULL);
7581 CONSTRUCTOR_NO_CLEARING (new_ctx.ctor) = true;
7582 ctx->global->put_value (r, new_ctx.ctor);
7583 ctx = &new_ctx;
7586 if (tree init = DECL_INITIAL (r))
7588 init = cxx_eval_constant_expression (ctx, init, vc_prvalue,
7589 non_constant_p, overflow_p);
7590 /* Don't share a CONSTRUCTOR that might be changed. */
7591 init = unshare_constructor (init);
7592 /* Remember that a constant object's constructor has already
7593 run. */
7594 if (CLASS_TYPE_P (TREE_TYPE (r))
7595 && CP_TYPE_CONST_P (TREE_TYPE (r)))
7596 TREE_READONLY (init) = true;
7597 ctx->global->put_value (r, init);
7599 else if (ctx == &new_ctx)
7600 /* We gave it a CONSTRUCTOR above. */;
7601 else
7602 ctx->global->put_value (r, NULL_TREE);
7604 break;
7606 case TARGET_EXPR:
7608 tree type = TREE_TYPE (t);
7610 if (!literal_type_p (type))
7612 if (!ctx->quiet)
7614 auto_diagnostic_group d;
7615 error ("temporary of non-literal type %qT in a "
7616 "constant expression", type);
7617 explain_non_literal_class (type);
7619 *non_constant_p = true;
7620 break;
7622 gcc_checking_assert (!TARGET_EXPR_DIRECT_INIT_P (t));
7623 /* Avoid evaluating a TARGET_EXPR more than once. */
7624 tree slot = TARGET_EXPR_SLOT (t);
7625 if (tree v = ctx->global->get_value (slot))
7627 if (lval)
7628 return slot;
7629 r = v;
7630 break;
7632 if ((AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type)))
7634 /* We're being expanded without an explicit target, so start
7635 initializing a new object; expansion with an explicit target
7636 strips the TARGET_EXPR before we get here. */
7637 new_ctx = *ctx;
7638 /* Link CTX to NEW_CTX so that lookup_placeholder can resolve
7639 any PLACEHOLDER_EXPR within the initializer that refers to the
7640 former object under construction. */
7641 new_ctx.parent = ctx;
7642 new_ctx.ctor = build_constructor (type, NULL);
7643 CONSTRUCTOR_NO_CLEARING (new_ctx.ctor) = true;
7644 new_ctx.object = slot;
7645 ctx->global->put_value (new_ctx.object, new_ctx.ctor);
7646 ctx = &new_ctx;
7648 /* Pass vc_prvalue because this indicates
7649 initialization of a temporary. */
7650 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1), vc_prvalue,
7651 non_constant_p, overflow_p);
7652 if (*non_constant_p)
7653 break;
7654 /* If the initializer is complex, evaluate it to initialize slot. */
7655 bool is_complex = target_expr_needs_replace (t);
7656 if (!is_complex)
7658 r = unshare_constructor (r);
7659 /* Adjust the type of the result to the type of the temporary. */
7660 r = adjust_temp_type (type, r);
7661 ctx->global->put_value (slot, r);
7663 if (TARGET_EXPR_CLEANUP (t) && !CLEANUP_EH_ONLY (t))
7664 ctx->global->cleanups->safe_push (TARGET_EXPR_CLEANUP (t));
7665 if (ctx->save_exprs)
7666 ctx->save_exprs->safe_push (slot);
7667 if (lval)
7668 return slot;
7669 if (is_complex)
7670 r = ctx->global->get_value (slot);
7672 break;
7674 case INIT_EXPR:
7675 case MODIFY_EXPR:
7676 gcc_assert (jump_target == NULL || *jump_target == NULL_TREE);
7677 r = cxx_eval_store_expression (ctx, t, lval,
7678 non_constant_p, overflow_p);
7679 break;
7681 case SCOPE_REF:
7682 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
7683 lval,
7684 non_constant_p, overflow_p);
7685 break;
7687 case RETURN_EXPR:
7688 if (TREE_OPERAND (t, 0) != NULL_TREE)
7689 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
7690 lval,
7691 non_constant_p, overflow_p);
7692 /* FALLTHRU */
7693 case BREAK_STMT:
7694 case CONTINUE_STMT:
7695 if (jump_target)
7696 *jump_target = t;
7697 else
7699 /* Can happen with ({ return true; }) && false; passed to
7700 maybe_constant_value. There is nothing to jump over in this
7701 case, and the bug will be diagnosed later. */
7702 gcc_assert (ctx->quiet);
7703 *non_constant_p = true;
7705 break;
7707 case SAVE_EXPR:
7708 /* Avoid evaluating a SAVE_EXPR more than once. */
7709 if (tree v = ctx->global->get_value (t))
7710 r = v;
7711 else
7713 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), vc_prvalue,
7714 non_constant_p, overflow_p);
7715 if (*non_constant_p)
7716 break;
7717 ctx->global->put_value (t, r);
7718 if (ctx->save_exprs)
7719 ctx->save_exprs->safe_push (t);
7721 break;
7723 case TRY_CATCH_EXPR:
7724 if (TREE_OPERAND (t, 0) == NULL_TREE)
7726 r = void_node;
7727 break;
7729 /* FALLTHRU */
7730 case NON_LVALUE_EXPR:
7731 case TRY_BLOCK:
7732 case MUST_NOT_THROW_EXPR:
7733 case EXPR_STMT:
7734 case EH_SPEC_BLOCK:
7735 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
7736 lval,
7737 non_constant_p, overflow_p,
7738 jump_target);
7739 break;
7741 case CLEANUP_POINT_EXPR:
7743 auto_vec<tree, 2> cleanups;
7744 vec<tree> *prev_cleanups = ctx->global->cleanups;
7745 ctx->global->cleanups = &cleanups;
7747 auto_vec<tree, 10> save_exprs;
7748 constexpr_ctx new_ctx = *ctx;
7749 new_ctx.save_exprs = &save_exprs;
7751 r = cxx_eval_constant_expression (&new_ctx, TREE_OPERAND (t, 0),
7752 lval,
7753 non_constant_p, overflow_p,
7754 jump_target);
7756 ctx->global->cleanups = prev_cleanups;
7757 unsigned int i;
7758 tree cleanup;
7759 /* Evaluate the cleanups. */
7760 FOR_EACH_VEC_ELT_REVERSE (cleanups, i, cleanup)
7761 cxx_eval_constant_expression (&new_ctx, cleanup, vc_discard,
7762 non_constant_p, overflow_p);
7764 /* Forget SAVE_EXPRs and TARGET_EXPRs created by this
7765 full-expression. */
7766 for (tree save_expr : save_exprs)
7767 destroy_value_checked (ctx, save_expr, non_constant_p);
7769 break;
7771 case TRY_FINALLY_EXPR:
7772 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
7773 non_constant_p, overflow_p,
7774 jump_target);
7775 if (!*non_constant_p)
7776 /* Also evaluate the cleanup. */
7777 cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1), vc_discard,
7778 non_constant_p, overflow_p);
7779 break;
7781 case CLEANUP_STMT:
7782 r = cxx_eval_constant_expression (ctx, CLEANUP_BODY (t), lval,
7783 non_constant_p, overflow_p,
7784 jump_target);
7785 if (!CLEANUP_EH_ONLY (t) && !*non_constant_p)
7787 iloc_sentinel ils (loc);
7788 /* Also evaluate the cleanup. */
7789 cxx_eval_constant_expression (ctx, CLEANUP_EXPR (t), vc_discard,
7790 non_constant_p, overflow_p);
7792 break;
7794 /* These differ from cxx_eval_unary_expression in that this doesn't
7795 check for a constant operand or result; an address can be
7796 constant without its operand being, and vice versa. */
7797 case MEM_REF:
7798 case INDIRECT_REF:
7799 r = cxx_eval_indirect_ref (ctx, t, lval,
7800 non_constant_p, overflow_p);
7801 break;
7803 case ADDR_EXPR:
7805 tree oldop = TREE_OPERAND (t, 0);
7806 tree op = cxx_eval_constant_expression (ctx, oldop, vc_glvalue,
7807 non_constant_p, overflow_p);
7808 /* Don't VERIFY_CONSTANT here. */
7809 if (*non_constant_p)
7810 return t;
7811 gcc_checking_assert (TREE_CODE (op) != CONSTRUCTOR);
7812 /* This function does more aggressive folding than fold itself. */
7813 r = build_fold_addr_expr_with_type (op, TREE_TYPE (t));
7814 if (TREE_CODE (r) == ADDR_EXPR && TREE_OPERAND (r, 0) == oldop)
7816 ggc_free (r);
7817 return t;
7819 break;
7822 case REALPART_EXPR:
7823 case IMAGPART_EXPR:
7824 if (lval)
7826 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
7827 non_constant_p, overflow_p);
7828 if (r == error_mark_node)
7830 else if (r == TREE_OPERAND (t, 0) || lval == vc_discard)
7831 r = t;
7832 else
7833 r = fold_build1 (TREE_CODE (t), TREE_TYPE (t), r);
7834 break;
7836 /* FALLTHRU */
7837 case CONJ_EXPR:
7838 case FIX_TRUNC_EXPR:
7839 case FLOAT_EXPR:
7840 case NEGATE_EXPR:
7841 case ABS_EXPR:
7842 case ABSU_EXPR:
7843 case BIT_NOT_EXPR:
7844 case TRUTH_NOT_EXPR:
7845 case FIXED_CONVERT_EXPR:
7846 r = cxx_eval_unary_expression (ctx, t, lval,
7847 non_constant_p, overflow_p);
7848 break;
7850 case SIZEOF_EXPR:
7851 r = fold_sizeof_expr (t);
7852 /* In a template, fold_sizeof_expr may merely create a new SIZEOF_EXPR,
7853 which could lead to an infinite recursion. */
7854 if (TREE_CODE (r) != SIZEOF_EXPR)
7855 r = cxx_eval_constant_expression (ctx, r, lval,
7856 non_constant_p, overflow_p,
7857 jump_target);
7858 else
7860 *non_constant_p = true;
7861 gcc_assert (ctx->quiet);
7864 break;
7866 case COMPOUND_EXPR:
7868 /* check_return_expr sometimes wraps a TARGET_EXPR in a
7869 COMPOUND_EXPR; don't get confused. Also handle EMPTY_CLASS_EXPR
7870 introduced by build_call_a. */
7871 tree op0 = TREE_OPERAND (t, 0);
7872 tree op1 = TREE_OPERAND (t, 1);
7873 STRIP_NOPS (op1);
7874 if ((TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
7875 || TREE_CODE (op1) == EMPTY_CLASS_EXPR)
7876 r = cxx_eval_constant_expression (ctx, op0,
7877 lval, non_constant_p, overflow_p,
7878 jump_target);
7879 else
7881 /* Check that the LHS is constant and then discard it. */
7882 cxx_eval_constant_expression (ctx, op0, vc_discard,
7883 non_constant_p, overflow_p,
7884 jump_target);
7885 if (*non_constant_p)
7886 return t;
7887 op1 = TREE_OPERAND (t, 1);
7888 r = cxx_eval_constant_expression (ctx, op1,
7889 lval, non_constant_p, overflow_p,
7890 jump_target);
7893 break;
7895 case POINTER_PLUS_EXPR:
7896 case POINTER_DIFF_EXPR:
7897 case PLUS_EXPR:
7898 case MINUS_EXPR:
7899 case MULT_EXPR:
7900 case TRUNC_DIV_EXPR:
7901 case CEIL_DIV_EXPR:
7902 case FLOOR_DIV_EXPR:
7903 case ROUND_DIV_EXPR:
7904 case TRUNC_MOD_EXPR:
7905 case CEIL_MOD_EXPR:
7906 case ROUND_MOD_EXPR:
7907 case RDIV_EXPR:
7908 case EXACT_DIV_EXPR:
7909 case MIN_EXPR:
7910 case MAX_EXPR:
7911 case LSHIFT_EXPR:
7912 case RSHIFT_EXPR:
7913 case LROTATE_EXPR:
7914 case RROTATE_EXPR:
7915 case BIT_IOR_EXPR:
7916 case BIT_XOR_EXPR:
7917 case BIT_AND_EXPR:
7918 case TRUTH_XOR_EXPR:
7919 case LT_EXPR:
7920 case LE_EXPR:
7921 case GT_EXPR:
7922 case GE_EXPR:
7923 case EQ_EXPR:
7924 case NE_EXPR:
7925 case SPACESHIP_EXPR:
7926 case UNORDERED_EXPR:
7927 case ORDERED_EXPR:
7928 case UNLT_EXPR:
7929 case UNLE_EXPR:
7930 case UNGT_EXPR:
7931 case UNGE_EXPR:
7932 case UNEQ_EXPR:
7933 case LTGT_EXPR:
7934 case RANGE_EXPR:
7935 case COMPLEX_EXPR:
7936 r = cxx_eval_binary_expression (ctx, t, lval,
7937 non_constant_p, overflow_p);
7938 break;
7940 /* fold can introduce non-IF versions of these; still treat them as
7941 short-circuiting. */
7942 case TRUTH_AND_EXPR:
7943 case TRUTH_ANDIF_EXPR:
7944 r = cxx_eval_logical_expression (ctx, t, boolean_false_node,
7945 boolean_true_node,
7946 non_constant_p, overflow_p);
7947 break;
7949 case TRUTH_OR_EXPR:
7950 case TRUTH_ORIF_EXPR:
7951 r = cxx_eval_logical_expression (ctx, t, boolean_true_node,
7952 boolean_false_node,
7953 non_constant_p, overflow_p);
7954 break;
7956 case ARRAY_REF:
7957 r = cxx_eval_array_reference (ctx, t, lval,
7958 non_constant_p, overflow_p);
7959 break;
7961 case COMPONENT_REF:
7962 if (is_overloaded_fn (t))
7964 /* We can only get here in checking mode via
7965 build_non_dependent_expr, because any expression that
7966 calls or takes the address of the function will have
7967 pulled a FUNCTION_DECL out of the COMPONENT_REF. */
7968 gcc_checking_assert (ctx->quiet || errorcount);
7969 *non_constant_p = true;
7970 return t;
7972 r = cxx_eval_component_reference (ctx, t, lval,
7973 non_constant_p, overflow_p);
7974 break;
7976 case BIT_FIELD_REF:
7977 r = cxx_eval_bit_field_ref (ctx, t, lval,
7978 non_constant_p, overflow_p);
7979 break;
7981 case COND_EXPR:
7982 case IF_STMT:
7983 if (jump_target && *jump_target)
7985 tree orig_jump = *jump_target;
7986 tree arg = ((TREE_CODE (t) != IF_STMT || TREE_OPERAND (t, 1))
7987 ? TREE_OPERAND (t, 1) : void_node);
7988 /* When jumping to a label, the label might be either in the
7989 then or else blocks, so process then block first in skipping
7990 mode first, and if we are still in the skipping mode at its end,
7991 process the else block too. */
7992 r = cxx_eval_constant_expression (ctx, arg, lval, non_constant_p,
7993 overflow_p, jump_target);
7994 /* It's possible that we found the label in the then block. But
7995 it could have been followed by another jumping statement, e.g.
7996 say we're looking for case 1:
7997 if (cond)
7999 // skipped statements
8000 case 1:; // clears up *jump_target
8001 return 1; // and sets it to a RETURN_EXPR
8003 else { ... }
8004 in which case we need not go looking to the else block.
8005 (goto is not allowed in a constexpr function.) */
8006 if (*jump_target == orig_jump)
8008 arg = ((TREE_CODE (t) != IF_STMT || TREE_OPERAND (t, 2))
8009 ? TREE_OPERAND (t, 2) : void_node);
8010 r = cxx_eval_constant_expression (ctx, arg, lval, non_constant_p,
8011 overflow_p, jump_target);
8013 break;
8015 r = cxx_eval_conditional_expression (ctx, t, lval,
8016 non_constant_p, overflow_p,
8017 jump_target);
8018 break;
8019 case VEC_COND_EXPR:
8020 r = cxx_eval_vector_conditional_expression (ctx, t, non_constant_p,
8021 overflow_p);
8022 break;
8024 case CONSTRUCTOR:
8025 if (TREE_CONSTANT (t) && reduced_constant_expression_p (t))
8027 /* Don't re-process a constant CONSTRUCTOR. */
8028 verify_constructor_flags (t);
8029 if (TREE_CONSTANT (t))
8030 return t;
8032 r = cxx_eval_bare_aggregate (ctx, t, lval,
8033 non_constant_p, overflow_p);
8034 break;
8036 case VEC_INIT_EXPR:
8037 /* We can get this in a defaulted constructor for a class with a
8038 non-static data member of array type. Either the initializer will
8039 be NULL, meaning default-initialization, or it will be an lvalue
8040 or xvalue of the same type, meaning direct-initialization from the
8041 corresponding member. */
8042 r = cxx_eval_vec_init (ctx, t, lval,
8043 non_constant_p, overflow_p);
8044 break;
8046 case VEC_PERM_EXPR:
8047 r = cxx_eval_trinary_expression (ctx, t, lval,
8048 non_constant_p, overflow_p);
8049 break;
8051 case PAREN_EXPR:
8052 gcc_assert (!REF_PARENTHESIZED_P (t));
8053 /* A PAREN_EXPR resulting from __builtin_assoc_barrier has no effect in
8054 constant expressions since it's unaffected by -fassociative-math. */
8055 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
8056 non_constant_p, overflow_p);
8057 break;
8059 case NOP_EXPR:
8060 if (REINTERPRET_CAST_P (t))
8062 if (!ctx->quiet)
8063 error_at (loc,
8064 "%<reinterpret_cast%> is not a constant expression");
8065 *non_constant_p = true;
8066 return t;
8068 /* FALLTHROUGH. */
8069 case CONVERT_EXPR:
8070 case VIEW_CONVERT_EXPR:
8071 case UNARY_PLUS_EXPR:
8073 tree oldop = TREE_OPERAND (t, 0);
8075 tree op = cxx_eval_constant_expression (ctx, oldop,
8076 lval,
8077 non_constant_p, overflow_p);
8078 if (*non_constant_p)
8079 return t;
8080 tree type = TREE_TYPE (t);
8082 if (VOID_TYPE_P (type))
8083 return void_node;
8085 if (TREE_CODE (t) == CONVERT_EXPR
8086 && ARITHMETIC_TYPE_P (type)
8087 && INDIRECT_TYPE_P (TREE_TYPE (op))
8088 && ctx->manifestly_const_eval == mce_true)
8090 if (!ctx->quiet)
8091 error_at (loc,
8092 "conversion from pointer type %qT to arithmetic type "
8093 "%qT in a constant expression", TREE_TYPE (op), type);
8094 *non_constant_p = true;
8095 return t;
8098 /* [expr.const]: a conversion from type cv void* to a pointer-to-object
8099 type cannot be part of a core constant expression as a resolution to
8100 DR 1312. */
8101 if (TYPE_PTROB_P (type)
8102 && TYPE_PTR_P (TREE_TYPE (op))
8103 && VOID_TYPE_P (TREE_TYPE (TREE_TYPE (op)))
8104 /* Inside a call to std::construct_at,
8105 std::allocator<T>::{,de}allocate, or
8106 std::source_location::current, we permit casting from void*
8107 because that is compiler-generated code. */
8108 && !is_std_construct_at (ctx->call)
8109 && !is_std_allocator_allocate (ctx->call)
8110 && !is_std_source_location_current (ctx->call))
8112 /* Likewise, don't error when casting from void* when OP is
8113 &heap uninit and similar. */
8114 tree sop = tree_strip_nop_conversions (op);
8115 tree decl = NULL_TREE;
8116 if (TREE_CODE (sop) == ADDR_EXPR)
8117 decl = TREE_OPERAND (sop, 0);
8118 if (decl
8119 && VAR_P (decl)
8120 && DECL_ARTIFICIAL (decl)
8121 && (DECL_NAME (decl) == heap_identifier
8122 || DECL_NAME (decl) == heap_uninit_identifier
8123 || DECL_NAME (decl) == heap_vec_identifier
8124 || DECL_NAME (decl) == heap_vec_uninit_identifier))
8125 /* OK */;
8126 /* P2738 (C++26): a conversion from a prvalue P of type "pointer to
8127 cv void" to a pointer-to-object type T unless P points to an
8128 object whose type is similar to T. */
8129 else if (cxx_dialect > cxx23)
8131 r = cxx_fold_indirect_ref (ctx, loc, TREE_TYPE (type), sop);
8132 if (r)
8134 r = build1 (ADDR_EXPR, type, r);
8135 break;
8137 if (!ctx->quiet)
8139 if (TREE_CODE (sop) == ADDR_EXPR)
8141 auto_diagnostic_group d;
8142 error_at (loc, "cast from %qT is not allowed in a "
8143 "constant expression because "
8144 "pointed-to type %qT is not similar to %qT",
8145 TREE_TYPE (op), TREE_TYPE (TREE_TYPE (sop)),
8146 TREE_TYPE (type));
8147 tree obj = build_fold_indirect_ref (sop);
8148 inform (DECL_SOURCE_LOCATION (obj),
8149 "pointed-to object declared here");
8151 else
8153 gcc_assert (integer_zerop (sop));
8154 error_at (loc, "cast from %qT is not allowed in a "
8155 "constant expression because "
8156 "%qE does not point to an object",
8157 TREE_TYPE (op), oldop);
8160 *non_constant_p = true;
8161 return t;
8163 else
8165 if (!ctx->quiet)
8166 error_at (loc, "cast from %qT is not allowed in a "
8167 "constant expression before C++26",
8168 TREE_TYPE (op));
8169 *non_constant_p = true;
8170 return t;
8174 if (TREE_CODE (op) == PTRMEM_CST && !TYPE_PTRMEM_P (type))
8176 op = cplus_expand_constant (op);
8177 if (TREE_CODE (op) == PTRMEM_CST)
8179 if (!ctx->quiet)
8180 error_at (loc, "%qE is not a constant expression when the "
8181 "class %qT is still incomplete", op,
8182 PTRMEM_CST_CLASS (op));
8183 *non_constant_p = true;
8184 return t;
8188 if (TREE_CODE (op) == PTRMEM_CST && tcode == NOP_EXPR)
8190 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (op))
8191 && !can_convert_qual (type, op))
8192 op = cplus_expand_constant (op);
8193 return cp_fold_convert (type, op);
8196 if (INDIRECT_TYPE_P (type) && TREE_CODE (op) == INTEGER_CST)
8198 if (integer_zerop (op))
8200 if (TYPE_REF_P (type))
8202 if (!ctx->quiet)
8203 error_at (loc, "dereferencing a null pointer");
8204 *non_constant_p = true;
8205 return t;
8208 else
8210 /* This detects for example:
8211 reinterpret_cast<void*>(sizeof 0)
8213 if (!ctx->quiet)
8214 error_at (loc, "%<reinterpret_cast<%T>(%E)%> is not "
8215 "a constant expression",
8216 type, op);
8217 *non_constant_p = true;
8218 return t;
8222 if (INDIRECT_TYPE_P (type)
8223 && TREE_CODE (op) == NOP_EXPR
8224 && TREE_TYPE (op) == ptr_type_node
8225 && TREE_CODE (TREE_OPERAND (op, 0)) == ADDR_EXPR
8226 && VAR_P (TREE_OPERAND (TREE_OPERAND (op, 0), 0))
8227 && (DECL_NAME (TREE_OPERAND (TREE_OPERAND (op, 0),
8228 0)) == heap_uninit_identifier
8229 || DECL_NAME (TREE_OPERAND (TREE_OPERAND (op, 0),
8230 0)) == heap_vec_uninit_identifier))
8232 tree var = TREE_OPERAND (TREE_OPERAND (op, 0), 0);
8233 tree var_size = TYPE_SIZE_UNIT (TREE_TYPE (var));
8234 tree elt_type = TREE_TYPE (type);
8235 tree cookie_size = NULL_TREE;
8236 tree arg_size = NULL_TREE;
8237 if (TREE_CODE (elt_type) == RECORD_TYPE
8238 && TYPE_NAME (elt_type) == heap_identifier)
8240 tree fld1 = TYPE_FIELDS (elt_type);
8241 tree fld2 = DECL_CHAIN (fld1);
8242 elt_type = TREE_TYPE (TREE_TYPE (fld2));
8243 cookie_size = TYPE_SIZE_UNIT (TREE_TYPE (fld1));
8245 DECL_NAME (var)
8246 = (DECL_NAME (var) == heap_uninit_identifier
8247 ? heap_identifier : heap_vec_identifier);
8248 /* For zero sized elt_type, try to recover how many outer_nelts
8249 it should have. */
8250 if ((cookie_size ? tree_int_cst_equal (var_size, cookie_size)
8251 : integer_zerop (var_size))
8252 && !int_size_in_bytes (elt_type)
8253 && TREE_CODE (oldop) == CALL_EXPR
8254 && call_expr_nargs (oldop) >= 1)
8255 if (tree fun = get_function_named_in_call (oldop))
8256 if (cxx_replaceable_global_alloc_fn (fun)
8257 && IDENTIFIER_NEW_OP_P (DECL_NAME (fun)))
8258 arg_size = CALL_EXPR_ARG (oldop, 0);
8259 TREE_TYPE (var)
8260 = build_new_constexpr_heap_type (ctx, elt_type, cookie_size,
8261 var_size, arg_size,
8262 non_constant_p, overflow_p);
8263 TREE_TYPE (TREE_OPERAND (op, 0))
8264 = build_pointer_type (TREE_TYPE (var));
8267 if (op == oldop && tcode != UNARY_PLUS_EXPR)
8268 /* We didn't fold at the top so we could check for ptr-int
8269 conversion. */
8270 return fold (t);
8272 tree sop;
8274 /* Handle an array's bounds having been deduced after we built
8275 the wrapping expression. */
8276 if (same_type_ignoring_tlq_and_bounds_p (type, TREE_TYPE (op)))
8277 r = op;
8278 else if (sop = tree_strip_nop_conversions (op),
8279 sop != op && (same_type_ignoring_tlq_and_bounds_p
8280 (type, TREE_TYPE (sop))))
8281 r = sop;
8282 else if (tcode == UNARY_PLUS_EXPR)
8283 r = fold_convert (TREE_TYPE (t), op);
8284 else
8285 r = fold_build1 (tcode, type, op);
8287 /* Conversion of an out-of-range value has implementation-defined
8288 behavior; the language considers it different from arithmetic
8289 overflow, which is undefined. */
8290 if (TREE_OVERFLOW_P (r) && !TREE_OVERFLOW_P (op))
8291 TREE_OVERFLOW (r) = false;
8293 break;
8295 case EXCESS_PRECISION_EXPR:
8297 tree oldop = TREE_OPERAND (t, 0);
8299 tree op = cxx_eval_constant_expression (ctx, oldop,
8300 lval,
8301 non_constant_p, overflow_p);
8302 if (*non_constant_p)
8303 return t;
8304 r = fold_convert (TREE_TYPE (t), op);
8305 break;
8308 case EMPTY_CLASS_EXPR:
8309 /* Handle EMPTY_CLASS_EXPR produced by build_call_a by lowering
8310 it to an appropriate CONSTRUCTOR. */
8311 return build_constructor (TREE_TYPE (t), NULL);
8313 case STATEMENT_LIST:
8314 new_ctx = *ctx;
8315 new_ctx.ctor = new_ctx.object = NULL_TREE;
8316 return cxx_eval_statement_list (&new_ctx, t,
8317 non_constant_p, overflow_p, jump_target);
8319 case BIND_EXPR:
8320 /* Pre-emptively clear the vars declared by this BIND_EXPR from the value
8321 map, so that when checking whether they're already destroyed later we
8322 don't get confused by remnants of previous calls. */
8323 for (tree decl = BIND_EXPR_VARS (t); decl; decl = DECL_CHAIN (decl))
8324 ctx->global->clear_value (decl);
8325 r = cxx_eval_constant_expression (ctx, BIND_EXPR_BODY (t),
8326 lval,
8327 non_constant_p, overflow_p,
8328 jump_target);
8329 for (tree decl = BIND_EXPR_VARS (t); decl; decl = DECL_CHAIN (decl))
8330 destroy_value_checked (ctx, decl, non_constant_p);
8331 break;
8333 case PREINCREMENT_EXPR:
8334 case POSTINCREMENT_EXPR:
8335 case PREDECREMENT_EXPR:
8336 case POSTDECREMENT_EXPR:
8337 return cxx_eval_increment_expression (ctx, t,
8338 lval, non_constant_p, overflow_p);
8340 case LAMBDA_EXPR:
8341 case NEW_EXPR:
8342 case VEC_NEW_EXPR:
8343 case DELETE_EXPR:
8344 case VEC_DELETE_EXPR:
8345 case THROW_EXPR:
8346 case MODOP_EXPR:
8347 /* GCC internal stuff. */
8348 case VA_ARG_EXPR:
8349 case BASELINK:
8350 case OFFSET_REF:
8351 if (!ctx->quiet)
8352 error_at (loc, "expression %qE is not a constant expression", t);
8353 *non_constant_p = true;
8354 break;
8356 case OBJ_TYPE_REF:
8357 /* Virtual function lookup. We don't need to do anything fancy. */
8358 return cxx_eval_constant_expression (ctx, OBJ_TYPE_REF_EXPR (t),
8359 lval, non_constant_p, overflow_p);
8361 case PLACEHOLDER_EXPR:
8362 /* Use of the value or address of the current object. */
8363 if (tree ctor = lookup_placeholder (ctx, lval, TREE_TYPE (t)))
8365 if (TREE_CODE (ctor) == CONSTRUCTOR)
8366 return ctor;
8367 else
8368 return cxx_eval_constant_expression (ctx, ctor, lval,
8369 non_constant_p, overflow_p);
8371 /* A placeholder without a referent. We can get here when
8372 checking whether NSDMIs are noexcept, or in massage_init_elt;
8373 just say it's non-constant for now. */
8374 gcc_assert (ctx->quiet);
8375 *non_constant_p = true;
8376 break;
8378 case EXIT_EXPR:
8380 tree cond = TREE_OPERAND (t, 0);
8381 cond = cxx_eval_constant_expression (ctx, cond, vc_prvalue,
8382 non_constant_p, overflow_p);
8383 VERIFY_CONSTANT (cond);
8384 if (integer_nonzerop (cond))
8385 *jump_target = t;
8387 break;
8389 case GOTO_EXPR:
8390 if (breaks (&TREE_OPERAND (t, 0))
8391 || continues (&TREE_OPERAND (t, 0)))
8392 *jump_target = TREE_OPERAND (t, 0);
8393 else
8395 gcc_assert (cxx_dialect >= cxx23);
8396 if (!ctx->quiet)
8397 error_at (loc, "%<goto%> is not a constant expression");
8398 *non_constant_p = true;
8400 break;
8402 case LOOP_EXPR:
8403 case DO_STMT:
8404 case WHILE_STMT:
8405 case FOR_STMT:
8406 cxx_eval_loop_expr (ctx, t,
8407 non_constant_p, overflow_p, jump_target);
8408 break;
8410 case SWITCH_EXPR:
8411 case SWITCH_STMT:
8412 cxx_eval_switch_expr (ctx, t,
8413 non_constant_p, overflow_p, jump_target);
8414 break;
8416 case REQUIRES_EXPR:
8417 /* It's possible to get a requires-expression in a constant
8418 expression. For example:
8420 template<typename T> concept bool C() {
8421 return requires (T t) { t; };
8424 template<typename T> requires !C<T>() void f(T);
8426 Normalization leaves f with the associated constraint
8427 '!requires (T t) { ... }' which is not transformed into
8428 a constraint. */
8429 if (!processing_template_decl)
8430 return evaluate_requires_expr (t);
8431 else
8432 *non_constant_p = true;
8433 return t;
8435 case ANNOTATE_EXPR:
8436 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
8437 lval,
8438 non_constant_p, overflow_p,
8439 jump_target);
8440 break;
8442 case USING_STMT:
8443 r = void_node;
8444 break;
8446 case ASSERTION_STMT:
8447 case PRECONDITION_STMT:
8448 case POSTCONDITION_STMT:
8450 contract_semantic semantic = get_contract_semantic (t);
8451 if (semantic == CCS_IGNORE)
8452 break;
8454 if (!cxx_eval_assert (ctx, CONTRACT_CONDITION (t),
8455 G_("contract predicate is false in "
8456 "constant expression"),
8457 EXPR_LOCATION (t), checked_contract_p (semantic),
8458 non_constant_p, overflow_p))
8459 *non_constant_p = true;
8460 r = void_node;
8462 break;
8464 case TEMPLATE_ID_EXPR:
8466 /* We can evaluate template-id that refers to a concept only if
8467 the template arguments are non-dependent. */
8468 tree id = unpack_concept_check (t);
8469 tree tmpl = TREE_OPERAND (id, 0);
8470 if (!concept_definition_p (tmpl))
8471 internal_error ("unexpected template-id %qE", t);
8473 if (function_concept_p (tmpl))
8475 if (!ctx->quiet)
8476 error_at (cp_expr_loc_or_input_loc (t),
8477 "function concept must be called");
8478 r = error_mark_node;
8479 break;
8482 if (!value_dependent_expression_p (t)
8483 && !uid_sensitive_constexpr_evaluation_p ())
8484 r = evaluate_concept_check (t);
8485 else
8486 *non_constant_p = true;
8488 break;
8491 case ASM_EXPR:
8492 if (!ctx->quiet)
8493 inline_asm_in_constexpr_error (loc, /*constexpr_fundef_p*/false);
8494 *non_constant_p = true;
8495 return t;
8497 case BIT_CAST_EXPR:
8498 if (lval)
8500 if (!ctx->quiet)
8501 error_at (EXPR_LOCATION (t),
8502 "address of a call to %qs is not a constant expression",
8503 "__builtin_bit_cast");
8504 *non_constant_p = true;
8505 return t;
8507 r = cxx_eval_bit_cast (ctx, t, non_constant_p, overflow_p);
8508 break;
8510 case OMP_PARALLEL:
8511 case OMP_TASK:
8512 case OMP_FOR:
8513 case OMP_SIMD:
8514 case OMP_DISTRIBUTE:
8515 case OMP_TASKLOOP:
8516 case OMP_LOOP:
8517 case OMP_TEAMS:
8518 case OMP_TARGET_DATA:
8519 case OMP_TARGET:
8520 case OMP_SECTIONS:
8521 case OMP_ORDERED:
8522 case OMP_CRITICAL:
8523 case OMP_SINGLE:
8524 case OMP_SCAN:
8525 case OMP_SCOPE:
8526 case OMP_SECTION:
8527 case OMP_STRUCTURED_BLOCK:
8528 case OMP_MASTER:
8529 case OMP_MASKED:
8530 case OMP_TASKGROUP:
8531 case OMP_TARGET_UPDATE:
8532 case OMP_TARGET_ENTER_DATA:
8533 case OMP_TARGET_EXIT_DATA:
8534 case OMP_ATOMIC:
8535 case OMP_ATOMIC_READ:
8536 case OMP_ATOMIC_CAPTURE_OLD:
8537 case OMP_ATOMIC_CAPTURE_NEW:
8538 case OMP_DEPOBJ:
8539 case OACC_PARALLEL:
8540 case OACC_KERNELS:
8541 case OACC_SERIAL:
8542 case OACC_DATA:
8543 case OACC_HOST_DATA:
8544 case OACC_LOOP:
8545 case OACC_CACHE:
8546 case OACC_DECLARE:
8547 case OACC_ENTER_DATA:
8548 case OACC_EXIT_DATA:
8549 case OACC_UPDATE:
8550 if (!ctx->quiet)
8551 error_at (EXPR_LOCATION (t),
8552 "statement is not a constant expression");
8553 *non_constant_p = true;
8554 break;
8556 default:
8557 if (STATEMENT_CODE_P (TREE_CODE (t)))
8559 /* This function doesn't know how to deal with pre-genericize
8560 statements; this can only happen with statement-expressions,
8561 so for now just fail. */
8562 if (!ctx->quiet)
8563 error_at (EXPR_LOCATION (t),
8564 "statement is not a constant expression");
8566 else
8567 internal_error ("unexpected expression %qE of kind %s", t,
8568 get_tree_code_name (TREE_CODE (t)));
8569 *non_constant_p = true;
8570 break;
8573 if (r == error_mark_node)
8574 *non_constant_p = true;
8576 if (*non_constant_p)
8577 return t;
8578 else
8579 return r;
8582 /* P0859: A function is needed for constant evaluation if it is a constexpr
8583 function that is named by an expression ([basic.def.odr]) that is
8584 potentially constant evaluated.
8586 So we need to instantiate any constexpr functions mentioned by the
8587 expression even if the definition isn't needed for evaluating the
8588 expression. */
8590 static tree
8591 instantiate_cx_fn_r (tree *tp, int *walk_subtrees, void */*data*/)
8593 if (TREE_CODE (*tp) == FUNCTION_DECL
8594 && DECL_DECLARED_CONSTEXPR_P (*tp)
8595 && !DECL_INITIAL (*tp)
8596 && !trivial_fn_p (*tp)
8597 && (DECL_TEMPLOID_INSTANTIATION (*tp) || DECL_DEFAULTED_FN (*tp))
8598 && !uid_sensitive_constexpr_evaluation_p ())
8600 ++function_depth;
8601 if (DECL_TEMPLOID_INSTANTIATION (*tp))
8602 instantiate_decl (*tp, /*defer_ok*/false, /*expl_inst*/false);
8603 else
8604 synthesize_method (*tp);
8605 --function_depth;
8607 else if (TREE_CODE (*tp) == CALL_EXPR
8608 || TREE_CODE (*tp) == AGGR_INIT_EXPR)
8610 if (EXPR_HAS_LOCATION (*tp))
8611 input_location = EXPR_LOCATION (*tp);
8614 if (!EXPR_P (*tp))
8615 *walk_subtrees = 0;
8617 return NULL_TREE;
8620 static void
8621 instantiate_constexpr_fns (tree t)
8623 location_t loc = input_location;
8624 cp_walk_tree_without_duplicates (&t, instantiate_cx_fn_r, NULL);
8625 input_location = loc;
8628 /* Look for heap variables in the expression *TP. */
8630 static tree
8631 find_heap_var_refs (tree *tp, int *walk_subtrees, void */*data*/)
8633 if (VAR_P (*tp)
8634 && (DECL_NAME (*tp) == heap_uninit_identifier
8635 || DECL_NAME (*tp) == heap_identifier
8636 || DECL_NAME (*tp) == heap_vec_uninit_identifier
8637 || DECL_NAME (*tp) == heap_vec_identifier
8638 || DECL_NAME (*tp) == heap_deleted_identifier))
8639 return *tp;
8641 if (TYPE_P (*tp))
8642 *walk_subtrees = 0;
8643 return NULL_TREE;
8646 /* Find immediate function decls in *TP if any. */
8648 static tree
8649 find_immediate_fndecl (tree *tp, int */*walk_subtrees*/, void */*data*/)
8651 if (TREE_CODE (*tp) == FUNCTION_DECL && DECL_IMMEDIATE_FUNCTION_P (*tp))
8652 return *tp;
8653 if (TREE_CODE (*tp) == PTRMEM_CST
8654 && TREE_CODE (PTRMEM_CST_MEMBER (*tp)) == FUNCTION_DECL
8655 && DECL_IMMEDIATE_FUNCTION_P (PTRMEM_CST_MEMBER (*tp)))
8656 return PTRMEM_CST_MEMBER (*tp);
8657 return NULL_TREE;
8660 /* T has TREE_CONSTANT set but has been deemed not a valid C++ constant
8661 expression. Return a version of T that has TREE_CONSTANT cleared. */
8663 static tree
8664 mark_non_constant (tree t)
8666 gcc_checking_assert (TREE_CONSTANT (t));
8668 /* This isn't actually constant, so unset TREE_CONSTANT.
8669 Don't clear TREE_CONSTANT on ADDR_EXPR, as the middle-end requires
8670 it to be set if it is invariant address, even when it is not
8671 a valid C++ constant expression. Wrap it with a NOP_EXPR
8672 instead. */
8673 if (EXPR_P (t) && TREE_CODE (t) != ADDR_EXPR)
8674 t = copy_node (t);
8675 else if (TREE_CODE (t) == CONSTRUCTOR)
8676 t = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (t), t);
8677 else
8678 t = build_nop (TREE_TYPE (t), t);
8679 TREE_CONSTANT (t) = false;
8680 return t;
8683 /* ALLOW_NON_CONSTANT is false if T is required to be a constant expression.
8684 STRICT has the same sense as for constant_value_1: true if we only allow
8685 conforming C++ constant expressions, or false if we want a constant value
8686 even if it doesn't conform.
8687 MANIFESTLY_CONST_EVAL is true if T is manifestly const-evaluated as
8688 per P0595 even when ALLOW_NON_CONSTANT is true.
8689 CONSTEXPR_DTOR is true when evaluating the dtor of a constexpr variable.
8690 OBJECT must be non-NULL in that case. */
8692 static tree
8693 cxx_eval_outermost_constant_expr (tree t, bool allow_non_constant,
8694 bool strict = true,
8695 mce_value manifestly_const_eval = mce_unknown,
8696 bool constexpr_dtor = false,
8697 tree object = NULL_TREE)
8699 auto_timevar time (TV_CONSTEXPR);
8701 bool non_constant_p = false;
8702 bool overflow_p = false;
8704 if (BRACE_ENCLOSED_INITIALIZER_P (t))
8706 gcc_checking_assert (allow_non_constant);
8707 return t;
8710 constexpr_global_ctx global_ctx;
8711 constexpr_ctx ctx = { &global_ctx, NULL, NULL, NULL, NULL, NULL, NULL,
8712 allow_non_constant, strict,
8713 !allow_non_constant ? mce_true : manifestly_const_eval };
8715 /* Turn off -frounding-math for manifestly constant evaluation. */
8716 warning_sentinel rm (flag_rounding_math,
8717 ctx.manifestly_const_eval == mce_true);
8718 tree type = initialized_type (t);
8719 tree r = t;
8720 bool is_consteval = false;
8721 if (VOID_TYPE_P (type))
8723 if (constexpr_dtor)
8724 /* Used for destructors of array elements. */
8725 type = TREE_TYPE (object);
8726 else
8728 if (cxx_dialect < cxx20)
8729 return t;
8730 if (TREE_CODE (t) != CALL_EXPR && TREE_CODE (t) != AGGR_INIT_EXPR)
8731 return t;
8732 /* Calls to immediate functions returning void need to be
8733 evaluated. */
8734 tree fndecl = cp_get_callee_fndecl_nofold (t);
8735 if (fndecl == NULL_TREE || !DECL_IMMEDIATE_FUNCTION_P (fndecl))
8736 return t;
8737 else
8738 is_consteval = true;
8741 else if (cxx_dialect >= cxx20
8742 && (TREE_CODE (t) == CALL_EXPR
8743 || TREE_CODE (t) == AGGR_INIT_EXPR
8744 || TREE_CODE (t) == TARGET_EXPR))
8746 /* For non-concept checks, determine if it is consteval. */
8747 if (!concept_check_p (t))
8749 tree x = t;
8750 if (TREE_CODE (x) == TARGET_EXPR)
8751 x = TARGET_EXPR_INITIAL (x);
8752 tree fndecl = cp_get_callee_fndecl_nofold (x);
8753 if (fndecl && DECL_IMMEDIATE_FUNCTION_P (fndecl))
8754 is_consteval = true;
8757 if (AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type))
8759 /* In C++14 an NSDMI can participate in aggregate initialization,
8760 and can refer to the address of the object being initialized, so
8761 we need to pass in the relevant VAR_DECL if we want to do the
8762 evaluation in a single pass. The evaluation will dynamically
8763 update ctx.values for the VAR_DECL. We use the same strategy
8764 for C++11 constexpr constructors that refer to the object being
8765 initialized. */
8766 if (constexpr_dtor)
8768 gcc_assert (object && VAR_P (object));
8769 gcc_assert (DECL_DECLARED_CONSTEXPR_P (object));
8770 gcc_assert (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (object));
8771 if (error_operand_p (DECL_INITIAL (object)))
8772 return t;
8773 ctx.ctor = unshare_expr (DECL_INITIAL (object));
8774 TREE_READONLY (ctx.ctor) = false;
8775 /* Temporarily force decl_really_constant_value to return false
8776 for it, we want to use ctx.ctor for the current value instead. */
8777 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (object) = false;
8779 else
8781 ctx.ctor = build_constructor (type, NULL);
8782 CONSTRUCTOR_NO_CLEARING (ctx.ctor) = true;
8784 if (!object)
8786 if (TREE_CODE (t) == CALL_EXPR)
8788 /* If T is calling a constructor to initialize an object, reframe
8789 it as an AGGR_INIT_EXPR to avoid trying to modify an object
8790 from outside the constant evaluation, which will fail even if
8791 the value is actually constant (is_constant_evaluated3.C). */
8792 tree fn = cp_get_callee_fndecl_nofold (t);
8793 if (fn && DECL_CONSTRUCTOR_P (fn))
8795 object = CALL_EXPR_ARG (t, 0);
8796 object = build_fold_indirect_ref (object);
8797 r = build_aggr_init_expr (type, r);
8800 else if (TREE_CODE (t) == TARGET_EXPR)
8801 object = TARGET_EXPR_SLOT (t);
8802 else if (TREE_CODE (t) == AGGR_INIT_EXPR)
8803 object = AGGR_INIT_EXPR_SLOT (t);
8805 ctx.object = object;
8806 if (object)
8807 gcc_assert (same_type_ignoring_top_level_qualifiers_p
8808 (type, TREE_TYPE (object)));
8809 if (object && DECL_P (object))
8810 global_ctx.put_value (object, ctx.ctor);
8811 if (TREE_CODE (r) == TARGET_EXPR)
8812 /* Avoid creating another CONSTRUCTOR when we expand the
8813 TARGET_EXPR. */
8814 r = TARGET_EXPR_INITIAL (r);
8817 auto_vec<tree, 16> cleanups;
8818 global_ctx.cleanups = &cleanups;
8820 if (manifestly_const_eval == mce_true)
8821 instantiate_constexpr_fns (r);
8822 r = cxx_eval_constant_expression (&ctx, r, vc_prvalue,
8823 &non_constant_p, &overflow_p);
8825 if (!constexpr_dtor)
8826 verify_constant (r, allow_non_constant, &non_constant_p, &overflow_p);
8827 else
8828 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (object) = true;
8830 unsigned int i;
8831 tree cleanup;
8832 /* Evaluate the cleanups. */
8833 FOR_EACH_VEC_ELT_REVERSE (cleanups, i, cleanup)
8834 cxx_eval_constant_expression (&ctx, cleanup, vc_discard,
8835 &non_constant_p, &overflow_p);
8837 /* Mutable logic is a bit tricky: we want to allow initialization of
8838 constexpr variables with mutable members, but we can't copy those
8839 members to another constexpr variable. */
8840 if (TREE_CODE (r) == CONSTRUCTOR && CONSTRUCTOR_MUTABLE_POISON (r))
8842 if (!allow_non_constant)
8843 error ("%qE is not a constant expression because it refers to "
8844 "mutable subobjects of %qT", t, type);
8845 non_constant_p = true;
8848 if (TREE_CODE (r) == CONSTRUCTOR && CONSTRUCTOR_NO_CLEARING (r))
8850 if (!allow_non_constant)
8851 error ("%qE is not a constant expression because it refers to "
8852 "an incompletely initialized variable", t);
8853 TREE_CONSTANT (r) = false;
8854 non_constant_p = true;
8857 if (!non_constant_p && cxx_dialect >= cxx20
8858 && !global_ctx.heap_vars.is_empty ())
8860 tree heap_var = cp_walk_tree_without_duplicates (&r, find_heap_var_refs,
8861 NULL);
8862 unsigned int i;
8863 if (heap_var)
8865 if (!allow_non_constant && !non_constant_p)
8866 error_at (DECL_SOURCE_LOCATION (heap_var),
8867 "%qE is not a constant expression because it refers to "
8868 "a result of %<operator new%>", t);
8869 r = t;
8870 non_constant_p = true;
8872 FOR_EACH_VEC_ELT (global_ctx.heap_vars, i, heap_var)
8874 if (DECL_NAME (heap_var) != heap_deleted_identifier)
8876 if (!allow_non_constant && !non_constant_p)
8877 error_at (DECL_SOURCE_LOCATION (heap_var),
8878 "%qE is not a constant expression because allocated "
8879 "storage has not been deallocated", t);
8880 r = t;
8881 non_constant_p = true;
8883 varpool_node::get (heap_var)->remove ();
8887 /* Check that immediate invocation does not return an expression referencing
8888 any immediate function decls. */
8889 if (!non_constant_p && cxx_dialect >= cxx20)
8890 if (tree immediate_fndecl
8891 = cp_walk_tree_without_duplicates (&r, find_immediate_fndecl,
8892 NULL))
8894 if (!allow_non_constant && !non_constant_p)
8896 if (is_consteval)
8897 error_at (cp_expr_loc_or_input_loc (t),
8898 "immediate evaluation returns address of immediate "
8899 "function %qD", immediate_fndecl);
8900 else
8901 error_at (cp_expr_loc_or_input_loc (t),
8902 "constant evaluation returns address of immediate "
8903 "function %qD", immediate_fndecl);
8905 r = t;
8906 non_constant_p = true;
8909 if (non_constant_p)
8910 /* If we saw something bad, go back to our argument. The wrapping below is
8911 only for the cases of TREE_CONSTANT argument or overflow. */
8912 r = t;
8914 if (!non_constant_p && overflow_p)
8915 non_constant_p = true;
8917 /* Unshare the result. */
8918 bool should_unshare = true;
8919 if (r == t || (TREE_CODE (t) == TARGET_EXPR
8920 && TARGET_EXPR_INITIAL (t) == r))
8921 should_unshare = false;
8923 if (non_constant_p && !allow_non_constant)
8924 return error_mark_node;
8925 else if (constexpr_dtor)
8926 return r;
8927 else if (non_constant_p && TREE_CONSTANT (r))
8928 r = mark_non_constant (r);
8929 else if (non_constant_p)
8930 return t;
8932 if (should_unshare)
8933 r = unshare_expr (r);
8935 if (TREE_CODE (r) == CONSTRUCTOR && CLASS_TYPE_P (TREE_TYPE (r)))
8937 r = adjust_temp_type (type, r);
8938 if (TREE_CODE (t) == TARGET_EXPR
8939 && TARGET_EXPR_INITIAL (t) == r)
8940 return t;
8941 else if (TREE_CODE (t) == CONSTRUCTOR || TREE_CODE (t) == CALL_EXPR)
8942 /* Don't add a TARGET_EXPR if our argument didn't have one. */;
8943 else if (TREE_CODE (t) == TARGET_EXPR && TARGET_EXPR_CLEANUP (t))
8944 r = get_target_expr (r);
8945 else
8947 r = get_target_expr (r, tf_warning_or_error | tf_no_cleanup);
8948 TREE_CONSTANT (r) = true;
8952 if (TREE_CODE (t) == TARGET_EXPR
8953 && TREE_CODE (r) == TARGET_EXPR)
8955 /* Preserve this flag for potential_constant_expression, and the others
8956 for good measure. */
8957 TARGET_EXPR_ELIDING_P (r) = TARGET_EXPR_ELIDING_P (t);
8958 TARGET_EXPR_IMPLICIT_P (r) = TARGET_EXPR_IMPLICIT_P (t);
8959 TARGET_EXPR_LIST_INIT_P (r) = TARGET_EXPR_LIST_INIT_P (t);
8960 TARGET_EXPR_DIRECT_INIT_P (r) = TARGET_EXPR_DIRECT_INIT_P (t);
8963 /* Remember the original location if that wouldn't need a wrapper. */
8964 if (location_t loc = EXPR_LOCATION (t))
8965 protected_set_expr_location (r, loc);
8967 return r;
8970 /* If T represents a constant expression returns its reduced value.
8971 Otherwise return error_mark_node. */
8973 tree
8974 cxx_constant_value (tree t, tree decl /* = NULL_TREE */,
8975 tsubst_flags_t complain /* = tf_error */)
8977 bool sfinae = !(complain & tf_error);
8978 tree r = cxx_eval_outermost_constant_expr (t, sfinae, true, mce_true, false, decl);
8979 if (sfinae && !TREE_CONSTANT (r))
8980 r = error_mark_node;
8981 return r;
8984 /* Like cxx_constant_value, but used for evaluation of constexpr destructors
8985 of constexpr variables. The actual initializer of DECL is not modified. */
8987 void
8988 cxx_constant_dtor (tree t, tree decl)
8990 cxx_eval_outermost_constant_expr (t, false, true, mce_true, true, decl);
8993 /* Helper routine for fold_simple function. Either return simplified
8994 expression T, otherwise NULL_TREE.
8995 In contrast to cp_fully_fold, and to maybe_constant_value, we try to fold
8996 even if we are within template-declaration. So be careful on call, as in
8997 such case types can be undefined. */
8999 static tree
9000 fold_simple_1 (tree t)
9002 tree op1;
9003 enum tree_code code = TREE_CODE (t);
9005 switch (code)
9007 case INTEGER_CST:
9008 case REAL_CST:
9009 case VECTOR_CST:
9010 case FIXED_CST:
9011 case COMPLEX_CST:
9012 return t;
9014 case SIZEOF_EXPR:
9015 return fold_sizeof_expr (t);
9017 case ABS_EXPR:
9018 case ABSU_EXPR:
9019 case CONJ_EXPR:
9020 case REALPART_EXPR:
9021 case IMAGPART_EXPR:
9022 case NEGATE_EXPR:
9023 case BIT_NOT_EXPR:
9024 case TRUTH_NOT_EXPR:
9025 case VIEW_CONVERT_EXPR:
9026 CASE_CONVERT:
9027 case FLOAT_EXPR:
9028 case FIX_TRUNC_EXPR:
9029 case FIXED_CONVERT_EXPR:
9030 case ADDR_SPACE_CONVERT_EXPR:
9032 op1 = TREE_OPERAND (t, 0);
9034 t = const_unop (code, TREE_TYPE (t), op1);
9035 if (!t)
9036 return NULL_TREE;
9038 if (CONVERT_EXPR_CODE_P (code)
9039 && TREE_OVERFLOW_P (t) && !TREE_OVERFLOW_P (op1))
9040 TREE_OVERFLOW (t) = false;
9041 return t;
9043 default:
9044 return NULL_TREE;
9048 /* If T is a simple constant expression, returns its simplified value.
9049 Otherwise returns T. In contrast to maybe_constant_value we
9050 simplify only few operations on constant-expressions, and we don't
9051 try to simplify constexpressions. */
9053 tree
9054 fold_simple (tree t)
9056 if (processing_template_decl)
9057 return t;
9059 tree r = fold_simple_1 (t);
9060 if (r)
9061 return r;
9063 return t;
9066 /* Try folding the expression T to a simple constant.
9067 Returns that constant, otherwise returns T. */
9069 tree
9070 fold_to_constant (tree t)
9072 tree r = fold (t);
9073 if (CONSTANT_CLASS_P (r) && !TREE_OVERFLOW (r))
9074 return r;
9075 else
9076 return t;
9079 /* If T is a constant expression, returns its reduced value.
9080 Otherwise, if T does not have TREE_CONSTANT set, returns T.
9081 Otherwise, returns a version of T without TREE_CONSTANT.
9082 MANIFESTLY_CONST_EVAL is true if T is manifestly const-evaluated
9083 as per P0595. */
9085 static GTY((deletable)) hash_map<tree, tree> *cv_cache;
9087 tree
9088 maybe_constant_value (tree t, tree decl /* = NULL_TREE */,
9089 mce_value manifestly_const_eval /* = mce_unknown */)
9091 tree r;
9093 if (!is_nondependent_constant_expression (t))
9095 if (TREE_OVERFLOW_P (t)
9096 || (!processing_template_decl && TREE_CONSTANT (t)))
9097 t = mark_non_constant (t);
9098 return t;
9100 else if (CONSTANT_CLASS_P (t))
9101 /* No caching or evaluation needed. */
9102 return t;
9104 /* Don't constant evaluate an unevaluated non-manifestly-constant operand,
9105 but at least try folding it to a simple constant. */
9106 if (cp_unevaluated_operand && manifestly_const_eval != mce_true)
9107 return fold_to_constant (t);
9109 if (manifestly_const_eval != mce_unknown)
9110 return cxx_eval_outermost_constant_expr (t, true, true,
9111 manifestly_const_eval, false, decl);
9113 if (cv_cache == NULL)
9114 cv_cache = hash_map<tree, tree>::create_ggc (101);
9115 if (tree *cached = cv_cache->get (t))
9117 r = *cached;
9118 if (r != t)
9120 /* Clear processing_template_decl for sake of break_out_target_exprs;
9121 entries in the cv_cache are non-templated. */
9122 processing_template_decl_sentinel ptds;
9124 r = break_out_target_exprs (r, /*clear_loc*/true);
9125 protected_set_expr_location (r, EXPR_LOCATION (t));
9127 return r;
9130 uid_sensitive_constexpr_evaluation_checker c;
9131 r = cxx_eval_outermost_constant_expr (t, true, true,
9132 manifestly_const_eval, false, decl);
9133 gcc_checking_assert (r == t
9134 || CONVERT_EXPR_P (t)
9135 || TREE_CODE (t) == VIEW_CONVERT_EXPR
9136 || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
9137 || !cp_tree_equal (r, t));
9138 if (!c.evaluation_restricted_p ())
9139 cv_cache->put (t, r);
9140 return r;
9143 /* Dispose of the whole CV_CACHE. */
9145 static void
9146 clear_cv_cache (void)
9148 if (cv_cache != NULL)
9149 cv_cache->empty ();
9152 /* Dispose of the whole CV_CACHE and FOLD_CACHE. */
9154 void
9155 clear_cv_and_fold_caches ()
9157 clear_cv_cache ();
9158 clear_fold_cache ();
9161 /* Internal function handling expressions in templates for
9162 fold_non_dependent_expr and fold_non_dependent_init.
9164 If we're in a template, but T isn't value dependent, simplify
9165 it. We're supposed to treat:
9167 template <typename T> void f(T[1 + 1]);
9168 template <typename T> void f(T[2]);
9170 as two declarations of the same function, for example. */
9172 static tree
9173 fold_non_dependent_expr_template (tree t, tsubst_flags_t complain,
9174 bool manifestly_const_eval,
9175 tree object)
9177 gcc_assert (processing_template_decl);
9179 if (is_nondependent_constant_expression (t))
9181 processing_template_decl_sentinel s;
9182 t = instantiate_non_dependent_expr_internal (t, complain);
9184 if (type_unknown_p (t) || BRACE_ENCLOSED_INITIALIZER_P (t))
9186 if (TREE_OVERFLOW_P (t))
9188 t = build_nop (TREE_TYPE (t), t);
9189 TREE_CONSTANT (t) = false;
9191 return t;
9193 else if (CONSTANT_CLASS_P (t))
9194 /* No evaluation needed. */
9195 return t;
9197 /* Don't constant evaluate an unevaluated non-manifestly-constant operand,
9198 but at least try folding it to a simple constant. */
9199 if (cp_unevaluated_operand && !manifestly_const_eval)
9200 return fold_to_constant (t);
9202 tree r = cxx_eval_outermost_constant_expr (t, true, true,
9203 mce_value (manifestly_const_eval),
9204 false, object);
9205 /* cp_tree_equal looks through NOPs, so allow them. */
9206 gcc_checking_assert (r == t
9207 || CONVERT_EXPR_P (t)
9208 || TREE_CODE (t) == VIEW_CONVERT_EXPR
9209 || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
9210 || !cp_tree_equal (r, t));
9211 return r;
9213 else if (TREE_OVERFLOW_P (t))
9215 t = build_nop (TREE_TYPE (t), t);
9216 TREE_CONSTANT (t) = false;
9219 return t;
9222 /* Like maybe_constant_value but first fully instantiate the argument.
9224 Note: this is equivalent to instantiate_non_dependent_expr (t, complain)
9225 followed by maybe_constant_value but is more efficient,
9226 because it calls instantiation_dependent_expression_p and
9227 potential_constant_expression at most once.
9228 The manifestly_const_eval argument is passed to maybe_constant_value.
9230 Callers should generally pass their active complain, or if they are in a
9231 non-template, diagnosing context, they can use the default of
9232 tf_warning_or_error. Callers that might be within a template context, don't
9233 have a complain parameter, and aren't going to remember the result for long
9234 (e.g. null_ptr_cst_p), can pass tf_none and deal with error_mark_node
9235 appropriately. */
9237 tree
9238 fold_non_dependent_expr (tree t,
9239 tsubst_flags_t complain /* = tf_warning_or_error */,
9240 bool manifestly_const_eval /* = false */,
9241 tree object /* = NULL_TREE */)
9243 if (t == NULL_TREE)
9244 return NULL_TREE;
9246 if (processing_template_decl)
9247 return fold_non_dependent_expr_template (t, complain,
9248 manifestly_const_eval, object);
9250 return maybe_constant_value (t, object, mce_value (manifestly_const_eval));
9253 /* Like fold_non_dependent_expr, but if EXPR couldn't be folded to a constant,
9254 return the original expression. */
9256 tree
9257 maybe_fold_non_dependent_expr (tree expr,
9258 tsubst_flags_t complain/*=tf_warning_or_error*/)
9260 tree t = fold_non_dependent_expr (expr, complain);
9261 if (t && TREE_CONSTANT (t))
9262 return t;
9264 return expr;
9267 /* Like maybe_constant_init but first fully instantiate the argument. */
9269 tree
9270 fold_non_dependent_init (tree t,
9271 tsubst_flags_t complain /*=tf_warning_or_error*/,
9272 bool manifestly_const_eval /*=false*/,
9273 tree object /* = NULL_TREE */)
9275 if (t == NULL_TREE)
9276 return NULL_TREE;
9278 if (processing_template_decl)
9280 t = fold_non_dependent_expr_template (t, complain,
9281 manifestly_const_eval, object);
9282 /* maybe_constant_init does this stripping, so do it here too. */
9283 if (TREE_CODE (t) == TARGET_EXPR)
9285 tree init = TARGET_EXPR_INITIAL (t);
9286 if (TREE_CODE (init) == CONSTRUCTOR)
9287 t = init;
9289 return t;
9292 return maybe_constant_init (t, object, manifestly_const_eval);
9295 /* Like maybe_constant_value, but returns a CONSTRUCTOR directly, rather
9296 than wrapped in a TARGET_EXPR.
9297 ALLOW_NON_CONSTANT is false if T is required to be a constant expression.
9298 MANIFESTLY_CONST_EVAL is true if T is manifestly const-evaluated as
9299 per P0595 even when ALLOW_NON_CONSTANT is true. */
9301 static tree
9302 maybe_constant_init_1 (tree t, tree decl, bool allow_non_constant,
9303 bool manifestly_const_eval)
9305 if (!t)
9306 return t;
9307 if (TREE_CODE (t) == EXPR_STMT)
9308 t = TREE_OPERAND (t, 0);
9309 if (TREE_CODE (t) == CONVERT_EXPR
9310 && VOID_TYPE_P (TREE_TYPE (t)))
9311 t = TREE_OPERAND (t, 0);
9312 if (TREE_CODE (t) == INIT_EXPR)
9313 t = TREE_OPERAND (t, 1);
9314 if (TREE_CODE (t) == TARGET_EXPR)
9315 t = TARGET_EXPR_INITIAL (t);
9316 if (!is_nondependent_static_init_expression (t))
9317 /* Don't try to evaluate it. */;
9318 else if (CONSTANT_CLASS_P (t) && TREE_CODE (t) != PTRMEM_CST)
9319 /* No evaluation needed. PTRMEM_CST needs the immediate fn check. */;
9320 else
9322 /* [basic.start.static] allows constant-initialization of variables with
9323 static or thread storage duration even if it isn't required, but we
9324 shouldn't bend the rules the same way for automatic variables. */
9325 bool is_static = (decl && DECL_P (decl)
9326 && (TREE_STATIC (decl) || DECL_EXTERNAL (decl)));
9327 if (is_static)
9328 manifestly_const_eval = true;
9330 if (cp_unevaluated_operand && !manifestly_const_eval)
9331 return fold_to_constant (t);
9333 t = cxx_eval_outermost_constant_expr (t, allow_non_constant, !is_static,
9334 mce_value (manifestly_const_eval),
9335 false, decl);
9337 if (TREE_CODE (t) == TARGET_EXPR)
9339 tree init = TARGET_EXPR_INITIAL (t);
9340 if (TREE_CODE (init) == CONSTRUCTOR)
9341 t = init;
9343 return t;
9346 /* Wrapper for maybe_constant_init_1 which permits non constants. */
9348 tree
9349 maybe_constant_init (tree t, tree decl, bool manifestly_const_eval)
9351 return maybe_constant_init_1 (t, decl, true, manifestly_const_eval);
9354 /* Wrapper for maybe_constant_init_1 which does not permit non constants. */
9356 tree
9357 cxx_constant_init (tree t, tree decl)
9359 return maybe_constant_init_1 (t, decl, false, true);
9362 #if 0
9363 /* FIXME see ADDR_EXPR section in potential_constant_expression_1. */
9364 /* Return true if the object referred to by REF has automatic or thread
9365 local storage. */
9367 enum { ck_ok, ck_bad, ck_unknown };
9368 static int
9369 check_automatic_or_tls (tree ref)
9371 machine_mode mode;
9372 poly_int64 bitsize, bitpos;
9373 tree offset;
9374 int volatilep = 0, unsignedp = 0;
9375 tree decl = get_inner_reference (ref, &bitsize, &bitpos, &offset,
9376 &mode, &unsignedp, &volatilep, false);
9377 duration_kind dk;
9379 /* If there isn't a decl in the middle, we don't know the linkage here,
9380 and this isn't a constant expression anyway. */
9381 if (!DECL_P (decl))
9382 return ck_unknown;
9383 dk = decl_storage_duration (decl);
9384 return (dk == dk_auto || dk == dk_thread) ? ck_bad : ck_ok;
9386 #endif
9388 /* Data structure for passing data from potential_constant_expression_1
9389 to check_for_return_continue via cp_walk_tree. */
9390 struct check_for_return_continue_data {
9391 hash_set<tree> *pset;
9392 tree continue_stmt;
9393 tree break_stmt;
9396 /* Helper function for potential_constant_expression_1 SWITCH_STMT handling,
9397 called through cp_walk_tree. Return the first RETURN_EXPR found, or note
9398 the first CONTINUE_STMT and/or BREAK_STMT if RETURN_EXPR is not found. */
9399 static tree
9400 check_for_return_continue (tree *tp, int *walk_subtrees, void *data)
9402 tree t = *tp, s, b;
9403 check_for_return_continue_data *d = (check_for_return_continue_data *) data;
9404 switch (TREE_CODE (t))
9406 case RETURN_EXPR:
9407 return t;
9409 case CONTINUE_STMT:
9410 if (d->continue_stmt == NULL_TREE)
9411 d->continue_stmt = t;
9412 break;
9414 case BREAK_STMT:
9415 if (d->break_stmt == NULL_TREE)
9416 d->break_stmt = t;
9417 break;
9419 #define RECUR(x) \
9420 if (tree r = cp_walk_tree (&x, check_for_return_continue, data, \
9421 d->pset)) \
9422 return r
9424 /* For loops, walk subtrees manually, so that continue stmts found
9425 inside of the bodies of the loops are ignored. */
9426 case DO_STMT:
9427 *walk_subtrees = 0;
9428 RECUR (DO_COND (t));
9429 s = d->continue_stmt;
9430 b = d->break_stmt;
9431 RECUR (DO_BODY (t));
9432 d->continue_stmt = s;
9433 d->break_stmt = b;
9434 break;
9436 case WHILE_STMT:
9437 *walk_subtrees = 0;
9438 RECUR (WHILE_COND (t));
9439 s = d->continue_stmt;
9440 b = d->break_stmt;
9441 RECUR (WHILE_BODY (t));
9442 d->continue_stmt = s;
9443 d->break_stmt = b;
9444 break;
9446 case FOR_STMT:
9447 *walk_subtrees = 0;
9448 RECUR (FOR_INIT_STMT (t));
9449 RECUR (FOR_COND (t));
9450 RECUR (FOR_EXPR (t));
9451 s = d->continue_stmt;
9452 b = d->break_stmt;
9453 RECUR (FOR_BODY (t));
9454 d->continue_stmt = s;
9455 d->break_stmt = b;
9456 break;
9458 case RANGE_FOR_STMT:
9459 *walk_subtrees = 0;
9460 RECUR (RANGE_FOR_EXPR (t));
9461 s = d->continue_stmt;
9462 b = d->break_stmt;
9463 RECUR (RANGE_FOR_BODY (t));
9464 d->continue_stmt = s;
9465 d->break_stmt = b;
9466 break;
9468 case SWITCH_STMT:
9469 *walk_subtrees = 0;
9470 RECUR (SWITCH_STMT_COND (t));
9471 b = d->break_stmt;
9472 RECUR (SWITCH_STMT_BODY (t));
9473 d->break_stmt = b;
9474 break;
9475 #undef RECUR
9477 case STATEMENT_LIST:
9478 case CONSTRUCTOR:
9479 break;
9481 default:
9482 if (!EXPR_P (t))
9483 *walk_subtrees = 0;
9484 break;
9487 return NULL_TREE;
9490 /* Return true if T denotes a potentially constant expression. Issue
9491 diagnostic as appropriate under control of FLAGS. If WANT_RVAL is true,
9492 an lvalue-rvalue conversion is implied. If NOW is true, we want to
9493 consider the expression in the current context, independent of constexpr
9494 substitution. If FUNDEF_P is true, we're checking a constexpr function body
9495 and hard errors should not be reported by constexpr_error.
9497 C++0x [expr.const] used to say
9499 6 An expression is a potential constant expression if it is
9500 a constant expression where all occurrences of function
9501 parameters are replaced by arbitrary constant expressions
9502 of the appropriate type.
9504 2 A conditional expression is a constant expression unless it
9505 involves one of the following as a potentially evaluated
9506 subexpression (3.2), but subexpressions of logical AND (5.14),
9507 logical OR (5.15), and conditional (5.16) operations that are
9508 not evaluated are not considered. */
9510 static bool
9511 potential_constant_expression_1 (tree t, bool want_rval, bool strict, bool now,
9512 bool fundef_p, tsubst_flags_t flags,
9513 tree *jump_target)
9515 #define RECUR(T,RV) \
9516 potential_constant_expression_1 ((T), (RV), strict, now, fundef_p, flags, \
9517 jump_target)
9519 enum { any = false, rval = true };
9520 int i;
9521 tree tmp;
9523 if (t == error_mark_node)
9524 return false;
9525 if (t == NULL_TREE)
9526 return true;
9527 location_t loc = cp_expr_loc_or_input_loc (t);
9529 if (*jump_target)
9530 /* If we are jumping, ignore everything. This is simpler than the
9531 cxx_eval_constant_expression handling because we only need to be
9532 conservatively correct, and we don't necessarily have a constant value
9533 available, so we don't bother with switch tracking. */
9534 return true;
9536 if (TREE_THIS_VOLATILE (t) && want_rval
9537 && !FUNC_OR_METHOD_TYPE_P (TREE_TYPE (t)))
9539 if (flags & tf_error)
9540 constexpr_error (loc, fundef_p, "lvalue-to-rvalue conversion of "
9541 "a volatile lvalue %qE with type %qT", t,
9542 TREE_TYPE (t));
9543 return false;
9545 if (CONSTANT_CLASS_P (t))
9546 return true;
9547 if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_TYPED)
9548 && TREE_TYPE (t) == error_mark_node)
9549 return false;
9551 switch (TREE_CODE (t))
9553 case FUNCTION_DECL:
9554 case BASELINK:
9555 case TEMPLATE_DECL:
9556 case OVERLOAD:
9557 case TEMPLATE_ID_EXPR:
9558 case LABEL_DECL:
9559 case CASE_LABEL_EXPR:
9560 case PREDICT_EXPR:
9561 case CONST_DECL:
9562 case SIZEOF_EXPR:
9563 case ALIGNOF_EXPR:
9564 case OFFSETOF_EXPR:
9565 case NOEXCEPT_EXPR:
9566 case TEMPLATE_PARM_INDEX:
9567 case TRAIT_EXPR:
9568 case IDENTIFIER_NODE:
9569 case USERDEF_LITERAL:
9570 /* We can see a FIELD_DECL in a pointer-to-member expression. */
9571 case FIELD_DECL:
9572 case RESULT_DECL:
9573 case USING_DECL:
9574 case USING_STMT:
9575 case PLACEHOLDER_EXPR:
9576 case REQUIRES_EXPR:
9577 case STATIC_ASSERT:
9578 case DEBUG_BEGIN_STMT:
9579 return true;
9581 case RETURN_EXPR:
9582 if (!RECUR (TREE_OPERAND (t, 0), any))
9583 return false;
9584 /* FALLTHROUGH */
9586 case BREAK_STMT:
9587 case CONTINUE_STMT:
9588 *jump_target = t;
9589 return true;
9591 case PARM_DECL:
9592 if (now && want_rval)
9594 tree type = TREE_TYPE (t);
9595 if (dependent_type_p (type)
9596 || !COMPLETE_TYPE_P (processing_template_decl
9597 ? type : complete_type (type))
9598 || is_really_empty_class (type, /*ignore_vptr*/false))
9599 /* An empty class has no data to read. */
9600 return true;
9601 if (flags & tf_error)
9602 constexpr_error (input_location, fundef_p,
9603 "%qE is not a constant expression", t);
9604 return false;
9606 return true;
9608 case AGGR_INIT_EXPR:
9609 case CALL_EXPR:
9610 /* -- an invocation of a function other than a constexpr function
9611 or a constexpr constructor. */
9613 tree fun = get_function_named_in_call (t);
9614 const int nargs = call_expr_nargs (t);
9615 i = 0;
9617 if (fun == NULL_TREE)
9619 /* Reset to allow the function to continue past the end
9620 of the block below. Otherwise return early. */
9621 bool bail = true;
9623 if (TREE_CODE (t) == CALL_EXPR
9624 && CALL_EXPR_FN (t) == NULL_TREE)
9625 switch (CALL_EXPR_IFN (t))
9627 /* These should be ignored, they are optimized away from
9628 constexpr functions. */
9629 case IFN_UBSAN_NULL:
9630 case IFN_UBSAN_BOUNDS:
9631 case IFN_UBSAN_VPTR:
9632 case IFN_FALLTHROUGH:
9633 case IFN_ASSUME:
9634 return true;
9636 case IFN_ADD_OVERFLOW:
9637 case IFN_SUB_OVERFLOW:
9638 case IFN_MUL_OVERFLOW:
9639 case IFN_LAUNDER:
9640 case IFN_VEC_CONVERT:
9641 bail = false;
9642 break;
9644 default:
9645 break;
9648 if (bail)
9650 /* fold_call_expr can't do anything with IFN calls. */
9651 if (flags & tf_error)
9652 constexpr_error (loc, fundef_p,
9653 "call to internal function %qE", t);
9654 return false;
9658 if (fun && is_overloaded_fn (fun))
9660 if (!RECUR (fun, true))
9661 return false;
9662 fun = get_fns (fun);
9664 if (TREE_CODE (fun) == FUNCTION_DECL)
9666 if (builtin_valid_in_constant_expr_p (fun))
9667 return true;
9668 if (!maybe_constexpr_fn (fun)
9669 /* Allow any built-in function; if the expansion
9670 isn't constant, we'll deal with that then. */
9671 && !fndecl_built_in_p (fun)
9672 /* In C++20, replaceable global allocation functions
9673 are constant expressions. */
9674 && (!cxx_replaceable_global_alloc_fn (fun)
9675 || TREE_CODE (t) != CALL_EXPR
9676 || (!CALL_FROM_NEW_OR_DELETE_P (t)
9677 && (current_function_decl == NULL_TREE
9678 || !is_std_allocator_allocate
9679 (current_function_decl))))
9680 /* Allow placement new in std::construct_at. */
9681 && (!cxx_placement_new_fn (fun)
9682 || TREE_CODE (t) != CALL_EXPR
9683 || current_function_decl == NULL_TREE
9684 || !is_std_construct_at (current_function_decl))
9685 && !cxx_dynamic_cast_fn_p (fun))
9687 if ((flags & tf_error)
9688 && constexpr_error (loc, fundef_p,
9689 "call to non-%<constexpr%> "
9690 "function %qD", fun))
9691 explain_invalid_constexpr_fn (fun);
9692 return false;
9696 fun = OVL_FIRST (fun);
9697 /* Skip initial arguments to base constructors. */
9698 if (DECL_BASE_CONSTRUCTOR_P (fun))
9699 i = num_artificial_parms_for (fun);
9701 else if (fun)
9703 if (TREE_TYPE (fun)
9704 && FUNCTION_POINTER_TYPE_P (TREE_TYPE (fun)))
9705 want_rval = rval;
9706 else
9707 want_rval = any;
9708 if (RECUR (fun, want_rval))
9709 /* Might end up being a constant function pointer. But it
9710 could also be a function object with constexpr op(), so
9711 we pass 'any' so that the underlying VAR_DECL is deemed
9712 as potentially-constant even though it wasn't declared
9713 constexpr. */;
9714 else
9715 return false;
9717 for (; i < nargs; ++i)
9719 tree x = get_nth_callarg (t, i);
9720 /* In a template, reference arguments haven't been converted to
9721 REFERENCE_TYPE and we might not even know if the parameter
9722 is a reference, so accept lvalue constants too. */
9723 bool rv = processing_template_decl ? any : rval;
9724 /* Don't require an immediately constant value, as constexpr
9725 substitution might not use the value of the argument. */
9726 bool sub_now = false;
9727 if (!potential_constant_expression_1 (x, rv, strict,
9728 sub_now, fundef_p, flags,
9729 jump_target))
9730 return false;
9732 return true;
9735 case NON_LVALUE_EXPR:
9736 /* -- an lvalue-to-rvalue conversion (4.1) unless it is applied to
9737 -- an lvalue of integral type that refers to a non-volatile
9738 const variable or static data member initialized with
9739 constant expressions, or
9741 -- an lvalue of literal type that refers to non-volatile
9742 object defined with constexpr, or that refers to a
9743 sub-object of such an object; */
9744 return RECUR (TREE_OPERAND (t, 0), rval);
9746 case EXCESS_PRECISION_EXPR:
9747 return RECUR (TREE_OPERAND (t, 0), rval);
9749 case VAR_DECL:
9750 if (DECL_HAS_VALUE_EXPR_P (t))
9752 if (now && is_normal_capture_proxy (t))
9754 /* -- in a lambda-expression, a reference to this or to a
9755 variable with automatic storage duration defined outside that
9756 lambda-expression, where the reference would be an
9757 odr-use. */
9759 if (want_rval)
9760 /* Since we're doing an lvalue-rvalue conversion, this might
9761 not be an odr-use, so evaluate the variable directly. */
9762 return RECUR (DECL_CAPTURED_VARIABLE (t), rval);
9764 if (flags & tf_error)
9766 tree cap = DECL_CAPTURED_VARIABLE (t);
9767 auto_diagnostic_group d;
9768 if (constexpr_error (input_location, fundef_p,
9769 "lambda capture of %qE is not a "
9770 "constant expression", cap)
9771 && decl_constant_var_p (cap))
9772 inform (input_location, "because it is used as a glvalue");
9774 return false;
9776 /* Treat __PRETTY_FUNCTION__ inside a template function as
9777 potentially-constant. */
9778 else if (DECL_PRETTY_FUNCTION_P (t)
9779 && DECL_VALUE_EXPR (t) == error_mark_node)
9780 return true;
9781 return RECUR (DECL_VALUE_EXPR (t), rval);
9783 if (want_rval
9784 && (now || !var_in_maybe_constexpr_fn (t))
9785 && !type_dependent_expression_p (t)
9786 && !decl_maybe_constant_var_p (t)
9787 && (strict
9788 || !CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (t))
9789 || (DECL_INITIAL (t)
9790 && !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t)))
9791 && COMPLETE_TYPE_P (TREE_TYPE (t))
9792 && !is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
9794 if (flags & tf_error)
9795 non_const_var_error (loc, t, fundef_p);
9796 return false;
9798 return true;
9800 case NOP_EXPR:
9801 if (REINTERPRET_CAST_P (t))
9803 if (flags & tf_error)
9804 constexpr_error (loc, fundef_p, "%<reinterpret_cast%> is not a "
9805 "constant expression");
9806 return false;
9808 /* FALLTHRU */
9809 case CONVERT_EXPR:
9810 case VIEW_CONVERT_EXPR:
9811 /* -- a reinterpret_cast. FIXME not implemented, and this rule
9812 may change to something more specific to type-punning (DR 1312). */
9814 tree from = TREE_OPERAND (t, 0);
9815 if (location_wrapper_p (t))
9817 iloc_sentinel ils = loc;
9818 return (RECUR (from, want_rval));
9820 if (INDIRECT_TYPE_P (TREE_TYPE (t)))
9822 STRIP_ANY_LOCATION_WRAPPER (from);
9823 if (TREE_CODE (from) == INTEGER_CST
9824 && !integer_zerop (from))
9826 if (flags & tf_error)
9827 constexpr_error (loc, fundef_p,
9828 "%<reinterpret_cast%> from integer to "
9829 "pointer");
9830 return false;
9833 return (RECUR (from, TREE_CODE (t) != VIEW_CONVERT_EXPR));
9836 case ADDRESSOF_EXPR:
9837 /* This is like ADDR_EXPR, except it won't form pointer-to-member. */
9838 t = TREE_OPERAND (t, 0);
9839 goto handle_addr_expr;
9841 case ADDR_EXPR:
9842 /* -- a unary operator & that is applied to an lvalue that
9843 designates an object with thread or automatic storage
9844 duration; */
9845 t = TREE_OPERAND (t, 0);
9847 if (TREE_CODE (t) == OFFSET_REF && PTRMEM_OK_P (t))
9848 /* A pointer-to-member constant. */
9849 return true;
9851 handle_addr_expr:
9852 #if 0
9853 /* FIXME adjust when issue 1197 is fully resolved. For now don't do
9854 any checking here, as we might dereference the pointer later. If
9855 we remove this code, also remove check_automatic_or_tls. */
9856 i = check_automatic_or_tls (t);
9857 if (i == ck_ok)
9858 return true;
9859 if (i == ck_bad)
9861 if (flags & tf_error)
9862 error ("address-of an object %qE with thread local or "
9863 "automatic storage is not a constant expression", t);
9864 return false;
9866 #endif
9867 return RECUR (t, any);
9869 case COMPONENT_REF:
9870 case ARROW_EXPR:
9871 case OFFSET_REF:
9872 /* -- a class member access unless its postfix-expression is
9873 of literal type or of pointer to literal type. */
9874 /* This test would be redundant, as it follows from the
9875 postfix-expression being a potential constant expression. */
9876 if (type_unknown_p (t))
9877 return true;
9878 if (is_overloaded_fn (t))
9879 /* In a template, a COMPONENT_REF of a function expresses ob.fn(),
9880 which uses ob as an lvalue. */
9881 want_rval = false;
9882 gcc_fallthrough ();
9884 case REALPART_EXPR:
9885 case IMAGPART_EXPR:
9886 case BIT_FIELD_REF:
9887 return RECUR (TREE_OPERAND (t, 0), want_rval);
9889 case EXPR_PACK_EXPANSION:
9890 return RECUR (PACK_EXPANSION_PATTERN (t), want_rval);
9892 case INDIRECT_REF:
9894 tree x = TREE_OPERAND (t, 0);
9895 STRIP_NOPS (x);
9896 if (is_this_parameter (x) && !is_capture_proxy (x))
9898 if (now || !var_in_maybe_constexpr_fn (x))
9900 if (flags & tf_error)
9901 constexpr_error (loc, fundef_p, "use of %<this%> in a "
9902 "constant expression");
9903 return false;
9905 return true;
9907 return RECUR (x, rval);
9910 case STATEMENT_LIST:
9911 for (tree stmt : tsi_range (t))
9912 if (!RECUR (stmt, any))
9913 return false;
9914 return true;
9916 case MODIFY_EXPR:
9917 if (cxx_dialect < cxx14)
9918 goto fail;
9919 if (!RECUR (TREE_OPERAND (t, 0), any))
9920 return false;
9921 /* Just ignore clobbers. */
9922 if (TREE_CLOBBER_P (TREE_OPERAND (t, 1)))
9923 return true;
9924 if (!RECUR (TREE_OPERAND (t, 1), rval))
9925 return false;
9926 return true;
9928 case MODOP_EXPR:
9929 if (cxx_dialect < cxx14)
9930 goto fail;
9931 if (!RECUR (TREE_OPERAND (t, 0), rval))
9932 return false;
9933 if (!RECUR (TREE_OPERAND (t, 2), rval))
9934 return false;
9935 return true;
9937 case DO_STMT:
9938 if (!RECUR (DO_COND (t), rval))
9939 return false;
9940 if (!RECUR (DO_BODY (t), any))
9941 return false;
9942 if (breaks (jump_target) || continues (jump_target))
9943 *jump_target = NULL_TREE;
9944 return true;
9946 case FOR_STMT:
9947 if (!RECUR (FOR_INIT_STMT (t), any))
9948 return false;
9949 tmp = FOR_COND (t);
9950 if (!RECUR (tmp, rval))
9951 return false;
9952 if (tmp)
9954 if (!processing_template_decl)
9955 tmp = cxx_eval_outermost_constant_expr (tmp, true);
9956 /* If we couldn't evaluate the condition, it might not ever be
9957 true. */
9958 if (!integer_onep (tmp))
9960 /* Before returning true, check if the for body can contain
9961 a return. */
9962 hash_set<tree> pset;
9963 check_for_return_continue_data data = { &pset, NULL_TREE,
9964 NULL_TREE };
9965 if (tree ret_expr
9966 = cp_walk_tree (&FOR_BODY (t), check_for_return_continue,
9967 &data, &pset))
9968 *jump_target = ret_expr;
9969 return true;
9972 if (!RECUR (FOR_EXPR (t), any))
9973 return false;
9974 if (!RECUR (FOR_BODY (t), any))
9975 return false;
9976 if (breaks (jump_target) || continues (jump_target))
9977 *jump_target = NULL_TREE;
9978 return true;
9980 case RANGE_FOR_STMT:
9981 if (!RECUR (RANGE_FOR_INIT_STMT (t), any))
9982 return false;
9983 if (!RECUR (RANGE_FOR_EXPR (t), any))
9984 return false;
9985 if (!RECUR (RANGE_FOR_BODY (t), any))
9986 return false;
9987 if (breaks (jump_target) || continues (jump_target))
9988 *jump_target = NULL_TREE;
9989 return true;
9991 case WHILE_STMT:
9992 tmp = WHILE_COND (t);
9993 if (!RECUR (tmp, rval))
9994 return false;
9995 if (!processing_template_decl)
9996 tmp = cxx_eval_outermost_constant_expr (tmp, true);
9997 /* If we couldn't evaluate the condition, it might not ever be true. */
9998 if (!integer_onep (tmp))
10000 /* Before returning true, check if the while body can contain
10001 a return. */
10002 hash_set<tree> pset;
10003 check_for_return_continue_data data = { &pset, NULL_TREE,
10004 NULL_TREE };
10005 if (tree ret_expr
10006 = cp_walk_tree (&WHILE_BODY (t), check_for_return_continue,
10007 &data, &pset))
10008 *jump_target = ret_expr;
10009 return true;
10011 if (!RECUR (WHILE_BODY (t), any))
10012 return false;
10013 if (breaks (jump_target) || continues (jump_target))
10014 *jump_target = NULL_TREE;
10015 return true;
10017 case SWITCH_STMT:
10018 if (!RECUR (SWITCH_STMT_COND (t), rval))
10019 return false;
10020 /* FIXME we don't check SWITCH_STMT_BODY currently, because even
10021 unreachable labels would be checked and it is enough if there is
10022 a single switch cond value for which it is a valid constant
10023 expression. We need to check if there are any RETURN_EXPRs
10024 or CONTINUE_STMTs inside of the body though, as in that case
10025 we need to set *jump_target. */
10026 else
10028 hash_set<tree> pset;
10029 check_for_return_continue_data data = { &pset, NULL_TREE,
10030 NULL_TREE };
10031 if (tree ret_expr
10032 = cp_walk_tree (&SWITCH_STMT_BODY (t), check_for_return_continue,
10033 &data, &pset))
10034 /* The switch might return. */
10035 *jump_target = ret_expr;
10036 else if (data.continue_stmt)
10037 /* The switch can't return, but might continue. */
10038 *jump_target = data.continue_stmt;
10040 return true;
10042 case STMT_EXPR:
10043 return RECUR (STMT_EXPR_STMT (t), rval);
10045 case LAMBDA_EXPR:
10046 if (cxx_dialect >= cxx17)
10047 /* In C++17 lambdas can be constexpr, don't give up yet. */
10048 return true;
10049 else if (flags & tf_error)
10050 constexpr_error (loc, fundef_p, "lambda-expression is not a "
10051 "constant expression before C++17");
10052 return false;
10054 case NEW_EXPR:
10055 case VEC_NEW_EXPR:
10056 case DELETE_EXPR:
10057 case VEC_DELETE_EXPR:
10058 if (cxx_dialect >= cxx20)
10059 /* In C++20, new-expressions are potentially constant. */
10060 return true;
10061 else if (flags & tf_error)
10062 constexpr_error (loc, fundef_p, "new-expression is not a "
10063 "constant expression before C++20");
10064 return false;
10066 case DYNAMIC_CAST_EXPR:
10067 case PSEUDO_DTOR_EXPR:
10068 case THROW_EXPR:
10069 case OMP_PARALLEL:
10070 case OMP_TASK:
10071 case OMP_FOR:
10072 case OMP_SIMD:
10073 case OMP_DISTRIBUTE:
10074 case OMP_TASKLOOP:
10075 case OMP_LOOP:
10076 case OMP_TEAMS:
10077 case OMP_TARGET_DATA:
10078 case OMP_TARGET:
10079 case OMP_SECTIONS:
10080 case OMP_ORDERED:
10081 case OMP_CRITICAL:
10082 case OMP_SINGLE:
10083 case OMP_SCAN:
10084 case OMP_SCOPE:
10085 case OMP_SECTION:
10086 case OMP_MASTER:
10087 case OMP_MASKED:
10088 case OMP_TASKGROUP:
10089 case OMP_TARGET_UPDATE:
10090 case OMP_TARGET_ENTER_DATA:
10091 case OMP_TARGET_EXIT_DATA:
10092 case OMP_ATOMIC:
10093 case OMP_ATOMIC_READ:
10094 case OMP_ATOMIC_CAPTURE_OLD:
10095 case OMP_ATOMIC_CAPTURE_NEW:
10096 case OMP_DEPOBJ:
10097 case OACC_PARALLEL:
10098 case OACC_KERNELS:
10099 case OACC_SERIAL:
10100 case OACC_DATA:
10101 case OACC_HOST_DATA:
10102 case OACC_LOOP:
10103 case OACC_CACHE:
10104 case OACC_DECLARE:
10105 case OACC_ENTER_DATA:
10106 case OACC_EXIT_DATA:
10107 case OACC_UPDATE:
10108 case OMP_ARRAY_SECTION:
10109 /* GCC internal stuff. */
10110 case VA_ARG_EXPR:
10111 case TRANSACTION_EXPR:
10112 case AT_ENCODE_EXPR:
10113 fail:
10114 if (flags & tf_error)
10115 constexpr_error (loc, fundef_p, "expression %qE is not a constant "
10116 "expression", t);
10117 return false;
10119 case ASM_EXPR:
10120 if (flags & tf_error)
10121 inline_asm_in_constexpr_error (loc, fundef_p);
10122 return false;
10124 case OBJ_TYPE_REF:
10125 if (cxx_dialect >= cxx20)
10126 /* In C++20 virtual calls can be constexpr, don't give up yet. */
10127 return true;
10128 else if (flags & tf_error)
10129 constexpr_error (loc, fundef_p, "virtual functions cannot be "
10130 "%<constexpr%> before C++20");
10131 return false;
10133 case TYPEID_EXPR:
10134 /* In C++20, a typeid expression whose operand is of polymorphic
10135 class type can be constexpr. */
10137 tree e = TREE_OPERAND (t, 0);
10138 if (cxx_dialect < cxx20
10139 && strict
10140 && !TYPE_P (e)
10141 && !type_dependent_expression_p (e)
10142 && TYPE_POLYMORPHIC_P (TREE_TYPE (e)))
10144 if (flags & tf_error)
10145 constexpr_error (loc, fundef_p, "%<typeid%> is not a "
10146 "constant expression because %qE is "
10147 "of polymorphic type", e);
10148 return false;
10150 return true;
10153 case POINTER_DIFF_EXPR:
10154 case MINUS_EXPR:
10155 want_rval = true;
10156 goto binary;
10158 case LT_EXPR:
10159 case LE_EXPR:
10160 case GT_EXPR:
10161 case GE_EXPR:
10162 case EQ_EXPR:
10163 case NE_EXPR:
10164 case SPACESHIP_EXPR:
10165 want_rval = true;
10166 goto binary;
10168 case PREINCREMENT_EXPR:
10169 case POSTINCREMENT_EXPR:
10170 case PREDECREMENT_EXPR:
10171 case POSTDECREMENT_EXPR:
10172 if (cxx_dialect < cxx14)
10173 goto fail;
10174 goto unary;
10176 case BIT_NOT_EXPR:
10177 /* A destructor. */
10178 if (TYPE_P (TREE_OPERAND (t, 0)))
10179 return true;
10180 /* fall through. */
10182 case CONJ_EXPR:
10183 case SAVE_EXPR:
10184 case FIX_TRUNC_EXPR:
10185 case FLOAT_EXPR:
10186 case NEGATE_EXPR:
10187 case ABS_EXPR:
10188 case ABSU_EXPR:
10189 case TRUTH_NOT_EXPR:
10190 case FIXED_CONVERT_EXPR:
10191 case UNARY_PLUS_EXPR:
10192 case UNARY_LEFT_FOLD_EXPR:
10193 case UNARY_RIGHT_FOLD_EXPR:
10194 unary:
10195 return RECUR (TREE_OPERAND (t, 0), rval);
10197 case CAST_EXPR:
10198 case CONST_CAST_EXPR:
10199 case STATIC_CAST_EXPR:
10200 case REINTERPRET_CAST_EXPR:
10201 case IMPLICIT_CONV_EXPR:
10202 if (!cast_valid_in_integral_constant_expression_p (TREE_TYPE (t)))
10203 /* In C++98, a conversion to non-integral type can't be part of a
10204 constant expression. */
10206 if (flags & tf_error)
10207 constexpr_error (loc, fundef_p,
10208 "cast to non-integral type %qT in a constant "
10209 "expression", TREE_TYPE (t));
10210 return false;
10212 /* This might be a conversion from a class to a (potentially) literal
10213 type. Let's consider it potentially constant since the conversion
10214 might be a constexpr user-defined conversion. */
10215 else if (cxx_dialect >= cxx11
10216 && (dependent_type_p (TREE_TYPE (t))
10217 || !COMPLETE_TYPE_P (TREE_TYPE (t))
10218 || literal_type_p (TREE_TYPE (t)))
10219 && TREE_OPERAND (t, 0))
10221 tree type = TREE_TYPE (TREE_OPERAND (t, 0));
10222 /* If this is a dependent type, it could end up being a class
10223 with conversions. */
10224 if (type == NULL_TREE || WILDCARD_TYPE_P (type))
10225 return true;
10226 /* Or a non-dependent class which has conversions. */
10227 else if (CLASS_TYPE_P (type)
10228 && (TYPE_HAS_CONVERSION (type) || dependent_scope_p (type)))
10229 return true;
10232 return (RECUR (TREE_OPERAND (t, 0),
10233 !TYPE_REF_P (TREE_TYPE (t))));
10235 case BIND_EXPR:
10236 return RECUR (BIND_EXPR_BODY (t), want_rval);
10238 case CLEANUP_POINT_EXPR:
10239 case MUST_NOT_THROW_EXPR:
10240 case TRY_CATCH_EXPR:
10241 case TRY_BLOCK:
10242 case EH_SPEC_BLOCK:
10243 case EXPR_STMT:
10244 case PAREN_EXPR:
10245 /* For convenience. */
10246 case LOOP_EXPR:
10247 case EXIT_EXPR:
10248 return RECUR (TREE_OPERAND (t, 0), want_rval);
10250 case DECL_EXPR:
10251 tmp = DECL_EXPR_DECL (t);
10252 if (VAR_P (tmp) && !DECL_ARTIFICIAL (tmp)
10253 && (processing_template_decl
10254 ? !decl_maybe_constant_var_p (tmp)
10255 : !decl_constant_var_p (tmp)))
10257 if (CP_DECL_THREAD_LOCAL_P (tmp) && !DECL_REALLY_EXTERN (tmp))
10259 if (flags & tf_error)
10260 constexpr_error (DECL_SOURCE_LOCATION (tmp), fundef_p,
10261 "%qD defined %<thread_local%> in "
10262 "%<constexpr%> context", tmp);
10263 return false;
10265 else if (TREE_STATIC (tmp))
10267 if (flags & tf_error)
10268 constexpr_error (DECL_SOURCE_LOCATION (tmp), fundef_p,
10269 "%qD defined %<static%> in %<constexpr%> "
10270 "context", tmp);
10271 return false;
10273 else if (!check_for_uninitialized_const_var
10274 (tmp, /*constexpr_context_p=*/true, flags))
10275 return false;
10277 if (VAR_P (tmp))
10278 return RECUR (DECL_INITIAL (tmp), want_rval);
10279 return true;
10281 case TRY_FINALLY_EXPR:
10282 return (RECUR (TREE_OPERAND (t, 0), want_rval)
10283 && RECUR (TREE_OPERAND (t, 1), any));
10285 case SCOPE_REF:
10286 return RECUR (TREE_OPERAND (t, 1), want_rval);
10288 case TARGET_EXPR:
10289 if (!TARGET_EXPR_DIRECT_INIT_P (t)
10290 && !TARGET_EXPR_ELIDING_P (t)
10291 && !literal_type_p (TREE_TYPE (t)))
10293 if (flags & tf_error)
10295 auto_diagnostic_group d;
10296 if (constexpr_error (loc, fundef_p,
10297 "temporary of non-literal type %qT in a "
10298 "constant expression", TREE_TYPE (t)))
10299 explain_non_literal_class (TREE_TYPE (t));
10301 return false;
10303 /* FALLTHRU */
10304 case INIT_EXPR:
10305 return RECUR (TREE_OPERAND (t, 1), rval);
10307 case CONSTRUCTOR:
10309 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
10310 constructor_elt *ce;
10311 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
10312 if (!RECUR (ce->value, want_rval))
10313 return false;
10314 return true;
10317 case TREE_LIST:
10319 gcc_assert (TREE_PURPOSE (t) == NULL_TREE
10320 || DECL_P (TREE_PURPOSE (t)));
10321 if (!RECUR (TREE_VALUE (t), want_rval))
10322 return false;
10323 if (TREE_CHAIN (t) == NULL_TREE)
10324 return true;
10325 return RECUR (TREE_CHAIN (t), want_rval);
10328 case TRUNC_DIV_EXPR:
10329 case CEIL_DIV_EXPR:
10330 case FLOOR_DIV_EXPR:
10331 case ROUND_DIV_EXPR:
10332 case TRUNC_MOD_EXPR:
10333 case CEIL_MOD_EXPR:
10334 case ROUND_MOD_EXPR:
10336 tree denom = TREE_OPERAND (t, 1);
10337 if (!RECUR (denom, rval))
10338 return false;
10339 /* We can't call cxx_eval_outermost_constant_expr on an expression
10340 that hasn't been through instantiate_non_dependent_expr yet. */
10341 if (!processing_template_decl)
10342 denom = cxx_eval_outermost_constant_expr (denom, true);
10343 if (integer_zerop (denom))
10345 if (flags & tf_error)
10346 constexpr_error (input_location, fundef_p,
10347 "division by zero is not a constant expression");
10348 return false;
10350 else
10352 want_rval = true;
10353 return RECUR (TREE_OPERAND (t, 0), want_rval);
10357 case COMPOUND_EXPR:
10359 /* check_return_expr sometimes wraps a TARGET_EXPR in a
10360 COMPOUND_EXPR; don't get confused. */
10361 tree op0 = TREE_OPERAND (t, 0);
10362 tree op1 = TREE_OPERAND (t, 1);
10363 STRIP_NOPS (op1);
10364 if (TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
10365 return RECUR (op0, want_rval);
10366 else
10367 goto binary;
10370 /* If the first operand is the non-short-circuit constant, look at
10371 the second operand; otherwise we only care about the first one for
10372 potentiality. */
10373 case TRUTH_AND_EXPR:
10374 case TRUTH_ANDIF_EXPR:
10375 tmp = boolean_true_node;
10376 goto truth;
10377 case TRUTH_OR_EXPR:
10378 case TRUTH_ORIF_EXPR:
10379 tmp = boolean_false_node;
10380 truth:
10382 tree op0 = TREE_OPERAND (t, 0);
10383 tree op1 = TREE_OPERAND (t, 1);
10384 if (!RECUR (op0, rval))
10385 return false;
10386 if (!(flags & tf_error) && RECUR (op1, rval))
10387 /* When quiet, try to avoid expensive trial evaluation by first
10388 checking potentiality of the second operand. */
10389 return true;
10390 if (!processing_template_decl)
10391 op0 = cxx_eval_outermost_constant_expr (op0, true);
10392 if (tree_int_cst_equal (op0, tmp))
10393 return (flags & tf_error) ? RECUR (op1, rval) : false;
10394 else
10395 return true;
10398 case PLUS_EXPR:
10399 case MULT_EXPR:
10400 case POINTER_PLUS_EXPR:
10401 case RDIV_EXPR:
10402 case EXACT_DIV_EXPR:
10403 case MIN_EXPR:
10404 case MAX_EXPR:
10405 case LSHIFT_EXPR:
10406 case RSHIFT_EXPR:
10407 case LROTATE_EXPR:
10408 case RROTATE_EXPR:
10409 case BIT_IOR_EXPR:
10410 case BIT_XOR_EXPR:
10411 case BIT_AND_EXPR:
10412 case TRUTH_XOR_EXPR:
10413 case UNORDERED_EXPR:
10414 case ORDERED_EXPR:
10415 case UNLT_EXPR:
10416 case UNLE_EXPR:
10417 case UNGT_EXPR:
10418 case UNGE_EXPR:
10419 case UNEQ_EXPR:
10420 case LTGT_EXPR:
10421 case RANGE_EXPR:
10422 case COMPLEX_EXPR:
10423 want_rval = true;
10424 /* Fall through. */
10425 case ARRAY_REF:
10426 case ARRAY_RANGE_REF:
10427 case MEMBER_REF:
10428 case DOTSTAR_EXPR:
10429 case MEM_REF:
10430 case BINARY_LEFT_FOLD_EXPR:
10431 case BINARY_RIGHT_FOLD_EXPR:
10432 binary:
10433 for (i = 0; i < 2; ++i)
10434 if (!RECUR (TREE_OPERAND (t, i), want_rval))
10435 return false;
10436 return true;
10438 case VEC_PERM_EXPR:
10439 for (i = 0; i < 3; ++i)
10440 if (!RECUR (TREE_OPERAND (t, i), true))
10441 return false;
10442 return true;
10444 case COND_EXPR:
10445 if (COND_EXPR_IS_VEC_DELETE (t) && cxx_dialect < cxx20)
10447 if (flags & tf_error)
10448 constexpr_error (loc, fundef_p, "%<delete[]%> is not a "
10449 "constant expression");
10450 return false;
10452 /* Fall through. */
10453 case IF_STMT:
10454 case VEC_COND_EXPR:
10455 /* If the condition is a known constant, we know which of the legs we
10456 care about; otherwise we only require that the condition and
10457 either of the legs be potentially constant. */
10458 tmp = TREE_OPERAND (t, 0);
10459 if (!RECUR (tmp, rval))
10460 return false;
10461 if (!processing_template_decl)
10462 tmp = cxx_eval_outermost_constant_expr (tmp, true);
10463 /* potential_constant_expression* isn't told if it is called for
10464 manifestly_const_eval or not, so for consteval if always
10465 process both branches as if the condition is not a known
10466 constant. */
10467 if (TREE_CODE (t) != IF_STMT || !IF_STMT_CONSTEVAL_P (t))
10469 if (integer_zerop (tmp))
10470 return RECUR (TREE_OPERAND (t, 2), want_rval);
10471 else if (TREE_CODE (tmp) == INTEGER_CST)
10472 return RECUR (TREE_OPERAND (t, 1), want_rval);
10474 tmp = *jump_target;
10475 for (i = 1; i < 3; ++i)
10477 tree this_jump_target = tmp;
10478 if (potential_constant_expression_1 (TREE_OPERAND (t, i),
10479 want_rval, strict, now, fundef_p,
10480 tf_none, &this_jump_target))
10482 if (returns (&this_jump_target))
10483 *jump_target = this_jump_target;
10484 else if (!returns (jump_target))
10486 if (breaks (&this_jump_target)
10487 || continues (&this_jump_target))
10488 *jump_target = this_jump_target;
10489 if (i == 1)
10491 /* If the then branch is potentially constant, but
10492 does not return, check if the else branch
10493 couldn't return, break or continue. */
10494 hash_set<tree> pset;
10495 check_for_return_continue_data data = { &pset, NULL_TREE,
10496 NULL_TREE };
10497 if (tree ret_expr
10498 = cp_walk_tree (&TREE_OPERAND (t, 2),
10499 check_for_return_continue, &data,
10500 &pset))
10501 *jump_target = ret_expr;
10502 else if (*jump_target == NULL_TREE)
10504 if (data.continue_stmt)
10505 *jump_target = data.continue_stmt;
10506 else if (data.break_stmt)
10507 *jump_target = data.break_stmt;
10511 return true;
10514 if (flags & tf_error)
10516 if (TREE_CODE (t) == IF_STMT)
10517 constexpr_error (loc, fundef_p, "neither branch of %<if%> is a "
10518 "constant expression");
10519 else
10520 constexpr_error (loc, fundef_p, "expression %qE is not a "
10521 "constant expression", t);
10523 return false;
10525 case VEC_INIT_EXPR:
10526 if (VEC_INIT_EXPR_IS_CONSTEXPR (t))
10527 return true;
10528 if (flags & tf_error)
10530 if (constexpr_error (loc, fundef_p, "non-constant array "
10531 "initialization"))
10532 diagnose_non_constexpr_vec_init (t);
10534 return false;
10536 case TYPE_DECL:
10537 case TAG_DEFN:
10538 /* We can see these in statement-expressions. */
10539 return true;
10541 case CLEANUP_STMT:
10542 if (!RECUR (CLEANUP_BODY (t), any))
10543 return false;
10544 if (!CLEANUP_EH_ONLY (t) && !RECUR (CLEANUP_EXPR (t), any))
10545 return false;
10546 return true;
10548 case EMPTY_CLASS_EXPR:
10549 return true;
10551 case GOTO_EXPR:
10553 tree *target = &TREE_OPERAND (t, 0);
10554 /* Gotos representing break, continue and cdtor return are OK. */
10555 if (breaks (target) || continues (target) || returns (target))
10557 *jump_target = *target;
10558 return true;
10560 if (flags & tf_error)
10561 constexpr_error (loc, fundef_p, "%<goto%> is not a constant "
10562 "expression");
10563 return false;
10566 case ASSERTION_STMT:
10567 case PRECONDITION_STMT:
10568 case POSTCONDITION_STMT:
10569 if (!checked_contract_p (get_contract_semantic (t)))
10570 return true;
10571 return RECUR (CONTRACT_CONDITION (t), rval);
10573 case LABEL_EXPR:
10574 t = LABEL_EXPR_LABEL (t);
10575 if (DECL_ARTIFICIAL (t) || cxx_dialect >= cxx23)
10576 return true;
10577 else if (flags & tf_error)
10578 constexpr_error (loc, fundef_p, "label definition in %<constexpr%> "
10579 "function only available with %<-std=c++2b%> or "
10580 "%<-std=gnu++2b%>");
10581 return false;
10583 case ANNOTATE_EXPR:
10584 return RECUR (TREE_OPERAND (t, 0), rval);
10586 case BIT_CAST_EXPR:
10587 return RECUR (TREE_OPERAND (t, 0), rval);
10589 /* Coroutine await, yield and return expressions are not. */
10590 case CO_AWAIT_EXPR:
10591 case CO_YIELD_EXPR:
10592 case CO_RETURN_EXPR:
10593 return false;
10595 case NONTYPE_ARGUMENT_PACK:
10597 tree args = ARGUMENT_PACK_ARGS (t);
10598 int len = TREE_VEC_LENGTH (args);
10599 for (int i = 0; i < len; ++i)
10600 if (!RECUR (TREE_VEC_ELT (args, i), any))
10601 return false;
10602 return true;
10605 default:
10606 if (objc_non_constant_expr_p (t))
10607 return false;
10609 sorry ("unexpected AST of kind %s", get_tree_code_name (TREE_CODE (t)));
10610 gcc_unreachable ();
10611 return false;
10613 #undef RECUR
10616 bool
10617 potential_constant_expression_1 (tree t, bool want_rval, bool strict, bool now,
10618 bool fundef_p, tsubst_flags_t flags)
10620 if (flags & tf_error)
10622 /* Check potentiality quietly first, as that could be performed more
10623 efficiently in some cases (currently only for TRUTH_*_EXPR). If
10624 that fails, replay the check noisily to give errors. */
10625 flags &= ~tf_error;
10626 if (potential_constant_expression_1 (t, want_rval, strict, now, fundef_p,
10627 flags))
10628 return true;
10629 flags |= tf_error;
10632 tree target = NULL_TREE;
10633 return potential_constant_expression_1 (t, want_rval, strict, now, fundef_p,
10634 flags, &target);
10637 /* The main entry point to the above. */
10639 bool
10640 potential_constant_expression (tree t)
10642 return potential_constant_expression_1 (t, /*want_rval*/false, /*strict*/true,
10643 /*now*/false, /*fundef_p*/false,
10644 tf_none);
10647 /* As above, but require a constant rvalue. */
10649 bool
10650 potential_rvalue_constant_expression (tree t)
10652 return potential_constant_expression_1 (t, /*want_rval*/true, /*strict*/true,
10653 /*now*/false, /*fundef_p*/false,
10654 tf_none);
10657 /* Like above, but complain about non-constant expressions. */
10659 bool
10660 require_potential_constant_expression (tree t)
10662 return potential_constant_expression_1 (t, /*want_rval*/false, /*strict*/true,
10663 /*now*/false, /*fundef_p*/false,
10664 tf_warning_or_error);
10667 /* Cross product of the above. */
10669 bool
10670 require_potential_rvalue_constant_expression (tree t)
10672 return potential_constant_expression_1 (t, /*want_rval*/true, /*strict*/true,
10673 /*now*/false, /*fundef_p*/false,
10674 tf_warning_or_error);
10677 /* Like require_potential_rvalue_constant_expression, but fundef_p is true. */
10679 bool
10680 require_potential_rvalue_constant_expression_fncheck (tree t)
10682 return potential_constant_expression_1 (t, /*want_rval*/true, /*strict*/true,
10683 /*now*/false, /*fundef_p*/true,
10684 tf_warning_or_error);
10687 /* Like above, but don't consider PARM_DECL a potential_constant_expression. */
10689 bool
10690 require_rvalue_constant_expression (tree t)
10692 return potential_constant_expression_1 (t, /*want_rval*/true, /*strict*/true,
10693 /*now*/true, /*fundef_p*/false,
10694 tf_warning_or_error);
10697 /* Like potential_constant_expression, but don't consider possible constexpr
10698 substitution of the current function. That is, PARM_DECL qualifies under
10699 potential_constant_expression, but not here.
10701 This is basically what you can check when any actual constant values might
10702 be value-dependent. */
10704 bool
10705 is_constant_expression (tree t)
10707 return potential_constant_expression_1 (t, /*want_rval*/false, /*strict*/true,
10708 /*now*/true, /*fundef_p*/false,
10709 tf_none);
10712 /* As above, but expect an rvalue. */
10714 bool
10715 is_rvalue_constant_expression (tree t)
10717 return potential_constant_expression_1 (t, /*want_rval*/true, /*strict*/true,
10718 /*now*/true, /*fundef_p*/false,
10719 tf_none);
10722 /* Like above, but complain about non-constant expressions. */
10724 bool
10725 require_constant_expression (tree t)
10727 return potential_constant_expression_1 (t, /*want_rval*/false, /*strict*/true,
10728 /*now*/true, /*fundef_p*/false,
10729 tf_warning_or_error);
10732 /* Like is_constant_expression, but allow const variables that are not allowed
10733 under constexpr rules. */
10735 bool
10736 is_static_init_expression (tree t)
10738 return potential_constant_expression_1 (t, /*want_rval*/false,
10739 /*strict*/false, /*now*/true,
10740 /*fundef_p*/false, tf_none);
10743 /* Returns true if T is a potential constant expression that is not
10744 instantiation-dependent, and therefore a candidate for constant folding even
10745 in a template. */
10747 bool
10748 is_nondependent_constant_expression (tree t)
10750 return (!type_unknown_p (t)
10751 && is_constant_expression (t)
10752 && !instantiation_dependent_expression_p (t));
10755 /* Returns true if T is a potential static initializer expression that is not
10756 instantiation-dependent. */
10758 bool
10759 is_nondependent_static_init_expression (tree t)
10761 return (!type_unknown_p (t)
10762 && is_static_init_expression (t)
10763 && !instantiation_dependent_expression_p (t));
10766 /* True iff FN is an implicitly constexpr function. */
10768 bool
10769 decl_implicit_constexpr_p (tree fn)
10771 if (!(flag_implicit_constexpr
10772 && TREE_CODE (fn) == FUNCTION_DECL
10773 && DECL_DECLARED_CONSTEXPR_P (fn)))
10774 return false;
10776 if (DECL_CLONED_FUNCTION_P (fn))
10777 fn = DECL_CLONED_FUNCTION (fn);
10779 return (DECL_LANG_SPECIFIC (fn)
10780 && DECL_LANG_SPECIFIC (fn)->u.fn.implicit_constexpr);
10783 /* Finalize constexpr processing after parsing. */
10785 void
10786 fini_constexpr (void)
10788 /* The contexpr call and fundef copies tables are no longer needed. */
10789 constexpr_call_table = NULL;
10790 fundef_copies_table = NULL;
10793 #include "gt-cp-constexpr.h"