[Ada] Adapt body of formal sets and maps for SPARK
[official-gcc.git] / gcc / cp / constexpr.cc
blob433fa767c0369e011907f8080b6f711eb07e385c
1 /* Perform -*- C++ -*- constant expression evaluation, including calls to
2 constexpr functions. These routines are used both during actual parsing
3 and during the instantiation of template functions.
5 Copyright (C) 1998-2022 Free Software Foundation, Inc.
7 This file is part of GCC.
9 GCC is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3, or (at your option)
12 any later version.
14 GCC is distributed in the hope that it will be useful, but
15 WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3. If not see
21 <http://www.gnu.org/licenses/>. */
23 #include "config.h"
24 #include "system.h"
25 #include "coretypes.h"
26 #include "cp-tree.h"
27 #include "varasm.h"
28 #include "c-family/c-objc.h"
29 #include "tree-iterator.h"
30 #include "gimplify.h"
31 #include "builtins.h"
32 #include "tree-inline.h"
33 #include "ubsan.h"
34 #include "timevar.h"
35 #include "fold-const-call.h"
36 #include "stor-layout.h"
37 #include "cgraph.h"
38 #include "opts.h"
39 #include "stringpool.h"
40 #include "attribs.h"
42 static bool verify_constant (tree, bool, bool *, bool *);
43 #define VERIFY_CONSTANT(X) \
44 do { \
45 if (verify_constant ((X), ctx->quiet, non_constant_p, overflow_p)) \
46 return t; \
47 } while (0)
49 static HOST_WIDE_INT find_array_ctor_elt (tree ary, tree dindex,
50 bool insert = false);
51 static int array_index_cmp (tree key, tree index);
53 /* Returns true iff FUN is an instantiation of a constexpr function
54 template or a defaulted constexpr function. */
56 bool
57 is_instantiation_of_constexpr (tree fun)
59 return ((DECL_TEMPLOID_INSTANTIATION (fun)
60 && DECL_DECLARED_CONSTEXPR_P (DECL_TI_TEMPLATE (fun)))
61 || (DECL_DEFAULTED_FN (fun)
62 && DECL_DECLARED_CONSTEXPR_P (fun)));
65 /* Return true if T is a literal type. */
67 bool
68 literal_type_p (tree t)
70 if (SCALAR_TYPE_P (t)
71 || VECTOR_TYPE_P (t)
72 || TYPE_REF_P (t)
73 || (VOID_TYPE_P (t) && cxx_dialect >= cxx14))
74 return true;
75 if (CLASS_TYPE_P (t))
77 t = complete_type (t);
78 gcc_assert (COMPLETE_TYPE_P (t) || errorcount);
79 return CLASSTYPE_LITERAL_P (t);
81 if (TREE_CODE (t) == ARRAY_TYPE)
82 return literal_type_p (strip_array_types (t));
83 return false;
86 /* If DECL is a variable declared `constexpr', require its type
87 be literal. Return error_mark_node if we give an error, the
88 DECL otherwise. */
90 tree
91 ensure_literal_type_for_constexpr_object (tree decl)
93 tree type = TREE_TYPE (decl);
94 if (VAR_P (decl)
95 && (DECL_DECLARED_CONSTEXPR_P (decl)
96 || var_in_constexpr_fn (decl))
97 && !processing_template_decl)
99 tree stype = strip_array_types (type);
100 if (CLASS_TYPE_P (stype) && !COMPLETE_TYPE_P (complete_type (stype)))
101 /* Don't complain here, we'll complain about incompleteness
102 when we try to initialize the variable. */;
103 else if (!literal_type_p (type))
105 if (DECL_DECLARED_CONSTEXPR_P (decl))
107 auto_diagnostic_group d;
108 error_at (DECL_SOURCE_LOCATION (decl),
109 "the type %qT of %<constexpr%> variable %qD "
110 "is not literal", type, decl);
111 explain_non_literal_class (type);
112 decl = error_mark_node;
114 else if (cxx_dialect < cxx23)
116 if (!is_instantiation_of_constexpr (current_function_decl))
118 auto_diagnostic_group d;
119 error_at (DECL_SOURCE_LOCATION (decl),
120 "variable %qD of non-literal type %qT in "
121 "%<constexpr%> function only available with "
122 "%<-std=c++2b%> or %<-std=gnu++2b%>", decl, type);
123 explain_non_literal_class (type);
124 decl = error_mark_node;
126 cp_function_chain->invalid_constexpr = true;
129 else if (DECL_DECLARED_CONSTEXPR_P (decl)
130 && variably_modified_type_p (type, NULL_TREE))
132 error_at (DECL_SOURCE_LOCATION (decl),
133 "%<constexpr%> variable %qD has variably-modified "
134 "type %qT", decl, type);
135 decl = error_mark_node;
138 return decl;
141 struct constexpr_fundef_hasher : ggc_ptr_hash<constexpr_fundef>
143 static hashval_t hash (const constexpr_fundef *);
144 static bool equal (const constexpr_fundef *, const constexpr_fundef *);
147 /* This table holds all constexpr function definitions seen in
148 the current translation unit. */
150 static GTY (()) hash_table<constexpr_fundef_hasher> *constexpr_fundef_table;
152 /* Utility function used for managing the constexpr function table.
153 Return true if the entries pointed to by P and Q are for the
154 same constexpr function. */
156 inline bool
157 constexpr_fundef_hasher::equal (const constexpr_fundef *lhs,
158 const constexpr_fundef *rhs)
160 return lhs->decl == rhs->decl;
163 /* Utility function used for managing the constexpr function table.
164 Return a hash value for the entry pointed to by Q. */
166 inline hashval_t
167 constexpr_fundef_hasher::hash (const constexpr_fundef *fundef)
169 return DECL_UID (fundef->decl);
172 /* Return a previously saved definition of function FUN. */
174 constexpr_fundef *
175 retrieve_constexpr_fundef (tree fun)
177 if (constexpr_fundef_table == NULL)
178 return NULL;
180 constexpr_fundef fundef = { fun, NULL_TREE, NULL_TREE, NULL_TREE };
181 return constexpr_fundef_table->find (&fundef);
184 /* Check whether the parameter and return types of FUN are valid for a
185 constexpr function, and complain if COMPLAIN. */
187 bool
188 is_valid_constexpr_fn (tree fun, bool complain)
190 bool ret = true;
192 if (DECL_INHERITED_CTOR (fun)
193 && TREE_CODE (fun) == TEMPLATE_DECL)
195 ret = false;
196 if (complain)
197 error ("inherited constructor %qD is not %<constexpr%>",
198 DECL_INHERITED_CTOR (fun));
200 else
202 for (tree parm = FUNCTION_FIRST_USER_PARM (fun);
203 parm != NULL_TREE; parm = TREE_CHAIN (parm))
204 if (!literal_type_p (TREE_TYPE (parm)))
206 ret = false;
207 if (complain)
209 auto_diagnostic_group d;
210 error ("invalid type for parameter %d of %<constexpr%> "
211 "function %q+#D", DECL_PARM_INDEX (parm), fun);
212 explain_non_literal_class (TREE_TYPE (parm));
217 if (LAMBDA_TYPE_P (CP_DECL_CONTEXT (fun)) && cxx_dialect < cxx17)
219 ret = false;
220 if (complain)
221 inform (DECL_SOURCE_LOCATION (fun),
222 "lambdas are implicitly %<constexpr%> only in C++17 and later");
224 else if (DECL_DESTRUCTOR_P (fun))
226 if (cxx_dialect < cxx20)
228 ret = false;
229 if (complain)
230 error_at (DECL_SOURCE_LOCATION (fun),
231 "%<constexpr%> destructors only available"
232 " with %<-std=c++20%> or %<-std=gnu++20%>");
235 else if (!DECL_CONSTRUCTOR_P (fun))
237 tree rettype = TREE_TYPE (TREE_TYPE (fun));
238 if (!literal_type_p (rettype))
240 ret = false;
241 if (complain)
243 auto_diagnostic_group d;
244 error ("invalid return type %qT of %<constexpr%> function %q+D",
245 rettype, fun);
246 explain_non_literal_class (rettype);
250 /* C++14 DR 1684 removed this restriction. */
251 if (cxx_dialect < cxx14
252 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fun)
253 && !CLASSTYPE_LITERAL_P (DECL_CONTEXT (fun)))
255 ret = false;
256 if (complain)
258 auto_diagnostic_group d;
259 if (pedwarn (DECL_SOURCE_LOCATION (fun), OPT_Wpedantic,
260 "enclosing class of %<constexpr%> non-static"
261 " member function %q+#D is not a literal type",
262 fun))
263 explain_non_literal_class (DECL_CONTEXT (fun));
267 else if (CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fun)))
269 ret = false;
270 if (complain)
271 error ("%q#T has virtual base classes", DECL_CONTEXT (fun));
274 return ret;
277 /* Subroutine of build_data_member_initialization. MEMBER is a COMPONENT_REF
278 for a member of an anonymous aggregate, INIT is the initializer for that
279 member, and VEC_OUTER is the vector of constructor elements for the class
280 whose constructor we are processing. Add the initializer to the vector
281 and return true to indicate success. */
283 static bool
284 build_anon_member_initialization (tree member, tree init,
285 vec<constructor_elt, va_gc> **vec_outer)
287 /* MEMBER presents the relevant fields from the inside out, but we need
288 to build up the initializer from the outside in so that we can reuse
289 previously built CONSTRUCTORs if this is, say, the second field in an
290 anonymous struct. So we use a vec as a stack. */
291 auto_vec<tree, 2> fields;
294 fields.safe_push (TREE_OPERAND (member, 1));
295 member = TREE_OPERAND (member, 0);
297 while (ANON_AGGR_TYPE_P (TREE_TYPE (member))
298 && TREE_CODE (member) == COMPONENT_REF);
300 /* VEC has the constructor elements vector for the context of FIELD.
301 If FIELD is an anonymous aggregate, we will push inside it. */
302 vec<constructor_elt, va_gc> **vec = vec_outer;
303 tree field;
304 while (field = fields.pop(),
305 ANON_AGGR_TYPE_P (TREE_TYPE (field)))
307 tree ctor;
308 /* If there is already an outer constructor entry for the anonymous
309 aggregate FIELD, use it; otherwise, insert one. */
310 if (vec_safe_is_empty (*vec)
311 || (*vec)->last().index != field)
313 ctor = build_constructor (TREE_TYPE (field), NULL);
314 CONSTRUCTOR_APPEND_ELT (*vec, field, ctor);
316 else
317 ctor = (*vec)->last().value;
318 vec = &CONSTRUCTOR_ELTS (ctor);
321 /* Now we're at the innermost field, the one that isn't an anonymous
322 aggregate. Add its initializer to the CONSTRUCTOR and we're done. */
323 gcc_assert (fields.is_empty());
324 CONSTRUCTOR_APPEND_ELT (*vec, field, init);
326 return true;
329 /* Subroutine of build_constexpr_constructor_member_initializers.
330 The expression tree T represents a data member initialization
331 in a (constexpr) constructor definition. Build a pairing of
332 the data member with its initializer, and prepend that pair
333 to the existing initialization pair INITS. */
335 static bool
336 build_data_member_initialization (tree t, vec<constructor_elt, va_gc> **vec)
338 tree member, init;
339 if (TREE_CODE (t) == CLEANUP_POINT_EXPR)
340 t = TREE_OPERAND (t, 0);
341 if (TREE_CODE (t) == EXPR_STMT)
342 t = TREE_OPERAND (t, 0);
343 if (t == error_mark_node)
344 return false;
345 if (TREE_CODE (t) == STATEMENT_LIST)
347 for (tree stmt : tsi_range (t))
348 if (! build_data_member_initialization (stmt, vec))
349 return false;
350 return true;
352 if (TREE_CODE (t) == CLEANUP_STMT)
354 /* We can't see a CLEANUP_STMT in a constructor for a literal class,
355 but we can in a constexpr constructor for a non-literal class. Just
356 ignore it; either all the initialization will be constant, in which
357 case the cleanup can't run, or it can't be constexpr.
358 Still recurse into CLEANUP_BODY. */
359 return build_data_member_initialization (CLEANUP_BODY (t), vec);
361 if (TREE_CODE (t) == CONVERT_EXPR)
362 t = TREE_OPERAND (t, 0);
363 if (TREE_CODE (t) == INIT_EXPR
364 /* vptr initialization shows up as a MODIFY_EXPR. In C++14 we only
365 use what this function builds for cx_check_missing_mem_inits, and
366 assignment in the ctor body doesn't count. */
367 || (cxx_dialect < cxx14 && TREE_CODE (t) == MODIFY_EXPR))
369 member = TREE_OPERAND (t, 0);
370 init = break_out_target_exprs (TREE_OPERAND (t, 1));
372 else if (TREE_CODE (t) == CALL_EXPR)
374 tree fn = get_callee_fndecl (t);
375 if (!fn || !DECL_CONSTRUCTOR_P (fn))
376 /* We're only interested in calls to subobject constructors. */
377 return true;
378 member = CALL_EXPR_ARG (t, 0);
379 /* We don't use build_cplus_new here because it complains about
380 abstract bases. Leaving the call unwrapped means that it has the
381 wrong type, but cxx_eval_constant_expression doesn't care. */
382 init = break_out_target_exprs (t);
384 else if (TREE_CODE (t) == BIND_EXPR)
385 return build_data_member_initialization (BIND_EXPR_BODY (t), vec);
386 else
387 /* Don't add anything else to the CONSTRUCTOR. */
388 return true;
389 if (INDIRECT_REF_P (member))
390 member = TREE_OPERAND (member, 0);
391 if (TREE_CODE (member) == NOP_EXPR)
393 tree op = member;
394 STRIP_NOPS (op);
395 if (TREE_CODE (op) == ADDR_EXPR)
397 gcc_assert (same_type_ignoring_top_level_qualifiers_p
398 (TREE_TYPE (TREE_TYPE (op)),
399 TREE_TYPE (TREE_TYPE (member))));
400 /* Initializing a cv-qualified member; we need to look through
401 the const_cast. */
402 member = op;
404 else if (op == current_class_ptr
405 && (same_type_ignoring_top_level_qualifiers_p
406 (TREE_TYPE (TREE_TYPE (member)),
407 current_class_type)))
408 /* Delegating constructor. */
409 member = op;
410 else
412 /* This is an initializer for an empty base; keep it for now so
413 we can check it in cxx_eval_bare_aggregate. */
414 gcc_assert (is_empty_class (TREE_TYPE (TREE_TYPE (member))));
417 if (TREE_CODE (member) == ADDR_EXPR)
418 member = TREE_OPERAND (member, 0);
419 if (TREE_CODE (member) == COMPONENT_REF)
421 tree aggr = TREE_OPERAND (member, 0);
422 if (TREE_CODE (aggr) == VAR_DECL)
423 /* Initializing a local variable, don't add anything. */
424 return true;
425 if (TREE_CODE (aggr) != COMPONENT_REF)
426 /* Normal member initialization. */
427 member = TREE_OPERAND (member, 1);
428 else if (ANON_AGGR_TYPE_P (TREE_TYPE (aggr)))
429 /* Initializing a member of an anonymous union. */
430 return build_anon_member_initialization (member, init, vec);
431 else
432 /* We're initializing a vtable pointer in a base. Leave it as
433 COMPONENT_REF so we remember the path to get to the vfield. */
434 gcc_assert (TREE_TYPE (member) == vtbl_ptr_type_node);
437 /* Value-initialization can produce multiple initializers for the
438 same field; use the last one. */
439 if (!vec_safe_is_empty (*vec) && (*vec)->last().index == member)
440 (*vec)->last().value = init;
441 else
442 CONSTRUCTOR_APPEND_ELT (*vec, member, init);
443 return true;
446 /* Subroutine of check_constexpr_ctor_body_1 and constexpr_fn_retval.
447 In C++11 mode checks that the TYPE_DECLs in the BIND_EXPR_VARS of a
448 BIND_EXPR conform to 7.1.5/3/4 on typedef and alias declarations. */
450 static bool
451 check_constexpr_bind_expr_vars (tree t)
453 gcc_assert (TREE_CODE (t) == BIND_EXPR);
455 for (tree var = BIND_EXPR_VARS (t); var; var = DECL_CHAIN (var))
456 if (TREE_CODE (var) == TYPE_DECL
457 && DECL_IMPLICIT_TYPEDEF_P (var)
458 && !LAMBDA_TYPE_P (TREE_TYPE (var)))
459 return false;
460 return true;
463 /* Subroutine of check_constexpr_ctor_body. */
465 static bool
466 check_constexpr_ctor_body_1 (tree last, tree list)
468 switch (TREE_CODE (list))
470 case DECL_EXPR:
471 if (TREE_CODE (DECL_EXPR_DECL (list)) == USING_DECL
472 || TREE_CODE (DECL_EXPR_DECL (list)) == TYPE_DECL)
473 return true;
474 return false;
476 case CLEANUP_POINT_EXPR:
477 return check_constexpr_ctor_body (last, TREE_OPERAND (list, 0),
478 /*complain=*/false);
480 case BIND_EXPR:
481 if (!check_constexpr_bind_expr_vars (list)
482 || !check_constexpr_ctor_body (last, BIND_EXPR_BODY (list),
483 /*complain=*/false))
484 return false;
485 return true;
487 case USING_STMT:
488 case STATIC_ASSERT:
489 case DEBUG_BEGIN_STMT:
490 return true;
492 default:
493 return false;
497 /* Make sure that there are no statements after LAST in the constructor
498 body represented by LIST. */
500 bool
501 check_constexpr_ctor_body (tree last, tree list, bool complain)
503 /* C++14 doesn't require a constexpr ctor to have an empty body. */
504 if (cxx_dialect >= cxx14)
505 return true;
507 bool ok = true;
508 if (TREE_CODE (list) == STATEMENT_LIST)
510 tree_stmt_iterator i = tsi_last (list);
511 for (; !tsi_end_p (i); tsi_prev (&i))
513 tree t = tsi_stmt (i);
514 if (t == last)
515 break;
516 if (!check_constexpr_ctor_body_1 (last, t))
518 ok = false;
519 break;
523 else if (list != last
524 && !check_constexpr_ctor_body_1 (last, list))
525 ok = false;
526 if (!ok)
528 if (complain)
529 error ("%<constexpr%> constructor does not have empty body");
530 DECL_DECLARED_CONSTEXPR_P (current_function_decl) = false;
532 return ok;
535 /* V is a vector of constructor elements built up for the base and member
536 initializers of a constructor for TYPE. They need to be in increasing
537 offset order, which they might not be yet if TYPE has a primary base
538 which is not first in the base-clause or a vptr and at least one base
539 all of which are non-primary. */
541 static vec<constructor_elt, va_gc> *
542 sort_constexpr_mem_initializers (tree type, vec<constructor_elt, va_gc> *v)
544 tree pri = CLASSTYPE_PRIMARY_BINFO (type);
545 tree field_type;
546 unsigned i;
547 constructor_elt *ce;
549 if (pri)
550 field_type = BINFO_TYPE (pri);
551 else if (TYPE_CONTAINS_VPTR_P (type))
552 field_type = vtbl_ptr_type_node;
553 else
554 return v;
556 /* Find the element for the primary base or vptr and move it to the
557 beginning of the vec. */
558 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
559 if (TREE_TYPE (ce->index) == field_type)
560 break;
562 if (i > 0 && i < vec_safe_length (v))
564 vec<constructor_elt, va_gc> &vref = *v;
565 constructor_elt elt = vref[i];
566 for (; i > 0; --i)
567 vref[i] = vref[i-1];
568 vref[0] = elt;
571 return v;
574 /* Build compile-time evalable representations of member-initializer list
575 for a constexpr constructor. */
577 static tree
578 build_constexpr_constructor_member_initializers (tree type, tree body)
580 vec<constructor_elt, va_gc> *vec = NULL;
581 bool ok = true;
582 while (true)
583 switch (TREE_CODE (body))
585 case MUST_NOT_THROW_EXPR:
586 case EH_SPEC_BLOCK:
587 body = TREE_OPERAND (body, 0);
588 break;
590 case STATEMENT_LIST:
591 for (tree stmt : tsi_range (body))
593 body = stmt;
594 if (TREE_CODE (body) == BIND_EXPR)
595 break;
597 break;
599 case BIND_EXPR:
600 body = BIND_EXPR_BODY (body);
601 goto found;
603 default:
604 gcc_unreachable ();
606 found:
607 if (TREE_CODE (body) == TRY_BLOCK)
609 body = TREE_OPERAND (body, 0);
610 if (TREE_CODE (body) == BIND_EXPR)
611 body = BIND_EXPR_BODY (body);
613 if (TREE_CODE (body) == CLEANUP_POINT_EXPR)
615 body = TREE_OPERAND (body, 0);
616 if (TREE_CODE (body) == EXPR_STMT)
617 body = TREE_OPERAND (body, 0);
618 if (TREE_CODE (body) == INIT_EXPR
619 && (same_type_ignoring_top_level_qualifiers_p
620 (TREE_TYPE (TREE_OPERAND (body, 0)),
621 current_class_type)))
623 /* Trivial copy. */
624 return TREE_OPERAND (body, 1);
626 ok = build_data_member_initialization (body, &vec);
628 else if (TREE_CODE (body) == STATEMENT_LIST)
630 for (tree stmt : tsi_range (body))
632 ok = build_data_member_initialization (stmt, &vec);
633 if (!ok)
634 break;
637 else if (EXPR_P (body))
638 ok = build_data_member_initialization (body, &vec);
639 else
640 gcc_assert (errorcount > 0);
641 if (ok)
643 if (vec_safe_length (vec) > 0)
645 /* In a delegating constructor, return the target. */
646 constructor_elt *ce = &(*vec)[0];
647 if (ce->index == current_class_ptr)
649 body = ce->value;
650 vec_free (vec);
651 return body;
654 vec = sort_constexpr_mem_initializers (type, vec);
655 return build_constructor (type, vec);
657 else
658 return error_mark_node;
661 /* We have an expression tree T that represents a call, either CALL_EXPR
662 or AGGR_INIT_EXPR. If the call is lexically to a named function,
663 retrun the _DECL for that function. */
665 static tree
666 get_function_named_in_call (tree t)
668 tree fun = cp_get_callee (t);
669 if (fun && TREE_CODE (fun) == ADDR_EXPR
670 && TREE_CODE (TREE_OPERAND (fun, 0)) == FUNCTION_DECL)
671 fun = TREE_OPERAND (fun, 0);
672 return fun;
675 /* Subroutine of check_constexpr_fundef. BODY is the body of a function
676 declared to be constexpr, or a sub-statement thereof. Returns the
677 return value if suitable, error_mark_node for a statement not allowed in
678 a constexpr function, or NULL_TREE if no return value was found. */
680 tree
681 constexpr_fn_retval (tree body)
683 switch (TREE_CODE (body))
685 case STATEMENT_LIST:
687 tree expr = NULL_TREE;
688 for (tree stmt : tsi_range (body))
690 tree s = constexpr_fn_retval (stmt);
691 if (s == error_mark_node)
692 return error_mark_node;
693 else if (s == NULL_TREE)
694 /* Keep iterating. */;
695 else if (expr)
696 /* Multiple return statements. */
697 return error_mark_node;
698 else
699 expr = s;
701 return expr;
704 case RETURN_EXPR:
705 return break_out_target_exprs (TREE_OPERAND (body, 0));
707 case DECL_EXPR:
709 tree decl = DECL_EXPR_DECL (body);
710 if (TREE_CODE (decl) == USING_DECL
711 /* Accept __func__, __FUNCTION__, and __PRETTY_FUNCTION__. */
712 || DECL_ARTIFICIAL (decl))
713 return NULL_TREE;
714 return error_mark_node;
717 case CLEANUP_POINT_EXPR:
718 return constexpr_fn_retval (TREE_OPERAND (body, 0));
720 case BIND_EXPR:
721 if (!check_constexpr_bind_expr_vars (body))
722 return error_mark_node;
723 return constexpr_fn_retval (BIND_EXPR_BODY (body));
725 case USING_STMT:
726 case DEBUG_BEGIN_STMT:
727 return NULL_TREE;
729 case CALL_EXPR:
731 tree fun = get_function_named_in_call (body);
732 if (fun != NULL_TREE
733 && fndecl_built_in_p (fun, BUILT_IN_UNREACHABLE))
734 return NULL_TREE;
736 /* Fallthru. */
738 default:
739 return error_mark_node;
743 /* Subroutine of check_constexpr_fundef. BODY is the DECL_SAVED_TREE of
744 FUN; do the necessary transformations to turn it into a single expression
745 that we can store in the hash table. */
747 static tree
748 massage_constexpr_body (tree fun, tree body)
750 if (DECL_CONSTRUCTOR_P (fun))
751 body = build_constexpr_constructor_member_initializers
752 (DECL_CONTEXT (fun), body);
753 else if (cxx_dialect < cxx14)
755 if (TREE_CODE (body) == EH_SPEC_BLOCK)
756 body = EH_SPEC_STMTS (body);
757 if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
758 body = TREE_OPERAND (body, 0);
759 body = constexpr_fn_retval (body);
761 return body;
764 /* CTYPE is a type constructed from BODY. Return true if some
765 bases/fields are uninitialized, and complain if COMPLAIN. */
767 static bool
768 cx_check_missing_mem_inits (tree ctype, tree body, bool complain)
770 /* We allow uninitialized bases/fields in C++20. */
771 if (cxx_dialect >= cxx20)
772 return false;
774 unsigned nelts = 0;
776 if (body)
778 if (TREE_CODE (body) != CONSTRUCTOR)
779 return false;
780 nelts = CONSTRUCTOR_NELTS (body);
782 tree field = TYPE_FIELDS (ctype);
784 if (TREE_CODE (ctype) == UNION_TYPE)
786 if (nelts == 0 && next_aggregate_field (field))
788 if (complain)
789 error ("%<constexpr%> constructor for union %qT must "
790 "initialize exactly one non-static data member", ctype);
791 return true;
793 return false;
796 /* Iterate over the CONSTRUCTOR, checking any missing fields don't
797 need an explicit initialization. */
798 bool bad = false;
799 for (unsigned i = 0; i <= nelts; ++i)
801 tree index = NULL_TREE;
802 if (i < nelts)
804 index = CONSTRUCTOR_ELT (body, i)->index;
805 /* Skip base and vtable inits. */
806 if (TREE_CODE (index) != FIELD_DECL
807 || DECL_ARTIFICIAL (index))
808 continue;
811 for (; field != index; field = DECL_CHAIN (field))
813 tree ftype;
814 if (TREE_CODE (field) != FIELD_DECL)
815 continue;
816 if (DECL_UNNAMED_BIT_FIELD (field))
817 continue;
818 if (DECL_ARTIFICIAL (field))
819 continue;
820 if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
822 /* Recurse to check the anonymous aggregate member. */
823 bad |= cx_check_missing_mem_inits
824 (TREE_TYPE (field), NULL_TREE, complain);
825 if (bad && !complain)
826 return true;
827 continue;
829 ftype = TREE_TYPE (field);
830 if (!ftype || !TYPE_P (ftype) || !COMPLETE_TYPE_P (ftype))
831 /* A flexible array can't be intialized here, so don't complain
832 that it isn't. */
833 continue;
834 if (is_empty_field (field))
835 /* An empty field doesn't need an initializer. */
836 continue;
837 ftype = strip_array_types (ftype);
838 if (type_has_constexpr_default_constructor (ftype))
840 /* It's OK to skip a member with a trivial constexpr ctor.
841 A constexpr ctor that isn't trivial should have been
842 added in by now. */
843 gcc_checking_assert (!TYPE_HAS_COMPLEX_DFLT (ftype)
844 || errorcount != 0);
845 continue;
847 if (!complain)
848 return true;
849 auto_diagnostic_group d;
850 error ("member %qD must be initialized by mem-initializer "
851 "in %<constexpr%> constructor", field);
852 inform (DECL_SOURCE_LOCATION (field), "declared here");
853 bad = true;
855 if (field == NULL_TREE)
856 break;
858 if (ANON_AGGR_TYPE_P (TREE_TYPE (index)))
860 /* Check the anonymous aggregate initializer is valid. */
861 bad |= cx_check_missing_mem_inits
862 (TREE_TYPE (index), CONSTRUCTOR_ELT (body, i)->value, complain);
863 if (bad && !complain)
864 return true;
866 field = DECL_CHAIN (field);
869 return bad;
872 /* We are processing the definition of the constexpr function FUN.
873 Check that its body fulfills the apropriate requirements and
874 enter it in the constexpr function definition table. */
876 void
877 maybe_save_constexpr_fundef (tree fun)
879 if (processing_template_decl
880 || cp_function_chain->invalid_constexpr
881 || (DECL_CLONED_FUNCTION_P (fun) && !DECL_DELETING_DESTRUCTOR_P (fun)))
882 return;
884 /* With -fimplicit-constexpr, try to make inlines constexpr. We'll
885 actually set DECL_DECLARED_CONSTEXPR_P below if the checks pass. */
886 bool implicit = false;
887 if (flag_implicit_constexpr)
889 if (DECL_DELETING_DESTRUCTOR_P (fun)
890 && decl_implicit_constexpr_p (DECL_CLONED_FUNCTION (fun)))
891 /* Don't inherit implicit constexpr from the non-deleting
892 destructor. */
893 DECL_DECLARED_CONSTEXPR_P (fun) = false;
895 if (!DECL_DECLARED_CONSTEXPR_P (fun)
896 && DECL_DECLARED_INLINE_P (fun)
897 && !lookup_attribute ("noinline", DECL_ATTRIBUTES (fun)))
898 implicit = true;
901 if (!DECL_DECLARED_CONSTEXPR_P (fun) && !implicit)
902 return;
904 bool complain = !DECL_GENERATED_P (fun) && !implicit;
906 if (!is_valid_constexpr_fn (fun, complain))
907 return;
909 tree massaged = massage_constexpr_body (fun, DECL_SAVED_TREE (fun));
910 if (massaged == NULL_TREE || massaged == error_mark_node)
912 if (!DECL_CONSTRUCTOR_P (fun) && complain)
913 error ("body of %<constexpr%> function %qD not a return-statement",
914 fun);
915 return;
918 bool potential = potential_rvalue_constant_expression (massaged);
919 if (!potential && complain)
920 require_potential_rvalue_constant_expression (massaged);
922 if (DECL_CONSTRUCTOR_P (fun) && potential
923 && !DECL_DEFAULTED_FN (fun))
925 if (cx_check_missing_mem_inits (DECL_CONTEXT (fun),
926 massaged, complain))
927 potential = false;
928 else if (cxx_dialect > cxx11)
930 /* What we got from massage_constexpr_body is pretty much just the
931 ctor-initializer, also check the body. */
932 massaged = DECL_SAVED_TREE (fun);
933 potential = potential_rvalue_constant_expression (massaged);
934 if (!potential && complain)
935 require_potential_rvalue_constant_expression (massaged);
939 if (!potential && complain)
940 return;
942 if (implicit)
944 if (potential)
946 DECL_DECLARED_CONSTEXPR_P (fun) = true;
947 DECL_LANG_SPECIFIC (fun)->u.fn.implicit_constexpr = true;
948 if (DECL_CONSTRUCTOR_P (fun))
949 TYPE_HAS_CONSTEXPR_CTOR (DECL_CONTEXT (fun)) = true;
951 else
952 /* Don't bother keeping the pre-generic body of unsuitable functions
953 not explicitly declared constexpr. */
954 return;
957 constexpr_fundef entry = {fun, NULL_TREE, NULL_TREE, NULL_TREE};
958 bool clear_ctx = false;
959 if (DECL_RESULT (fun) && DECL_CONTEXT (DECL_RESULT (fun)) == NULL_TREE)
961 clear_ctx = true;
962 DECL_CONTEXT (DECL_RESULT (fun)) = fun;
964 tree saved_fn = current_function_decl;
965 current_function_decl = fun;
966 entry.body = copy_fn (entry.decl, entry.parms, entry.result);
967 current_function_decl = saved_fn;
968 if (clear_ctx)
969 DECL_CONTEXT (DECL_RESULT (entry.decl)) = NULL_TREE;
970 if (!potential)
971 /* For a template instantiation, we want to remember the pre-generic body
972 for explain_invalid_constexpr_fn, but do tell cxx_eval_call_expression
973 that it doesn't need to bother trying to expand the function. */
974 entry.result = error_mark_node;
976 register_constexpr_fundef (entry);
979 /* BODY is a validated and massaged definition of a constexpr
980 function. Register it in the hash table. */
982 void
983 register_constexpr_fundef (const constexpr_fundef &value)
985 /* Create the constexpr function table if necessary. */
986 if (constexpr_fundef_table == NULL)
987 constexpr_fundef_table
988 = hash_table<constexpr_fundef_hasher>::create_ggc (101);
990 constexpr_fundef **slot = constexpr_fundef_table->find_slot
991 (const_cast<constexpr_fundef *> (&value), INSERT);
993 gcc_assert (*slot == NULL);
994 *slot = ggc_alloc<constexpr_fundef> ();
995 **slot = value;
998 /* FUN is a non-constexpr function called in a context that requires a
999 constant expression. If it comes from a constexpr template, explain why
1000 the instantiation isn't constexpr. */
1002 void
1003 explain_invalid_constexpr_fn (tree fun)
1005 static hash_set<tree> *diagnosed;
1006 tree body;
1007 /* Only diagnose defaulted functions, lambdas, or instantiations. */
1008 if (!DECL_DEFAULTED_FN (fun)
1009 && !LAMBDA_TYPE_P (CP_DECL_CONTEXT (fun))
1010 && !is_instantiation_of_constexpr (fun))
1012 inform (DECL_SOURCE_LOCATION (fun), "%qD declared here", fun);
1013 return;
1015 if (diagnosed == NULL)
1016 diagnosed = new hash_set<tree>;
1017 if (diagnosed->add (fun))
1018 /* Already explained. */
1019 return;
1021 iloc_sentinel ils = input_location;
1022 if (!lambda_static_thunk_p (fun))
1024 /* Diagnostics should completely ignore the static thunk, so leave
1025 input_location set to our caller's location. */
1026 input_location = DECL_SOURCE_LOCATION (fun);
1027 inform (input_location,
1028 "%qD is not usable as a %<constexpr%> function because:", fun);
1030 /* First check the declaration. */
1031 if (is_valid_constexpr_fn (fun, true))
1033 /* Then if it's OK, the body. */
1034 if (!DECL_DECLARED_CONSTEXPR_P (fun)
1035 && DECL_DEFAULTED_FN (fun))
1036 explain_implicit_non_constexpr (fun);
1037 else
1039 if (constexpr_fundef *fd = retrieve_constexpr_fundef (fun))
1040 body = fd->body;
1041 else
1042 body = DECL_SAVED_TREE (fun);
1043 body = massage_constexpr_body (fun, body);
1044 require_potential_rvalue_constant_expression (body);
1045 if (DECL_CONSTRUCTOR_P (fun))
1046 cx_check_missing_mem_inits (DECL_CONTEXT (fun), body, true);
1051 /* Objects of this type represent calls to constexpr functions
1052 along with the bindings of parameters to their arguments, for
1053 the purpose of compile time evaluation. */
1055 struct GTY((for_user)) constexpr_call {
1056 /* Description of the constexpr function definition. */
1057 constexpr_fundef *fundef;
1058 /* Parameter bindings environment. A TREE_VEC of arguments. */
1059 tree bindings;
1060 /* Result of the call.
1061 NULL means the call is being evaluated.
1062 error_mark_node means that the evaluation was erroneous;
1063 otherwise, the actuall value of the call. */
1064 tree result;
1065 /* The hash of this call; we remember it here to avoid having to
1066 recalculate it when expanding the hash table. */
1067 hashval_t hash;
1068 /* Whether __builtin_is_constant_evaluated() should evaluate to true. */
1069 bool manifestly_const_eval;
1072 struct constexpr_call_hasher : ggc_ptr_hash<constexpr_call>
1074 static hashval_t hash (constexpr_call *);
1075 static bool equal (constexpr_call *, constexpr_call *);
1078 enum constexpr_switch_state {
1079 /* Used when processing a switch for the first time by cxx_eval_switch_expr
1080 and default: label for that switch has not been seen yet. */
1081 css_default_not_seen,
1082 /* Used when processing a switch for the first time by cxx_eval_switch_expr
1083 and default: label for that switch has been seen already. */
1084 css_default_seen,
1085 /* Used when processing a switch for the second time by
1086 cxx_eval_switch_expr, where default: label should match. */
1087 css_default_processing
1090 /* The constexpr expansion context part which needs one instance per
1091 cxx_eval_outermost_constant_expr invocation. VALUES is a map of values of
1092 variables initialized within the expression. */
1094 struct constexpr_global_ctx {
1095 /* Values for any temporaries or local variables within the
1096 constant-expression. */
1097 hash_map<tree,tree> values;
1098 /* Number of cxx_eval_constant_expression calls (except skipped ones,
1099 on simple constants or location wrappers) encountered during current
1100 cxx_eval_outermost_constant_expr call. */
1101 HOST_WIDE_INT constexpr_ops_count;
1102 /* Heap VAR_DECLs created during the evaluation of the outermost constant
1103 expression. */
1104 auto_vec<tree, 16> heap_vars;
1105 /* Cleanups that need to be evaluated at the end of CLEANUP_POINT_EXPR. */
1106 vec<tree> *cleanups;
1107 /* Number of heap VAR_DECL deallocations. */
1108 unsigned heap_dealloc_count;
1109 /* Constructor. */
1110 constexpr_global_ctx ()
1111 : constexpr_ops_count (0), cleanups (NULL), heap_dealloc_count (0) {}
1114 /* The constexpr expansion context. CALL is the current function
1115 expansion, CTOR is the current aggregate initializer, OBJECT is the
1116 object being initialized by CTOR, either a VAR_DECL or a _REF. */
1118 struct constexpr_ctx {
1119 /* The part of the context that needs to be unique to the whole
1120 cxx_eval_outermost_constant_expr invocation. */
1121 constexpr_global_ctx *global;
1122 /* The innermost call we're evaluating. */
1123 constexpr_call *call;
1124 /* SAVE_EXPRs and TARGET_EXPR_SLOT vars of TARGET_EXPRs that we've seen
1125 within the current LOOP_EXPR. NULL if we aren't inside a loop. */
1126 vec<tree> *save_exprs;
1127 /* The CONSTRUCTOR we're currently building up for an aggregate
1128 initializer. */
1129 tree ctor;
1130 /* The object we're building the CONSTRUCTOR for. */
1131 tree object;
1132 /* If inside SWITCH_EXPR. */
1133 constexpr_switch_state *css_state;
1134 /* The aggregate initialization context inside which this one is nested. This
1135 is used by lookup_placeholder to resolve PLACEHOLDER_EXPRs. */
1136 const constexpr_ctx *parent;
1138 /* Whether we should error on a non-constant expression or fail quietly.
1139 This flag needs to be here, but some of the others could move to global
1140 if they get larger than a word. */
1141 bool quiet;
1142 /* Whether we are strictly conforming to constant expression rules or
1143 trying harder to get a constant value. */
1144 bool strict;
1145 /* Whether __builtin_is_constant_evaluated () should be true. */
1146 bool manifestly_const_eval;
1149 /* This internal flag controls whether we should avoid doing anything during
1150 constexpr evaluation that would cause extra DECL_UID generation, such as
1151 template instantiation and function body copying. */
1153 static bool uid_sensitive_constexpr_evaluation_value;
1155 /* An internal counter that keeps track of the number of times
1156 uid_sensitive_constexpr_evaluation_p returned true. */
1158 static unsigned uid_sensitive_constexpr_evaluation_true_counter;
1160 /* The accessor for uid_sensitive_constexpr_evaluation_value which also
1161 increments the corresponding counter. */
1163 static bool
1164 uid_sensitive_constexpr_evaluation_p ()
1166 if (uid_sensitive_constexpr_evaluation_value)
1168 ++uid_sensitive_constexpr_evaluation_true_counter;
1169 return true;
1171 else
1172 return false;
1175 /* The default constructor for uid_sensitive_constexpr_evaluation_sentinel
1176 enables the internal flag for uid_sensitive_constexpr_evaluation_p
1177 during the lifetime of the sentinel object. Upon its destruction, the
1178 previous value of uid_sensitive_constexpr_evaluation_p is restored. */
1180 uid_sensitive_constexpr_evaluation_sentinel
1181 ::uid_sensitive_constexpr_evaluation_sentinel ()
1182 : ovr (uid_sensitive_constexpr_evaluation_value, true)
1186 /* The default constructor for uid_sensitive_constexpr_evaluation_checker
1187 records the current number of times that uid_sensitive_constexpr_evaluation_p
1188 has been called and returned true. */
1190 uid_sensitive_constexpr_evaluation_checker
1191 ::uid_sensitive_constexpr_evaluation_checker ()
1192 : saved_counter (uid_sensitive_constexpr_evaluation_true_counter)
1196 /* Returns true iff uid_sensitive_constexpr_evaluation_p is true, and
1197 some constexpr evaluation was restricted due to u_s_c_e_p being called
1198 and returning true during the lifetime of this checker object. */
1200 bool
1201 uid_sensitive_constexpr_evaluation_checker::evaluation_restricted_p () const
1203 return (uid_sensitive_constexpr_evaluation_value
1204 && saved_counter != uid_sensitive_constexpr_evaluation_true_counter);
1208 /* A table of all constexpr calls that have been evaluated by the
1209 compiler in this translation unit. */
1211 static GTY (()) hash_table<constexpr_call_hasher> *constexpr_call_table;
1213 static tree cxx_eval_constant_expression (const constexpr_ctx *, tree,
1214 bool, bool *, bool *, tree * = NULL);
1216 /* Compute a hash value for a constexpr call representation. */
1218 inline hashval_t
1219 constexpr_call_hasher::hash (constexpr_call *info)
1221 return info->hash;
1224 /* Return true if the objects pointed to by P and Q represent calls
1225 to the same constexpr function with the same arguments.
1226 Otherwise, return false. */
1228 bool
1229 constexpr_call_hasher::equal (constexpr_call *lhs, constexpr_call *rhs)
1231 if (lhs == rhs)
1232 return true;
1233 if (lhs->hash != rhs->hash)
1234 return false;
1235 if (lhs->manifestly_const_eval != rhs->manifestly_const_eval)
1236 return false;
1237 if (!constexpr_fundef_hasher::equal (lhs->fundef, rhs->fundef))
1238 return false;
1239 return cp_tree_equal (lhs->bindings, rhs->bindings);
1242 /* Initialize the constexpr call table, if needed. */
1244 static void
1245 maybe_initialize_constexpr_call_table (void)
1247 if (constexpr_call_table == NULL)
1248 constexpr_call_table = hash_table<constexpr_call_hasher>::create_ggc (101);
1251 /* During constexpr CALL_EXPR evaluation, to avoid issues with sharing when
1252 a function happens to get called recursively, we unshare the callee
1253 function's body and evaluate this unshared copy instead of evaluating the
1254 original body.
1256 FUNDEF_COPIES_TABLE is a per-function freelist of these unshared function
1257 copies. The underlying data structure of FUNDEF_COPIES_TABLE is a hash_map
1258 that's keyed off of the original FUNCTION_DECL and whose value is a
1259 TREE_LIST of this function's unused copies awaiting reuse.
1261 This is not GC-deletable to avoid GC affecting UID generation. */
1263 static GTY(()) decl_tree_map *fundef_copies_table;
1265 /* Reuse a copy or create a new unshared copy of the function FUN.
1266 Return this copy. We use a TREE_LIST whose PURPOSE is body, VALUE
1267 is parms, TYPE is result. */
1269 static tree
1270 get_fundef_copy (constexpr_fundef *fundef)
1272 tree copy;
1273 bool existed;
1274 tree *slot = &(hash_map_safe_get_or_insert<hm_ggc>
1275 (fundef_copies_table, fundef->decl, &existed, 127));
1277 if (!existed)
1279 /* There is no cached function available, or in use. We can use
1280 the function directly. That the slot is now created records
1281 that this function is now in use. */
1282 copy = build_tree_list (fundef->body, fundef->parms);
1283 TREE_TYPE (copy) = fundef->result;
1285 else if (*slot == NULL_TREE)
1287 if (uid_sensitive_constexpr_evaluation_p ())
1288 return NULL_TREE;
1290 /* We've already used the function itself, so make a copy. */
1291 copy = build_tree_list (NULL, NULL);
1292 tree saved_body = DECL_SAVED_TREE (fundef->decl);
1293 tree saved_parms = DECL_ARGUMENTS (fundef->decl);
1294 tree saved_result = DECL_RESULT (fundef->decl);
1295 tree saved_fn = current_function_decl;
1296 DECL_SAVED_TREE (fundef->decl) = fundef->body;
1297 DECL_ARGUMENTS (fundef->decl) = fundef->parms;
1298 DECL_RESULT (fundef->decl) = fundef->result;
1299 current_function_decl = fundef->decl;
1300 TREE_PURPOSE (copy) = copy_fn (fundef->decl, TREE_VALUE (copy),
1301 TREE_TYPE (copy));
1302 current_function_decl = saved_fn;
1303 DECL_RESULT (fundef->decl) = saved_result;
1304 DECL_ARGUMENTS (fundef->decl) = saved_parms;
1305 DECL_SAVED_TREE (fundef->decl) = saved_body;
1307 else
1309 /* We have a cached function available. */
1310 copy = *slot;
1311 *slot = TREE_CHAIN (copy);
1314 return copy;
1317 /* Save the copy COPY of function FUN for later reuse by
1318 get_fundef_copy(). By construction, there will always be an entry
1319 to find. */
1321 static void
1322 save_fundef_copy (tree fun, tree copy)
1324 tree *slot = fundef_copies_table->get (fun);
1325 TREE_CHAIN (copy) = *slot;
1326 *slot = copy;
1329 /* We have an expression tree T that represents a call, either CALL_EXPR
1330 or AGGR_INIT_EXPR. Return the Nth argument. */
1332 static inline tree
1333 get_nth_callarg (tree t, int n)
1335 switch (TREE_CODE (t))
1337 case CALL_EXPR:
1338 return CALL_EXPR_ARG (t, n);
1340 case AGGR_INIT_EXPR:
1341 return AGGR_INIT_EXPR_ARG (t, n);
1343 default:
1344 gcc_unreachable ();
1345 return NULL;
1349 /* Attempt to evaluate T which represents a call to a builtin function.
1350 We assume here that all builtin functions evaluate to scalar types
1351 represented by _CST nodes. */
1353 static tree
1354 cxx_eval_builtin_function_call (const constexpr_ctx *ctx, tree t, tree fun,
1355 bool lval,
1356 bool *non_constant_p, bool *overflow_p)
1358 const int nargs = call_expr_nargs (t);
1359 tree *args = (tree *) alloca (nargs * sizeof (tree));
1360 tree new_call;
1361 int i;
1363 /* Don't fold __builtin_constant_p within a constexpr function. */
1364 bool bi_const_p = DECL_IS_BUILTIN_CONSTANT_P (fun);
1366 /* If we aren't requiring a constant expression, defer __builtin_constant_p
1367 in a constexpr function until we have values for the parameters. */
1368 if (bi_const_p
1369 && !ctx->manifestly_const_eval
1370 && current_function_decl
1371 && DECL_DECLARED_CONSTEXPR_P (current_function_decl))
1373 *non_constant_p = true;
1374 return t;
1377 /* For __builtin_is_constant_evaluated, defer it if not
1378 ctx->manifestly_const_eval (as sometimes we try to constant evaluate
1379 without manifestly_const_eval even expressions or parts thereof which
1380 will later be manifestly const_eval evaluated), otherwise fold it to
1381 true. */
1382 if (fndecl_built_in_p (fun, CP_BUILT_IN_IS_CONSTANT_EVALUATED,
1383 BUILT_IN_FRONTEND))
1385 if (!ctx->manifestly_const_eval)
1387 *non_constant_p = true;
1388 return t;
1390 return boolean_true_node;
1393 if (fndecl_built_in_p (fun, CP_BUILT_IN_SOURCE_LOCATION, BUILT_IN_FRONTEND))
1395 temp_override<tree> ovr (current_function_decl);
1396 if (ctx->call && ctx->call->fundef)
1397 current_function_decl = ctx->call->fundef->decl;
1398 return fold_builtin_source_location (EXPR_LOCATION (t));
1401 int strops = 0;
1402 int strret = 0;
1403 if (fndecl_built_in_p (fun, BUILT_IN_NORMAL))
1404 switch (DECL_FUNCTION_CODE (fun))
1406 case BUILT_IN_STRLEN:
1407 case BUILT_IN_STRNLEN:
1408 strops = 1;
1409 break;
1410 case BUILT_IN_MEMCHR:
1411 case BUILT_IN_STRCHR:
1412 case BUILT_IN_STRRCHR:
1413 strops = 1;
1414 strret = 1;
1415 break;
1416 case BUILT_IN_MEMCMP:
1417 case BUILT_IN_STRCMP:
1418 strops = 2;
1419 break;
1420 case BUILT_IN_STRSTR:
1421 strops = 2;
1422 strret = 1;
1423 break;
1424 case BUILT_IN_ASAN_POINTER_COMPARE:
1425 case BUILT_IN_ASAN_POINTER_SUBTRACT:
1426 /* These builtins shall be ignored during constant expression
1427 evaluation. */
1428 return void_node;
1429 default:
1430 break;
1433 /* Be permissive for arguments to built-ins; __builtin_constant_p should
1434 return constant false for a non-constant argument. */
1435 constexpr_ctx new_ctx = *ctx;
1436 new_ctx.quiet = true;
1437 for (i = 0; i < nargs; ++i)
1439 tree arg = CALL_EXPR_ARG (t, i);
1440 tree oarg = arg;
1442 /* To handle string built-ins we need to pass ADDR_EXPR<STRING_CST> since
1443 expand_builtin doesn't know how to look in the values table. */
1444 bool strop = i < strops;
1445 if (strop)
1447 STRIP_NOPS (arg);
1448 if (TREE_CODE (arg) == ADDR_EXPR)
1449 arg = TREE_OPERAND (arg, 0);
1450 else
1451 strop = false;
1454 /* If builtin_valid_in_constant_expr_p is true,
1455 potential_constant_expression_1 has not recursed into the arguments
1456 of the builtin, verify it here. */
1457 if (!builtin_valid_in_constant_expr_p (fun)
1458 || potential_constant_expression (arg))
1460 bool dummy1 = false, dummy2 = false;
1461 arg = cxx_eval_constant_expression (&new_ctx, arg, false,
1462 &dummy1, &dummy2);
1465 if (bi_const_p)
1466 /* For __builtin_constant_p, fold all expressions with constant values
1467 even if they aren't C++ constant-expressions. */
1468 arg = cp_fold_rvalue (arg);
1469 else if (strop)
1471 if (TREE_CODE (arg) == CONSTRUCTOR)
1472 arg = braced_lists_to_strings (TREE_TYPE (arg), arg);
1473 if (TREE_CODE (arg) == STRING_CST)
1474 arg = build_address (arg);
1475 else
1476 arg = oarg;
1479 args[i] = arg;
1482 bool save_ffbcp = force_folding_builtin_constant_p;
1483 force_folding_builtin_constant_p |= ctx->manifestly_const_eval;
1484 tree save_cur_fn = current_function_decl;
1485 /* Return name of ctx->call->fundef->decl for __builtin_FUNCTION (). */
1486 if (fndecl_built_in_p (fun, BUILT_IN_FUNCTION)
1487 && ctx->call
1488 && ctx->call->fundef)
1489 current_function_decl = ctx->call->fundef->decl;
1490 if (fndecl_built_in_p (fun,
1491 CP_BUILT_IN_IS_POINTER_INTERCONVERTIBLE_WITH_CLASS,
1492 BUILT_IN_FRONTEND))
1494 location_t loc = EXPR_LOCATION (t);
1495 if (nargs >= 1)
1496 VERIFY_CONSTANT (args[0]);
1497 new_call
1498 = fold_builtin_is_pointer_inverconvertible_with_class (loc, nargs,
1499 args);
1501 else if (fndecl_built_in_p (fun,
1502 CP_BUILT_IN_IS_CORRESPONDING_MEMBER,
1503 BUILT_IN_FRONTEND))
1505 location_t loc = EXPR_LOCATION (t);
1506 if (nargs >= 2)
1508 VERIFY_CONSTANT (args[0]);
1509 VERIFY_CONSTANT (args[1]);
1511 new_call = fold_builtin_is_corresponding_member (loc, nargs, args);
1513 else
1514 new_call = fold_builtin_call_array (EXPR_LOCATION (t), TREE_TYPE (t),
1515 CALL_EXPR_FN (t), nargs, args);
1516 current_function_decl = save_cur_fn;
1517 force_folding_builtin_constant_p = save_ffbcp;
1518 if (new_call == NULL)
1520 if (!*non_constant_p && !ctx->quiet)
1522 /* Do not allow__builtin_unreachable in constexpr function.
1523 The __builtin_unreachable call with BUILTINS_LOCATION
1524 comes from cp_maybe_instrument_return. */
1525 if (fndecl_built_in_p (fun, BUILT_IN_UNREACHABLE)
1526 && EXPR_LOCATION (t) == BUILTINS_LOCATION)
1527 error ("%<constexpr%> call flows off the end of the function");
1528 else
1530 new_call = build_call_array_loc (EXPR_LOCATION (t), TREE_TYPE (t),
1531 CALL_EXPR_FN (t), nargs, args);
1532 error ("%q+E is not a constant expression", new_call);
1535 *non_constant_p = true;
1536 return t;
1539 if (!potential_constant_expression (new_call))
1541 if (!*non_constant_p && !ctx->quiet)
1542 error ("%q+E is not a constant expression", new_call);
1543 *non_constant_p = true;
1544 return t;
1547 if (strret)
1549 /* memchr returns a pointer into the first argument, but we replaced the
1550 argument above with a STRING_CST; put it back it now. */
1551 tree op = CALL_EXPR_ARG (t, strret-1);
1552 STRIP_NOPS (new_call);
1553 if (TREE_CODE (new_call) == POINTER_PLUS_EXPR)
1554 TREE_OPERAND (new_call, 0) = op;
1555 else if (TREE_CODE (new_call) == ADDR_EXPR)
1556 new_call = op;
1559 return cxx_eval_constant_expression (&new_ctx, new_call, lval,
1560 non_constant_p, overflow_p);
1563 /* TEMP is the constant value of a temporary object of type TYPE. Adjust
1564 the type of the value to match. */
1566 static tree
1567 adjust_temp_type (tree type, tree temp)
1569 if (same_type_p (TREE_TYPE (temp), type))
1570 return temp;
1571 /* Avoid wrapping an aggregate value in a NOP_EXPR. */
1572 if (TREE_CODE (temp) == CONSTRUCTOR)
1574 /* build_constructor wouldn't retain various CONSTRUCTOR flags. */
1575 tree t = copy_node (temp);
1576 TREE_TYPE (t) = type;
1577 return t;
1579 if (TREE_CODE (temp) == EMPTY_CLASS_EXPR)
1580 return build0 (EMPTY_CLASS_EXPR, type);
1581 gcc_assert (scalarish_type_p (type));
1582 /* Now we know we're dealing with a scalar, and a prvalue of non-class
1583 type is cv-unqualified. */
1584 return cp_fold_convert (cv_unqualified (type), temp);
1587 /* If T is a CONSTRUCTOR, return an unshared copy of T and any
1588 sub-CONSTRUCTORs. Otherwise return T.
1590 We use this whenever we initialize an object as a whole, whether it's a
1591 parameter, a local variable, or a subobject, so that subsequent
1592 modifications don't affect other places where it was used. */
1594 tree
1595 unshare_constructor (tree t MEM_STAT_DECL)
1597 if (!t || TREE_CODE (t) != CONSTRUCTOR)
1598 return t;
1599 auto_vec <tree*, 4> ptrs;
1600 ptrs.safe_push (&t);
1601 while (!ptrs.is_empty ())
1603 tree *p = ptrs.pop ();
1604 tree n = copy_node (*p PASS_MEM_STAT);
1605 CONSTRUCTOR_ELTS (n) = vec_safe_copy (CONSTRUCTOR_ELTS (*p) PASS_MEM_STAT);
1606 *p = n;
1607 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (n);
1608 constructor_elt *ce;
1609 for (HOST_WIDE_INT i = 0; vec_safe_iterate (v, i, &ce); ++i)
1610 if (ce->value && TREE_CODE (ce->value) == CONSTRUCTOR)
1611 ptrs.safe_push (&ce->value);
1613 return t;
1616 /* If T is a CONSTRUCTOR, ggc_free T and any sub-CONSTRUCTORs. */
1618 static void
1619 free_constructor (tree t)
1621 if (!t || TREE_CODE (t) != CONSTRUCTOR)
1622 return;
1623 releasing_vec ctors;
1624 vec_safe_push (ctors, t);
1625 while (!ctors->is_empty ())
1627 tree c = ctors->pop ();
1628 if (vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (c))
1630 constructor_elt *ce;
1631 for (HOST_WIDE_INT i = 0; vec_safe_iterate (elts, i, &ce); ++i)
1632 if (TREE_CODE (ce->value) == CONSTRUCTOR)
1633 vec_safe_push (ctors, ce->value);
1634 ggc_free (elts);
1636 ggc_free (c);
1640 /* Helper function of cxx_bind_parameters_in_call. Return non-NULL
1641 if *TP is address of a static variable (or part of it) currently being
1642 constructed or of a heap artificial variable. */
1644 static tree
1645 addr_of_non_const_var (tree *tp, int *walk_subtrees, void *data)
1647 if (TREE_CODE (*tp) == ADDR_EXPR)
1648 if (tree var = get_base_address (TREE_OPERAND (*tp, 0)))
1649 if (VAR_P (var) && TREE_STATIC (var))
1651 if (DECL_NAME (var) == heap_uninit_identifier
1652 || DECL_NAME (var) == heap_identifier
1653 || DECL_NAME (var) == heap_vec_uninit_identifier
1654 || DECL_NAME (var) == heap_vec_identifier)
1655 return var;
1657 constexpr_global_ctx *global = (constexpr_global_ctx *) data;
1658 if (global->values.get (var))
1659 return var;
1661 if (TYPE_P (*tp))
1662 *walk_subtrees = false;
1663 return NULL_TREE;
1666 /* Subroutine of cxx_eval_call_expression.
1667 We are processing a call expression (either CALL_EXPR or
1668 AGGR_INIT_EXPR) in the context of CTX. Evaluate
1669 all arguments and bind their values to correspondings
1670 parameters, making up the NEW_CALL context. */
1672 static tree
1673 cxx_bind_parameters_in_call (const constexpr_ctx *ctx, tree t, tree fun,
1674 bool *non_constant_p, bool *overflow_p,
1675 bool *non_constant_args)
1677 const int nargs = call_expr_nargs (t);
1678 tree parms = DECL_ARGUMENTS (fun);
1679 int i;
1680 /* We don't record ellipsis args below. */
1681 int nparms = list_length (parms);
1682 int nbinds = nargs < nparms ? nargs : nparms;
1683 tree binds = make_tree_vec (nbinds);
1684 for (i = 0; i < nargs; ++i)
1686 tree x, arg;
1687 tree type = parms ? TREE_TYPE (parms) : void_type_node;
1688 if (parms && DECL_BY_REFERENCE (parms))
1689 type = TREE_TYPE (type);
1690 x = get_nth_callarg (t, i);
1691 /* For member function, the first argument is a pointer to the implied
1692 object. For a constructor, it might still be a dummy object, in
1693 which case we get the real argument from ctx. */
1694 if (i == 0 && DECL_CONSTRUCTOR_P (fun)
1695 && is_dummy_object (x))
1697 x = ctx->object;
1698 x = build_address (x);
1700 if (TREE_ADDRESSABLE (type))
1701 /* Undo convert_for_arg_passing work here. */
1702 x = convert_from_reference (x);
1703 /* Normally we would strip a TARGET_EXPR in an initialization context
1704 such as this, but here we do the elision differently: we keep the
1705 TARGET_EXPR, and use its CONSTRUCTOR as the value of the parm. */
1706 arg = cxx_eval_constant_expression (ctx, x, /*lval=*/false,
1707 non_constant_p, overflow_p);
1708 /* Don't VERIFY_CONSTANT here. */
1709 if (*non_constant_p && ctx->quiet)
1710 break;
1711 /* Just discard ellipsis args after checking their constantitude. */
1712 if (!parms)
1713 continue;
1715 if (!*non_constant_p)
1717 /* Make sure the binding has the same type as the parm. But
1718 only for constant args. */
1719 if (!TYPE_REF_P (type))
1720 arg = adjust_temp_type (type, arg);
1721 if (!TREE_CONSTANT (arg))
1722 *non_constant_args = true;
1723 else if (TYPE_HAS_NONTRIVIAL_DESTRUCTOR (type))
1724 /* The destructor needs to see any modifications the callee makes
1725 to the argument. */
1726 *non_constant_args = true;
1727 /* If arg is or contains address of a heap artificial variable or
1728 of a static variable being constructed, avoid caching the
1729 function call, as those variables might be modified by the
1730 function, or might be modified by the callers in between
1731 the cached function and just read by the function. */
1732 else if (!*non_constant_args
1733 && cp_walk_tree (&arg, addr_of_non_const_var, ctx->global,
1734 NULL))
1735 *non_constant_args = true;
1737 /* For virtual calls, adjust the this argument, so that it is
1738 the object on which the method is called, rather than
1739 one of its bases. */
1740 if (i == 0 && DECL_VIRTUAL_P (fun))
1742 tree addr = arg;
1743 STRIP_NOPS (addr);
1744 if (TREE_CODE (addr) == ADDR_EXPR)
1746 tree obj = TREE_OPERAND (addr, 0);
1747 while (TREE_CODE (obj) == COMPONENT_REF
1748 && DECL_FIELD_IS_BASE (TREE_OPERAND (obj, 1))
1749 && !same_type_ignoring_top_level_qualifiers_p
1750 (TREE_TYPE (obj), DECL_CONTEXT (fun)))
1751 obj = TREE_OPERAND (obj, 0);
1752 if (obj != TREE_OPERAND (addr, 0))
1753 arg = build_fold_addr_expr_with_type (obj,
1754 TREE_TYPE (arg));
1757 TREE_VEC_ELT (binds, i) = arg;
1759 parms = TREE_CHAIN (parms);
1762 return binds;
1765 /* Variables and functions to manage constexpr call expansion context.
1766 These do not need to be marked for PCH or GC. */
1768 /* FIXME remember and print actual constant arguments. */
1769 static vec<tree> call_stack;
1770 static int call_stack_tick;
1771 static int last_cx_error_tick;
1773 static int
1774 push_cx_call_context (tree call)
1776 ++call_stack_tick;
1777 if (!EXPR_HAS_LOCATION (call))
1778 SET_EXPR_LOCATION (call, input_location);
1779 call_stack.safe_push (call);
1780 int len = call_stack.length ();
1781 if (len > max_constexpr_depth)
1782 return false;
1783 return len;
1786 static void
1787 pop_cx_call_context (void)
1789 ++call_stack_tick;
1790 call_stack.pop ();
1793 vec<tree>
1794 cx_error_context (void)
1796 vec<tree> r = vNULL;
1797 if (call_stack_tick != last_cx_error_tick
1798 && !call_stack.is_empty ())
1799 r = call_stack;
1800 last_cx_error_tick = call_stack_tick;
1801 return r;
1804 /* Evaluate a call T to a GCC internal function when possible and return
1805 the evaluated result or, under the control of CTX, give an error, set
1806 NON_CONSTANT_P, and return the unevaluated call T otherwise. */
1808 static tree
1809 cxx_eval_internal_function (const constexpr_ctx *ctx, tree t,
1810 bool lval,
1811 bool *non_constant_p, bool *overflow_p)
1813 enum tree_code opcode = ERROR_MARK;
1815 switch (CALL_EXPR_IFN (t))
1817 case IFN_UBSAN_NULL:
1818 case IFN_UBSAN_BOUNDS:
1819 case IFN_UBSAN_VPTR:
1820 case IFN_FALLTHROUGH:
1821 return void_node;
1823 case IFN_ADD_OVERFLOW:
1824 opcode = PLUS_EXPR;
1825 break;
1826 case IFN_SUB_OVERFLOW:
1827 opcode = MINUS_EXPR;
1828 break;
1829 case IFN_MUL_OVERFLOW:
1830 opcode = MULT_EXPR;
1831 break;
1833 case IFN_LAUNDER:
1834 return cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0),
1835 false, non_constant_p, overflow_p);
1837 case IFN_VEC_CONVERT:
1839 tree arg = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0),
1840 false, non_constant_p,
1841 overflow_p);
1842 if (TREE_CODE (arg) == VECTOR_CST)
1843 if (tree r = fold_const_call (CFN_VEC_CONVERT, TREE_TYPE (t), arg))
1844 return r;
1846 /* FALLTHRU */
1848 default:
1849 if (!ctx->quiet)
1850 error_at (cp_expr_loc_or_input_loc (t),
1851 "call to internal function %qE", t);
1852 *non_constant_p = true;
1853 return t;
1856 /* Evaluate constant arguments using OPCODE and return a complex
1857 number containing the result and the overflow bit. */
1858 tree arg0 = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0), lval,
1859 non_constant_p, overflow_p);
1860 tree arg1 = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 1), lval,
1861 non_constant_p, overflow_p);
1863 if (TREE_CODE (arg0) == INTEGER_CST && TREE_CODE (arg1) == INTEGER_CST)
1865 location_t loc = cp_expr_loc_or_input_loc (t);
1866 tree type = TREE_TYPE (TREE_TYPE (t));
1867 tree result = fold_binary_loc (loc, opcode, type,
1868 fold_convert_loc (loc, type, arg0),
1869 fold_convert_loc (loc, type, arg1));
1870 tree ovf
1871 = build_int_cst (type, arith_overflowed_p (opcode, type, arg0, arg1));
1872 /* Reset TREE_OVERFLOW to avoid warnings for the overflow. */
1873 if (TREE_OVERFLOW (result))
1874 TREE_OVERFLOW (result) = 0;
1876 return build_complex (TREE_TYPE (t), result, ovf);
1879 *non_constant_p = true;
1880 return t;
1883 /* Clean CONSTRUCTOR_NO_CLEARING from CTOR and its sub-aggregates. */
1885 static void
1886 clear_no_implicit_zero (tree ctor)
1888 if (CONSTRUCTOR_NO_CLEARING (ctor))
1890 CONSTRUCTOR_NO_CLEARING (ctor) = false;
1891 for (auto &e: CONSTRUCTOR_ELTS (ctor))
1892 if (TREE_CODE (e.value) == CONSTRUCTOR)
1893 clear_no_implicit_zero (e.value);
1897 /* Complain about a const object OBJ being modified in a constant expression.
1898 EXPR is the MODIFY_EXPR expression performing the modification. */
1900 static void
1901 modifying_const_object_error (tree expr, tree obj)
1903 location_t loc = cp_expr_loc_or_input_loc (expr);
1904 auto_diagnostic_group d;
1905 error_at (loc, "modifying a const object %qE is not allowed in "
1906 "a constant expression", TREE_OPERAND (expr, 0));
1907 inform (location_of (obj), "originally declared %<const%> here");
1910 /* Return true if FNDECL is a replaceable global allocation function that
1911 should be useable during constant expression evaluation. */
1913 static inline bool
1914 cxx_replaceable_global_alloc_fn (tree fndecl)
1916 return (cxx_dialect >= cxx20
1917 && IDENTIFIER_NEWDEL_OP_P (DECL_NAME (fndecl))
1918 && CP_DECL_CONTEXT (fndecl) == global_namespace
1919 && (DECL_IS_REPLACEABLE_OPERATOR_NEW_P (fndecl)
1920 || DECL_IS_OPERATOR_DELETE_P (fndecl)));
1923 /* Return true if FNDECL is a placement new function that should be
1924 useable during constant expression evaluation of std::construct_at. */
1926 static inline bool
1927 cxx_placement_new_fn (tree fndecl)
1929 if (cxx_dialect >= cxx20
1930 && IDENTIFIER_NEW_OP_P (DECL_NAME (fndecl))
1931 && CP_DECL_CONTEXT (fndecl) == global_namespace
1932 && !DECL_IS_REPLACEABLE_OPERATOR_NEW_P (fndecl)
1933 && TREE_CODE (TREE_TYPE (fndecl)) == FUNCTION_TYPE)
1935 tree first_arg = TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (fndecl)));
1936 if (TREE_VALUE (first_arg) == ptr_type_node
1937 && TREE_CHAIN (first_arg) == void_list_node)
1938 return true;
1940 return false;
1943 /* Return true if FNDECL is std::construct_at. */
1945 static inline bool
1946 is_std_construct_at (tree fndecl)
1948 if (!decl_in_std_namespace_p (fndecl))
1949 return false;
1951 tree name = DECL_NAME (fndecl);
1952 return name && id_equal (name, "construct_at");
1955 /* Overload for the above taking constexpr_call*. */
1957 static inline bool
1958 is_std_construct_at (const constexpr_call *call)
1960 return (call
1961 && call->fundef
1962 && is_std_construct_at (call->fundef->decl));
1965 /* Return true if FNDECL is std::allocator<T>::{,de}allocate. */
1967 static inline bool
1968 is_std_allocator_allocate (tree fndecl)
1970 tree name = DECL_NAME (fndecl);
1971 if (name == NULL_TREE
1972 || !(id_equal (name, "allocate") || id_equal (name, "deallocate")))
1973 return false;
1975 tree ctx = DECL_CONTEXT (fndecl);
1976 if (ctx == NULL_TREE || !CLASS_TYPE_P (ctx) || !TYPE_MAIN_DECL (ctx))
1977 return false;
1979 tree decl = TYPE_MAIN_DECL (ctx);
1980 name = DECL_NAME (decl);
1981 if (name == NULL_TREE || !id_equal (name, "allocator"))
1982 return false;
1984 return decl_in_std_namespace_p (decl);
1987 /* Overload for the above taking constexpr_call*. */
1989 static inline bool
1990 is_std_allocator_allocate (const constexpr_call *call)
1992 return (call
1993 && call->fundef
1994 && is_std_allocator_allocate (call->fundef->decl));
1997 /* Return true if FNDECL is __dynamic_cast. */
1999 static inline bool
2000 cxx_dynamic_cast_fn_p (tree fndecl)
2002 return (cxx_dialect >= cxx20
2003 && id_equal (DECL_NAME (fndecl), "__dynamic_cast")
2004 && CP_DECL_CONTEXT (fndecl) == global_namespace);
2007 /* Often, we have an expression in the form of address + offset, e.g.
2008 "&_ZTV1A + 16". Extract the object from it, i.e. "_ZTV1A". */
2010 static tree
2011 extract_obj_from_addr_offset (tree expr)
2013 if (TREE_CODE (expr) == POINTER_PLUS_EXPR)
2014 expr = TREE_OPERAND (expr, 0);
2015 STRIP_NOPS (expr);
2016 if (TREE_CODE (expr) == ADDR_EXPR)
2017 expr = TREE_OPERAND (expr, 0);
2018 return expr;
2021 /* Given a PATH like
2023 g.D.2181.D.2154.D.2102.D.2093
2025 find a component with type TYPE. Return NULL_TREE if not found, and
2026 error_mark_node if the component is not accessible. If STOP is non-null,
2027 this function will return NULL_TREE if STOP is found before TYPE. */
2029 static tree
2030 get_component_with_type (tree path, tree type, tree stop)
2032 while (true)
2034 if (same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (path), type))
2035 /* Found it. */
2036 return path;
2037 else if (stop
2038 && (same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (path),
2039 stop)))
2040 return NULL_TREE;
2041 else if (TREE_CODE (path) == COMPONENT_REF
2042 && DECL_FIELD_IS_BASE (TREE_OPERAND (path, 1)))
2044 /* We need to check that the component we're accessing is in fact
2045 accessible. */
2046 if (TREE_PRIVATE (TREE_OPERAND (path, 1))
2047 || TREE_PROTECTED (TREE_OPERAND (path, 1)))
2048 return error_mark_node;
2049 path = TREE_OPERAND (path, 0);
2051 else
2052 return NULL_TREE;
2056 /* Evaluate a call to __dynamic_cast (permitted by P1327R1).
2058 The declaration of __dynamic_cast is:
2060 void* __dynamic_cast (const void* __src_ptr,
2061 const __class_type_info* __src_type,
2062 const __class_type_info* __dst_type,
2063 ptrdiff_t __src2dst);
2065 where src2dst has the following possible values
2067 >-1: src_type is a unique public non-virtual base of dst_type
2068 dst_ptr + src2dst == src_ptr
2069 -1: unspecified relationship
2070 -2: src_type is not a public base of dst_type
2071 -3: src_type is a multiple public non-virtual base of dst_type
2073 Since literal types can't have virtual bases, we only expect hint >=0,
2074 -2, or -3. */
2076 static tree
2077 cxx_eval_dynamic_cast_fn (const constexpr_ctx *ctx, tree call,
2078 bool *non_constant_p, bool *overflow_p)
2080 /* T will be something like
2081 __dynamic_cast ((B*) b, &_ZTI1B, &_ZTI1D, 8)
2082 dismantle it. */
2083 gcc_assert (call_expr_nargs (call) == 4);
2084 tsubst_flags_t complain = ctx->quiet ? tf_none : tf_warning_or_error;
2085 tree obj = CALL_EXPR_ARG (call, 0);
2086 tree type = CALL_EXPR_ARG (call, 2);
2087 HOST_WIDE_INT hint = int_cst_value (CALL_EXPR_ARG (call, 3));
2088 location_t loc = cp_expr_loc_or_input_loc (call);
2090 /* Get the target type of the dynamic_cast. */
2091 gcc_assert (TREE_CODE (type) == ADDR_EXPR);
2092 type = TREE_OPERAND (type, 0);
2093 type = TREE_TYPE (DECL_NAME (type));
2095 /* TYPE can only be either T* or T&. We can't know which of these it
2096 is by looking at TYPE, but OBJ will be "(T*) x" in the first case,
2097 and something like "(T*)(T&)(T*) x" in the second case. */
2098 bool reference_p = false;
2099 while (CONVERT_EXPR_P (obj) || TREE_CODE (obj) == SAVE_EXPR)
2101 reference_p |= TYPE_REF_P (TREE_TYPE (obj));
2102 obj = TREE_OPERAND (obj, 0);
2105 /* Evaluate the object so that we know its dynamic type. */
2106 obj = cxx_eval_constant_expression (ctx, obj, /*lval*/false, non_constant_p,
2107 overflow_p);
2108 if (*non_constant_p)
2109 return call;
2111 /* We expect OBJ to be in form of &d.D.2102 when HINT == 0,
2112 but when HINT is > 0, it can also be something like
2113 &d.D.2102 + 18446744073709551608, which includes the BINFO_OFFSET. */
2114 obj = extract_obj_from_addr_offset (obj);
2115 const tree objtype = TREE_TYPE (obj);
2116 /* If OBJ doesn't refer to a base field, we're done. */
2117 if (tree t = (TREE_CODE (obj) == COMPONENT_REF
2118 ? TREE_OPERAND (obj, 1) : obj))
2119 if (TREE_CODE (t) != FIELD_DECL || !DECL_FIELD_IS_BASE (t))
2121 if (reference_p)
2123 if (!ctx->quiet)
2125 error_at (loc, "reference %<dynamic_cast%> failed");
2126 inform (loc, "dynamic type %qT of its operand does "
2127 "not have a base class of type %qT",
2128 objtype, type);
2130 *non_constant_p = true;
2132 return integer_zero_node;
2135 /* [class.cdtor] When a dynamic_cast is used in a constructor ...
2136 or in a destructor ... if the operand of the dynamic_cast refers
2137 to the object under construction or destruction, this object is
2138 considered to be a most derived object that has the type of the
2139 constructor or destructor's class. */
2140 tree vtable = build_vfield_ref (obj, objtype);
2141 vtable = cxx_eval_constant_expression (ctx, vtable, /*lval*/false,
2142 non_constant_p, overflow_p);
2143 if (*non_constant_p)
2144 return call;
2145 /* With -fsanitize=vptr, we initialize all vtable pointers to null,
2146 so it's possible that we got a null pointer now. */
2147 if (integer_zerop (vtable))
2149 if (!ctx->quiet)
2150 error_at (loc, "virtual table pointer is used uninitialized");
2151 *non_constant_p = true;
2152 return integer_zero_node;
2154 /* VTABLE will be &_ZTV1A + 16 or similar, get _ZTV1A. */
2155 vtable = extract_obj_from_addr_offset (vtable);
2156 const tree mdtype = DECL_CONTEXT (vtable);
2158 /* Given dynamic_cast<T>(v),
2160 [expr.dynamic.cast] If C is the class type to which T points or refers,
2161 the runtime check logically executes as follows:
2163 If, in the most derived object pointed (referred) to by v, v points
2164 (refers) to a public base class subobject of a C object, and if only
2165 one object of type C is derived from the subobject pointed (referred)
2166 to by v the result points (refers) to that C object.
2168 In this case, HINT >= 0 or -3. */
2169 if (hint >= 0 || hint == -3)
2171 /* Look for a component with type TYPE. */
2172 tree t = get_component_with_type (obj, type, mdtype);
2173 /* If not accessible, give an error. */
2174 if (t == error_mark_node)
2176 if (reference_p)
2178 if (!ctx->quiet)
2180 error_at (loc, "reference %<dynamic_cast%> failed");
2181 inform (loc, "static type %qT of its operand is a "
2182 "non-public base class of dynamic type %qT",
2183 objtype, type);
2186 *non_constant_p = true;
2188 return integer_zero_node;
2190 else if (t)
2191 /* The result points to the TYPE object. */
2192 return cp_build_addr_expr (t, complain);
2193 /* Else, TYPE was not found, because the HINT turned out to be wrong.
2194 Fall through to the normal processing. */
2197 /* Otherwise, if v points (refers) to a public base class subobject of the
2198 most derived object, and the type of the most derived object has a base
2199 class, of type C, that is unambiguous and public, the result points
2200 (refers) to the C subobject of the most derived object.
2202 But it can also be an invalid case. */
2204 /* Get the most derived object. */
2205 obj = get_component_with_type (obj, mdtype, NULL_TREE);
2206 if (obj == error_mark_node)
2208 if (reference_p)
2210 if (!ctx->quiet)
2212 error_at (loc, "reference %<dynamic_cast%> failed");
2213 inform (loc, "static type %qT of its operand is a non-public"
2214 " base class of dynamic type %qT", objtype, mdtype);
2216 *non_constant_p = true;
2218 return integer_zero_node;
2220 else
2221 gcc_assert (obj);
2223 /* Check that the type of the most derived object has a base class
2224 of type TYPE that is unambiguous and public. */
2225 base_kind b_kind;
2226 tree binfo = lookup_base (mdtype, type, ba_check, &b_kind, tf_none);
2227 if (!binfo || binfo == error_mark_node)
2229 if (reference_p)
2231 if (!ctx->quiet)
2233 error_at (loc, "reference %<dynamic_cast%> failed");
2234 if (b_kind == bk_ambig)
2235 inform (loc, "%qT is an ambiguous base class of dynamic "
2236 "type %qT of its operand", type, mdtype);
2237 else
2238 inform (loc, "dynamic type %qT of its operand does not "
2239 "have an unambiguous public base class %qT",
2240 mdtype, type);
2242 *non_constant_p = true;
2244 return integer_zero_node;
2246 /* If so, return the TYPE subobject of the most derived object. */
2247 obj = convert_to_base_statically (obj, binfo);
2248 return cp_build_addr_expr (obj, complain);
2251 /* Data structure used by replace_decl and replace_decl_r. */
2253 struct replace_decl_data
2255 /* The _DECL we want to replace. */
2256 tree decl;
2257 /* The replacement for DECL. */
2258 tree replacement;
2259 /* Trees we've visited. */
2260 hash_set<tree> *pset;
2261 /* Whether we've performed any replacements. */
2262 bool changed;
2265 /* Helper function for replace_decl, called through cp_walk_tree. */
2267 static tree
2268 replace_decl_r (tree *tp, int *walk_subtrees, void *data)
2270 replace_decl_data *d = (replace_decl_data *) data;
2272 if (*tp == d->decl)
2274 *tp = unshare_expr (d->replacement);
2275 d->changed = true;
2276 *walk_subtrees = 0;
2278 else if (TYPE_P (*tp)
2279 || d->pset->add (*tp))
2280 *walk_subtrees = 0;
2282 return NULL_TREE;
2285 /* Replace every occurrence of DECL with (an unshared copy of)
2286 REPLACEMENT within the expression *TP. Returns true iff a
2287 replacement was performed. */
2289 bool
2290 replace_decl (tree *tp, tree decl, tree replacement)
2292 gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
2293 (TREE_TYPE (decl), TREE_TYPE (replacement)));
2294 hash_set<tree> pset;
2295 replace_decl_data data = { decl, replacement, &pset, false };
2296 cp_walk_tree (tp, replace_decl_r, &data, NULL);
2297 return data.changed;
2300 /* Evaluate the call T to virtual function thunk THUNK_FNDECL. */
2302 static tree
2303 cxx_eval_thunk_call (const constexpr_ctx *ctx, tree t, tree thunk_fndecl,
2304 bool lval,
2305 bool *non_constant_p, bool *overflow_p)
2307 tree function = THUNK_TARGET (thunk_fndecl);
2309 if (THUNK_VIRTUAL_OFFSET (thunk_fndecl))
2311 if (!ctx->quiet)
2313 if (!DECL_DECLARED_CONSTEXPR_P (function))
2315 error ("call to non-%<constexpr%> function %qD", function);
2316 explain_invalid_constexpr_fn (function);
2318 else
2319 /* virtual_offset is only set for virtual bases, which make the
2320 class non-literal, so we don't need to handle it here. */
2321 error ("calling constexpr member function %qD through virtual "
2322 "base subobject", function);
2324 *non_constant_p = true;
2325 return t;
2328 tree new_call = copy_node (t);
2329 CALL_EXPR_FN (new_call) = function;
2330 TREE_TYPE (new_call) = TREE_TYPE (TREE_TYPE (function));
2332 tree offset = size_int (THUNK_FIXED_OFFSET (thunk_fndecl));
2334 if (DECL_THIS_THUNK_P (thunk_fndecl))
2336 /* 'this'-adjusting thunk. */
2337 tree this_arg = CALL_EXPR_ARG (t, 0);
2338 this_arg = build2 (POINTER_PLUS_EXPR, TREE_TYPE (this_arg),
2339 this_arg, offset);
2340 CALL_EXPR_ARG (new_call, 0) = this_arg;
2342 else
2343 /* Return-adjusting thunk. */
2344 new_call = build2 (POINTER_PLUS_EXPR, TREE_TYPE (new_call),
2345 new_call, offset);
2347 return cxx_eval_constant_expression (ctx, new_call, lval,
2348 non_constant_p, overflow_p);
2351 /* If OBJECT is of const class type, evaluate it to a CONSTRUCTOR and set
2352 its TREE_READONLY flag according to READONLY_P. Used for constexpr
2353 'tors to detect modifying const objects in a constexpr context. */
2355 static void
2356 cxx_set_object_constness (const constexpr_ctx *ctx, tree object,
2357 bool readonly_p, bool *non_constant_p,
2358 bool *overflow_p)
2360 if (CLASS_TYPE_P (TREE_TYPE (object))
2361 && CP_TYPE_CONST_P (TREE_TYPE (object)))
2363 /* Subobjects might not be stored in ctx->global->values but we
2364 can get its CONSTRUCTOR by evaluating *this. */
2365 tree e = cxx_eval_constant_expression (ctx, object, /*lval*/false,
2366 non_constant_p, overflow_p);
2367 if (TREE_CODE (e) == CONSTRUCTOR && !*non_constant_p)
2368 TREE_READONLY (e) = readonly_p;
2372 /* Subroutine of cxx_eval_constant_expression.
2373 Evaluate the call expression tree T in the context of OLD_CALL expression
2374 evaluation. */
2376 static tree
2377 cxx_eval_call_expression (const constexpr_ctx *ctx, tree t,
2378 bool lval,
2379 bool *non_constant_p, bool *overflow_p)
2381 /* Handle concept checks separately. */
2382 if (concept_check_p (t))
2383 return evaluate_concept_check (t);
2385 location_t loc = cp_expr_loc_or_input_loc (t);
2386 tree fun = get_function_named_in_call (t);
2387 constexpr_call new_call
2388 = { NULL, NULL, NULL, 0, ctx->manifestly_const_eval };
2389 int depth_ok;
2391 if (fun == NULL_TREE)
2392 return cxx_eval_internal_function (ctx, t, lval,
2393 non_constant_p, overflow_p);
2395 if (TREE_CODE (fun) != FUNCTION_DECL)
2397 /* Might be a constexpr function pointer. */
2398 fun = cxx_eval_constant_expression (ctx, fun,
2399 /*lval*/false, non_constant_p,
2400 overflow_p);
2401 STRIP_NOPS (fun);
2402 if (TREE_CODE (fun) == ADDR_EXPR)
2403 fun = TREE_OPERAND (fun, 0);
2404 /* For TARGET_VTABLE_USES_DESCRIPTORS targets, there is no
2405 indirection, the called expression is a pointer into the
2406 virtual table which should contain FDESC_EXPR. Extract the
2407 FUNCTION_DECL from there. */
2408 else if (TARGET_VTABLE_USES_DESCRIPTORS
2409 && TREE_CODE (fun) == POINTER_PLUS_EXPR
2410 && TREE_CODE (TREE_OPERAND (fun, 0)) == ADDR_EXPR
2411 && TREE_CODE (TREE_OPERAND (fun, 1)) == INTEGER_CST)
2413 tree d = TREE_OPERAND (TREE_OPERAND (fun, 0), 0);
2414 if (VAR_P (d)
2415 && DECL_VTABLE_OR_VTT_P (d)
2416 && TREE_CODE (TREE_TYPE (d)) == ARRAY_TYPE
2417 && TREE_TYPE (TREE_TYPE (d)) == vtable_entry_type
2418 && DECL_INITIAL (d)
2419 && TREE_CODE (DECL_INITIAL (d)) == CONSTRUCTOR)
2421 tree i = int_const_binop (TRUNC_DIV_EXPR, TREE_OPERAND (fun, 1),
2422 TYPE_SIZE_UNIT (vtable_entry_type));
2423 HOST_WIDE_INT idx = find_array_ctor_elt (DECL_INITIAL (d), i);
2424 if (idx >= 0)
2426 tree fdesc
2427 = (*CONSTRUCTOR_ELTS (DECL_INITIAL (d)))[idx].value;
2428 if (TREE_CODE (fdesc) == FDESC_EXPR
2429 && integer_zerop (TREE_OPERAND (fdesc, 1)))
2430 fun = TREE_OPERAND (fdesc, 0);
2435 if (TREE_CODE (fun) != FUNCTION_DECL)
2437 if (!ctx->quiet && !*non_constant_p)
2438 error_at (loc, "expression %qE does not designate a %<constexpr%> "
2439 "function", fun);
2440 *non_constant_p = true;
2441 return t;
2443 if (DECL_CLONED_FUNCTION_P (fun) && !DECL_DELETING_DESTRUCTOR_P (fun))
2444 fun = DECL_CLONED_FUNCTION (fun);
2446 if (is_ubsan_builtin_p (fun))
2447 return void_node;
2449 if (fndecl_built_in_p (fun))
2450 return cxx_eval_builtin_function_call (ctx, t, fun,
2451 lval, non_constant_p, overflow_p);
2452 if (DECL_THUNK_P (fun))
2453 return cxx_eval_thunk_call (ctx, t, fun, lval, non_constant_p, overflow_p);
2454 if (!maybe_constexpr_fn (fun))
2456 if (TREE_CODE (t) == CALL_EXPR
2457 && cxx_replaceable_global_alloc_fn (fun)
2458 && (CALL_FROM_NEW_OR_DELETE_P (t)
2459 || is_std_allocator_allocate (ctx->call)))
2461 const int nargs = call_expr_nargs (t);
2462 tree arg0 = NULL_TREE;
2463 for (int i = 0; i < nargs; ++i)
2465 tree arg = CALL_EXPR_ARG (t, i);
2466 arg = cxx_eval_constant_expression (ctx, arg, false,
2467 non_constant_p, overflow_p);
2468 VERIFY_CONSTANT (arg);
2469 if (i == 0)
2470 arg0 = arg;
2472 gcc_assert (arg0);
2473 if (IDENTIFIER_NEW_OP_P (DECL_NAME (fun)))
2475 tree type = build_array_type_nelts (char_type_node,
2476 tree_to_uhwi (arg0));
2477 tree var = build_decl (loc, VAR_DECL,
2478 (IDENTIFIER_OVL_OP_FLAGS (DECL_NAME (fun))
2479 & OVL_OP_FLAG_VEC)
2480 ? heap_vec_uninit_identifier
2481 : heap_uninit_identifier,
2482 type);
2483 DECL_ARTIFICIAL (var) = 1;
2484 TREE_STATIC (var) = 1;
2485 // Temporarily register the artificial var in varpool,
2486 // so that comparisons of its address against NULL are folded
2487 // through nonzero_address even with
2488 // -fno-delete-null-pointer-checks or that comparison of
2489 // addresses of different heap artificial vars is folded too.
2490 // See PR98988 and PR99031.
2491 varpool_node::finalize_decl (var);
2492 ctx->global->heap_vars.safe_push (var);
2493 ctx->global->values.put (var, NULL_TREE);
2494 return fold_convert (ptr_type_node, build_address (var));
2496 else
2498 STRIP_NOPS (arg0);
2499 if (TREE_CODE (arg0) == ADDR_EXPR
2500 && VAR_P (TREE_OPERAND (arg0, 0)))
2502 tree var = TREE_OPERAND (arg0, 0);
2503 if (DECL_NAME (var) == heap_uninit_identifier
2504 || DECL_NAME (var) == heap_identifier)
2506 if (IDENTIFIER_OVL_OP_FLAGS (DECL_NAME (fun))
2507 & OVL_OP_FLAG_VEC)
2509 if (!ctx->quiet)
2511 error_at (loc, "array deallocation of object "
2512 "allocated with non-array "
2513 "allocation");
2514 inform (DECL_SOURCE_LOCATION (var),
2515 "allocation performed here");
2517 *non_constant_p = true;
2518 return t;
2520 DECL_NAME (var) = heap_deleted_identifier;
2521 ctx->global->values.remove (var);
2522 ctx->global->heap_dealloc_count++;
2523 return void_node;
2525 else if (DECL_NAME (var) == heap_vec_uninit_identifier
2526 || DECL_NAME (var) == heap_vec_identifier)
2528 if ((IDENTIFIER_OVL_OP_FLAGS (DECL_NAME (fun))
2529 & OVL_OP_FLAG_VEC) == 0)
2531 if (!ctx->quiet)
2533 error_at (loc, "non-array deallocation of "
2534 "object allocated with array "
2535 "allocation");
2536 inform (DECL_SOURCE_LOCATION (var),
2537 "allocation performed here");
2539 *non_constant_p = true;
2540 return t;
2542 DECL_NAME (var) = heap_deleted_identifier;
2543 ctx->global->values.remove (var);
2544 ctx->global->heap_dealloc_count++;
2545 return void_node;
2547 else if (DECL_NAME (var) == heap_deleted_identifier)
2549 if (!ctx->quiet)
2550 error_at (loc, "deallocation of already deallocated "
2551 "storage");
2552 *non_constant_p = true;
2553 return t;
2556 if (!ctx->quiet)
2557 error_at (loc, "deallocation of storage that was "
2558 "not previously allocated");
2559 *non_constant_p = true;
2560 return t;
2563 /* Allow placement new in std::construct_at, just return the second
2564 argument. */
2565 if (TREE_CODE (t) == CALL_EXPR
2566 && cxx_placement_new_fn (fun)
2567 && is_std_construct_at (ctx->call))
2569 const int nargs = call_expr_nargs (t);
2570 tree arg1 = NULL_TREE;
2571 for (int i = 0; i < nargs; ++i)
2573 tree arg = CALL_EXPR_ARG (t, i);
2574 arg = cxx_eval_constant_expression (ctx, arg, false,
2575 non_constant_p, overflow_p);
2576 if (i == 1)
2577 arg1 = arg;
2578 else
2579 VERIFY_CONSTANT (arg);
2581 gcc_assert (arg1);
2582 return arg1;
2584 else if (cxx_dynamic_cast_fn_p (fun))
2585 return cxx_eval_dynamic_cast_fn (ctx, t, non_constant_p, overflow_p);
2587 if (!ctx->quiet)
2589 if (!lambda_static_thunk_p (fun))
2590 error_at (loc, "call to non-%<constexpr%> function %qD", fun);
2591 explain_invalid_constexpr_fn (fun);
2593 *non_constant_p = true;
2594 return t;
2597 constexpr_ctx new_ctx = *ctx;
2598 if (DECL_CONSTRUCTOR_P (fun) && !ctx->object
2599 && TREE_CODE (t) == AGGR_INIT_EXPR)
2601 /* We want to have an initialization target for an AGGR_INIT_EXPR.
2602 If we don't already have one in CTX, use the AGGR_INIT_EXPR_SLOT. */
2603 new_ctx.object = AGGR_INIT_EXPR_SLOT (t);
2604 tree ctor = new_ctx.ctor = build_constructor (DECL_CONTEXT (fun), NULL);
2605 CONSTRUCTOR_NO_CLEARING (ctor) = true;
2606 ctx->global->values.put (new_ctx.object, ctor);
2607 ctx = &new_ctx;
2610 /* Shortcut trivial constructor/op=. */
2611 if (trivial_fn_p (fun))
2613 tree init = NULL_TREE;
2614 if (call_expr_nargs (t) == 2)
2615 init = convert_from_reference (get_nth_callarg (t, 1));
2616 else if (TREE_CODE (t) == AGGR_INIT_EXPR
2617 && AGGR_INIT_ZERO_FIRST (t))
2618 init = build_zero_init (DECL_CONTEXT (fun), NULL_TREE, false);
2619 if (init)
2621 tree op = get_nth_callarg (t, 0);
2622 if (is_dummy_object (op))
2623 op = ctx->object;
2624 else
2625 op = build1 (INDIRECT_REF, TREE_TYPE (TREE_TYPE (op)), op);
2626 tree set = build2 (MODIFY_EXPR, TREE_TYPE (op), op, init);
2627 new_ctx.call = &new_call;
2628 return cxx_eval_constant_expression (&new_ctx, set, lval,
2629 non_constant_p, overflow_p);
2633 bool non_constant_args = false;
2634 new_call.bindings
2635 = cxx_bind_parameters_in_call (ctx, t, fun, non_constant_p,
2636 overflow_p, &non_constant_args);
2638 /* We build up the bindings list before we know whether we already have this
2639 call cached. If we don't end up saving these bindings, ggc_free them when
2640 this function exits. */
2641 class free_bindings
2643 tree *bindings;
2644 public:
2645 free_bindings (tree &b): bindings (&b) { }
2646 ~free_bindings () { if (bindings) ggc_free (*bindings); }
2647 void preserve () { bindings = NULL; }
2648 } fb (new_call.bindings);
2650 if (*non_constant_p)
2651 return t;
2653 /* We can't defer instantiating the function any longer. */
2654 if (!DECL_INITIAL (fun)
2655 && DECL_TEMPLOID_INSTANTIATION (fun)
2656 && !uid_sensitive_constexpr_evaluation_p ())
2658 location_t save_loc = input_location;
2659 input_location = loc;
2660 ++function_depth;
2661 if (ctx->manifestly_const_eval)
2662 FNDECL_MANIFESTLY_CONST_EVALUATED (fun) = true;
2663 instantiate_decl (fun, /*defer_ok*/false, /*expl_inst*/false);
2664 --function_depth;
2665 input_location = save_loc;
2668 /* If in direct recursive call, optimize definition search. */
2669 if (ctx && ctx->call && ctx->call->fundef && ctx->call->fundef->decl == fun)
2670 new_call.fundef = ctx->call->fundef;
2671 else
2673 new_call.fundef = retrieve_constexpr_fundef (fun);
2674 if (new_call.fundef == NULL || new_call.fundef->body == NULL
2675 || new_call.fundef->result == error_mark_node
2676 || fun == current_function_decl)
2678 if (!ctx->quiet)
2680 /* We need to check for current_function_decl here in case we're
2681 being called during cp_fold_function, because at that point
2682 DECL_INITIAL is set properly and we have a fundef but we
2683 haven't lowered invisirefs yet (c++/70344). */
2684 if (DECL_INITIAL (fun) == error_mark_node
2685 || fun == current_function_decl)
2686 error_at (loc, "%qD called in a constant expression before its "
2687 "definition is complete", fun);
2688 else if (DECL_INITIAL (fun))
2690 /* The definition of fun was somehow unsuitable. But pretend
2691 that lambda static thunks don't exist. */
2692 if (!lambda_static_thunk_p (fun))
2693 error_at (loc, "%qD called in a constant expression", fun);
2694 explain_invalid_constexpr_fn (fun);
2696 else
2697 error_at (loc, "%qD used before its definition", fun);
2699 *non_constant_p = true;
2700 return t;
2704 depth_ok = push_cx_call_context (t);
2706 /* Remember the object we are constructing or destructing. */
2707 tree new_obj = NULL_TREE;
2708 if (DECL_CONSTRUCTOR_P (fun) || DECL_DESTRUCTOR_P (fun))
2710 /* In a cdtor, it should be the first `this' argument.
2711 At this point it has already been evaluated in the call
2712 to cxx_bind_parameters_in_call. */
2713 new_obj = TREE_VEC_ELT (new_call.bindings, 0);
2714 STRIP_NOPS (new_obj);
2715 if (TREE_CODE (new_obj) == ADDR_EXPR)
2716 new_obj = TREE_OPERAND (new_obj, 0);
2718 if (ctx->call && ctx->call->fundef
2719 && DECL_CONSTRUCTOR_P (ctx->call->fundef->decl))
2721 tree cur_obj = TREE_VEC_ELT (ctx->call->bindings, 0);
2722 STRIP_NOPS (cur_obj);
2723 if (TREE_CODE (cur_obj) == ADDR_EXPR)
2724 cur_obj = TREE_OPERAND (cur_obj, 0);
2725 if (new_obj == cur_obj)
2726 /* We're calling the target constructor of a delegating
2727 constructor, or accessing a base subobject through a
2728 NOP_EXPR as part of a call to a base constructor, so
2729 there is no new (sub)object. */
2730 new_obj = NULL_TREE;
2734 tree result = NULL_TREE;
2736 constexpr_call *entry = NULL;
2737 if (depth_ok && !non_constant_args && ctx->strict)
2739 new_call.hash = constexpr_fundef_hasher::hash (new_call.fundef);
2740 new_call.hash
2741 = iterative_hash_template_arg (new_call.bindings, new_call.hash);
2742 new_call.hash
2743 = iterative_hash_object (ctx->manifestly_const_eval, new_call.hash);
2745 /* If we have seen this call before, we are done. */
2746 maybe_initialize_constexpr_call_table ();
2747 constexpr_call **slot
2748 = constexpr_call_table->find_slot (&new_call, INSERT);
2749 entry = *slot;
2750 if (entry == NULL)
2752 /* Only cache up to constexpr_cache_depth to limit memory use. */
2753 if (depth_ok < constexpr_cache_depth)
2755 /* We need to keep a pointer to the entry, not just the slot, as
2756 the slot can move during evaluation of the body. */
2757 *slot = entry = ggc_alloc<constexpr_call> ();
2758 *entry = new_call;
2759 fb.preserve ();
2762 /* Calls that are in progress have their result set to NULL, so that we
2763 can detect circular dependencies. Now that we only cache up to
2764 constexpr_cache_depth this won't catch circular dependencies that
2765 start deeper, but they'll hit the recursion or ops limit. */
2766 else if (entry->result == NULL)
2768 if (!ctx->quiet)
2769 error ("call has circular dependency");
2770 *non_constant_p = true;
2771 entry->result = result = error_mark_node;
2773 else
2774 result = entry->result;
2777 if (!depth_ok)
2779 if (!ctx->quiet)
2780 error ("%<constexpr%> evaluation depth exceeds maximum of %d (use "
2781 "%<-fconstexpr-depth=%> to increase the maximum)",
2782 max_constexpr_depth);
2783 *non_constant_p = true;
2784 result = error_mark_node;
2786 else
2788 bool cacheable = true;
2789 if (result && result != error_mark_node)
2790 /* OK */;
2791 else if (!DECL_SAVED_TREE (fun))
2793 /* When at_eof >= 2, cgraph has started throwing away
2794 DECL_SAVED_TREE, so fail quietly. FIXME we get here because of
2795 late code generation for VEC_INIT_EXPR, which needs to be
2796 completely reconsidered. */
2797 gcc_assert (at_eof >= 2 && ctx->quiet);
2798 *non_constant_p = true;
2800 else if (tree copy = get_fundef_copy (new_call.fundef))
2802 tree body, parms, res;
2803 releasing_vec ctors;
2805 /* Reuse or create a new unshared copy of this function's body. */
2806 body = TREE_PURPOSE (copy);
2807 parms = TREE_VALUE (copy);
2808 res = TREE_TYPE (copy);
2810 /* Associate the bindings with the remapped parms. */
2811 tree bound = new_call.bindings;
2812 tree remapped = parms;
2813 for (int i = 0; i < TREE_VEC_LENGTH (bound); ++i)
2815 tree arg = TREE_VEC_ELT (bound, i);
2816 if (entry)
2818 /* Unshare args going into the hash table to separate them
2819 from the caller's context, for better GC and to avoid
2820 problems with verify_gimple. */
2821 arg = unshare_expr_without_location (arg);
2822 TREE_VEC_ELT (bound, i) = arg;
2824 /* And then unshare again so the callee doesn't change the
2825 argument values in the hash table. XXX Could we unshare
2826 lazily in cxx_eval_store_expression? */
2827 arg = unshare_constructor (arg);
2828 if (TREE_CODE (arg) == CONSTRUCTOR)
2829 vec_safe_push (ctors, arg);
2831 ctx->global->values.put (remapped, arg);
2832 remapped = DECL_CHAIN (remapped);
2834 /* Add the RESULT_DECL to the values map, too. */
2835 gcc_assert (!DECL_BY_REFERENCE (res));
2836 ctx->global->values.put (res, NULL_TREE);
2838 /* Track the callee's evaluated SAVE_EXPRs and TARGET_EXPRs so that
2839 we can forget their values after the call. */
2840 constexpr_ctx ctx_with_save_exprs = *ctx;
2841 auto_vec<tree, 10> save_exprs;
2842 ctx_with_save_exprs.save_exprs = &save_exprs;
2843 ctx_with_save_exprs.call = &new_call;
2844 unsigned save_heap_alloc_count = ctx->global->heap_vars.length ();
2845 unsigned save_heap_dealloc_count = ctx->global->heap_dealloc_count;
2847 /* If this is a constexpr destructor, the object's const and volatile
2848 semantics are no longer in effect; see [class.dtor]p5. */
2849 if (new_obj && DECL_DESTRUCTOR_P (fun))
2850 cxx_set_object_constness (ctx, new_obj, /*readonly_p=*/false,
2851 non_constant_p, overflow_p);
2853 tree jump_target = NULL_TREE;
2854 cxx_eval_constant_expression (&ctx_with_save_exprs, body,
2855 lval, non_constant_p, overflow_p,
2856 &jump_target);
2858 if (DECL_CONSTRUCTOR_P (fun))
2860 /* This can be null for a subobject constructor call, in
2861 which case what we care about is the initialization
2862 side-effects rather than the value. We could get at the
2863 value by evaluating *this, but we don't bother; there's
2864 no need to put such a call in the hash table. */
2865 result = lval ? ctx->object : ctx->ctor;
2867 /* If we've just evaluated a subobject constructor call for an
2868 empty union member, it might not have produced a side effect
2869 that actually activated the union member. So produce such a
2870 side effect now to ensure the union appears initialized. */
2871 if (!result && new_obj
2872 && TREE_CODE (new_obj) == COMPONENT_REF
2873 && TREE_CODE (TREE_TYPE
2874 (TREE_OPERAND (new_obj, 0))) == UNION_TYPE
2875 && is_really_empty_class (TREE_TYPE (new_obj),
2876 /*ignore_vptr*/false))
2878 tree activate = build2 (MODIFY_EXPR, TREE_TYPE (new_obj),
2879 new_obj,
2880 build_constructor (TREE_TYPE (new_obj),
2881 NULL));
2882 cxx_eval_constant_expression (ctx, activate, lval,
2883 non_constant_p, overflow_p);
2884 ggc_free (activate);
2887 else if (VOID_TYPE_P (TREE_TYPE (res)))
2888 result = void_node;
2889 else
2891 result = *ctx->global->values.get (res);
2892 if (result == NULL_TREE && !*non_constant_p
2893 && !DECL_DESTRUCTOR_P (fun))
2895 if (!ctx->quiet)
2896 error ("%<constexpr%> call flows off the end "
2897 "of the function");
2898 *non_constant_p = true;
2902 /* At this point, the object's constructor will have run, so
2903 the object is no longer under construction, and its possible
2904 'const' semantics now apply. Make a note of this fact by
2905 marking the CONSTRUCTOR TREE_READONLY. */
2906 if (new_obj && DECL_CONSTRUCTOR_P (fun))
2907 cxx_set_object_constness (ctx, new_obj, /*readonly_p=*/true,
2908 non_constant_p, overflow_p);
2910 /* Forget the saved values of the callee's SAVE_EXPRs and
2911 TARGET_EXPRs. */
2912 for (tree save_expr : save_exprs)
2913 ctx->global->values.remove (save_expr);
2915 /* Remove the parms/result from the values map. Is it worth
2916 bothering to do this when the map itself is only live for
2917 one constexpr evaluation? If so, maybe also clear out
2918 other vars from call, maybe in BIND_EXPR handling? */
2919 ctx->global->values.remove (res);
2920 for (tree parm = parms; parm; parm = TREE_CHAIN (parm))
2921 ctx->global->values.remove (parm);
2923 /* Free any parameter CONSTRUCTORs we aren't returning directly. */
2924 while (!ctors->is_empty ())
2926 tree c = ctors->pop ();
2927 if (c != result)
2928 free_constructor (c);
2931 /* Make the unshared function copy we used available for re-use. */
2932 save_fundef_copy (fun, copy);
2934 /* If the call allocated some heap object that hasn't been
2935 deallocated during the call, or if it deallocated some heap
2936 object it has not allocated, the call isn't really stateless
2937 for the constexpr evaluation and should not be cached.
2938 It is fine if the call allocates something and deallocates it
2939 too. */
2940 if (entry
2941 && (save_heap_alloc_count != ctx->global->heap_vars.length ()
2942 || (save_heap_dealloc_count
2943 != ctx->global->heap_dealloc_count)))
2945 tree heap_var;
2946 unsigned int i;
2947 if ((ctx->global->heap_vars.length ()
2948 - ctx->global->heap_dealloc_count)
2949 != save_heap_alloc_count - save_heap_dealloc_count)
2950 cacheable = false;
2951 else
2952 FOR_EACH_VEC_ELT_FROM (ctx->global->heap_vars, i, heap_var,
2953 save_heap_alloc_count)
2954 if (DECL_NAME (heap_var) != heap_deleted_identifier)
2956 cacheable = false;
2957 break;
2961 /* Rewrite all occurrences of the function's RESULT_DECL with the
2962 current object under construction. */
2963 if (!*non_constant_p && ctx->object
2964 && CLASS_TYPE_P (TREE_TYPE (res))
2965 && !is_empty_class (TREE_TYPE (res)))
2966 if (replace_decl (&result, res, ctx->object))
2967 cacheable = false;
2969 else
2970 /* Couldn't get a function copy to evaluate. */
2971 *non_constant_p = true;
2973 if (result == error_mark_node)
2974 *non_constant_p = true;
2975 if (*non_constant_p || *overflow_p)
2976 result = error_mark_node;
2977 else if (!result)
2978 result = void_node;
2979 if (entry)
2980 entry->result = cacheable ? result : error_mark_node;
2983 /* The result of a constexpr function must be completely initialized.
2985 However, in C++20, a constexpr constructor doesn't necessarily have
2986 to initialize all the fields, so we don't clear CONSTRUCTOR_NO_CLEARING
2987 in order to detect reading an unitialized object in constexpr instead
2988 of value-initializing it. (reduced_constant_expression_p is expected to
2989 take care of clearing the flag.) */
2990 if (TREE_CODE (result) == CONSTRUCTOR
2991 && (cxx_dialect < cxx20
2992 || !DECL_CONSTRUCTOR_P (fun)))
2993 clear_no_implicit_zero (result);
2995 pop_cx_call_context ();
2996 return result;
2999 /* Return true if T is a valid constant initializer. If a CONSTRUCTOR
3000 initializes all the members, the CONSTRUCTOR_NO_CLEARING flag will be
3001 cleared.
3002 FIXME speed this up, it's taking 16% of compile time on sieve testcase. */
3004 bool
3005 reduced_constant_expression_p (tree t)
3007 if (t == NULL_TREE)
3008 return false;
3010 switch (TREE_CODE (t))
3012 case PTRMEM_CST:
3013 /* Even if we can't lower this yet, it's constant. */
3014 return true;
3016 case CONSTRUCTOR:
3017 /* And we need to handle PTRMEM_CST wrapped in a CONSTRUCTOR. */
3018 tree field;
3019 if (CONSTRUCTOR_NO_CLEARING (t))
3021 if (TREE_CODE (TREE_TYPE (t)) == VECTOR_TYPE)
3022 /* An initialized vector would have a VECTOR_CST. */
3023 return false;
3024 else if (TREE_CODE (TREE_TYPE (t)) == ARRAY_TYPE)
3026 /* There must be a valid constant initializer at every array
3027 index. */
3028 tree min = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (t)));
3029 tree max = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (t)));
3030 tree cursor = min;
3031 for (auto &e: CONSTRUCTOR_ELTS (t))
3033 if (!reduced_constant_expression_p (e.value))
3034 return false;
3035 if (array_index_cmp (cursor, e.index) != 0)
3036 return false;
3037 if (TREE_CODE (e.index) == RANGE_EXPR)
3038 cursor = TREE_OPERAND (e.index, 1);
3039 cursor = int_const_binop (PLUS_EXPR, cursor, size_one_node);
3041 if (find_array_ctor_elt (t, max) == -1)
3042 return false;
3043 goto ok;
3045 else if (cxx_dialect >= cxx20
3046 && TREE_CODE (TREE_TYPE (t)) == UNION_TYPE)
3048 if (CONSTRUCTOR_NELTS (t) == 0)
3049 /* An initialized union has a constructor element. */
3050 return false;
3051 /* And it only initializes one member. */
3052 field = NULL_TREE;
3054 else
3055 field = next_subobject_field (TYPE_FIELDS (TREE_TYPE (t)));
3057 else
3058 field = NULL_TREE;
3059 for (auto &e: CONSTRUCTOR_ELTS (t))
3061 /* If VAL is null, we're in the middle of initializing this
3062 element. */
3063 if (!reduced_constant_expression_p (e.value))
3064 return false;
3065 /* Empty class field may or may not have an initializer. */
3066 for (; field && e.index != field;
3067 field = next_subobject_field (DECL_CHAIN (field)))
3068 if (!is_really_empty_class (TREE_TYPE (field),
3069 /*ignore_vptr*/false))
3070 return false;
3071 if (field)
3072 field = next_subobject_field (DECL_CHAIN (field));
3074 /* There could be a non-empty field at the end. */
3075 for (; field; field = next_subobject_field (DECL_CHAIN (field)))
3076 if (!is_really_empty_class (TREE_TYPE (field), /*ignore_vptr*/false))
3077 return false;
3079 if (CONSTRUCTOR_NO_CLEARING (t))
3080 /* All the fields are initialized. */
3081 CONSTRUCTOR_NO_CLEARING (t) = false;
3082 return true;
3084 default:
3085 /* FIXME are we calling this too much? */
3086 return initializer_constant_valid_p (t, TREE_TYPE (t)) != NULL_TREE;
3090 /* Some expressions may have constant operands but are not constant
3091 themselves, such as 1/0. Call this function to check for that
3092 condition.
3094 We only call this in places that require an arithmetic constant, not in
3095 places where we might have a non-constant expression that can be a
3096 component of a constant expression, such as the address of a constexpr
3097 variable that might be dereferenced later. */
3099 static bool
3100 verify_constant (tree t, bool allow_non_constant, bool *non_constant_p,
3101 bool *overflow_p)
3103 if (!*non_constant_p && !reduced_constant_expression_p (t)
3104 && t != void_node)
3106 if (!allow_non_constant)
3107 error ("%q+E is not a constant expression", t);
3108 *non_constant_p = true;
3110 if (TREE_OVERFLOW_P (t))
3112 if (!allow_non_constant)
3114 permerror (input_location, "overflow in constant expression");
3115 /* If we're being permissive (and are in an enforcing
3116 context), ignore the overflow. */
3117 if (flag_permissive)
3118 return *non_constant_p;
3120 *overflow_p = true;
3122 return *non_constant_p;
3125 /* Check whether the shift operation with code CODE and type TYPE on LHS
3126 and RHS is undefined. If it is, give an error with an explanation,
3127 and return true; return false otherwise. */
3129 static bool
3130 cxx_eval_check_shift_p (location_t loc, const constexpr_ctx *ctx,
3131 enum tree_code code, tree type, tree lhs, tree rhs)
3133 if ((code != LSHIFT_EXPR && code != RSHIFT_EXPR)
3134 || TREE_CODE (lhs) != INTEGER_CST
3135 || TREE_CODE (rhs) != INTEGER_CST)
3136 return false;
3138 tree lhstype = TREE_TYPE (lhs);
3139 unsigned HOST_WIDE_INT uprec = TYPE_PRECISION (TREE_TYPE (lhs));
3141 /* [expr.shift] The behavior is undefined if the right operand
3142 is negative, or greater than or equal to the length in bits
3143 of the promoted left operand. */
3144 if (tree_int_cst_sgn (rhs) == -1)
3146 if (!ctx->quiet)
3147 permerror (loc, "right operand of shift expression %q+E is negative",
3148 build2_loc (loc, code, type, lhs, rhs));
3149 return (!flag_permissive || ctx->quiet);
3151 if (compare_tree_int (rhs, uprec) >= 0)
3153 if (!ctx->quiet)
3154 permerror (loc, "right operand of shift expression %q+E is greater "
3155 "than or equal to the precision %wu of the left operand",
3156 build2_loc (loc, code, type, lhs, rhs), uprec);
3157 return (!flag_permissive || ctx->quiet);
3160 /* The value of E1 << E2 is E1 left-shifted E2 bit positions; [...]
3161 if E1 has a signed type and non-negative value, and E1x2^E2 is
3162 representable in the corresponding unsigned type of the result type,
3163 then that value, converted to the result type, is the resulting value;
3164 otherwise, the behavior is undefined.
3165 For C++20:
3166 The value of E1 << E2 is the unique value congruent to E1 x 2^E2 modulo
3167 2^N, where N is the range exponent of the type of the result. */
3168 if (code == LSHIFT_EXPR
3169 && !TYPE_OVERFLOW_WRAPS (lhstype)
3170 && cxx_dialect >= cxx11
3171 && cxx_dialect < cxx20)
3173 if (tree_int_cst_sgn (lhs) == -1)
3175 if (!ctx->quiet)
3176 permerror (loc,
3177 "left operand of shift expression %q+E is negative",
3178 build2_loc (loc, code, type, lhs, rhs));
3179 return (!flag_permissive || ctx->quiet);
3181 /* For signed x << y the following:
3182 (unsigned) x >> ((prec (lhs) - 1) - y)
3183 if > 1, is undefined. The right-hand side of this formula
3184 is the highest bit of the LHS that can be set (starting from 0),
3185 so that the shift doesn't overflow. We then right-shift the LHS
3186 to see whether any other bit is set making the original shift
3187 undefined -- the result is not representable in the corresponding
3188 unsigned type. */
3189 tree t = build_int_cst (unsigned_type_node, uprec - 1);
3190 t = fold_build2 (MINUS_EXPR, unsigned_type_node, t, rhs);
3191 tree ulhs = fold_convert (unsigned_type_for (lhstype), lhs);
3192 t = fold_build2 (RSHIFT_EXPR, TREE_TYPE (ulhs), ulhs, t);
3193 if (tree_int_cst_lt (integer_one_node, t))
3195 if (!ctx->quiet)
3196 permerror (loc, "shift expression %q+E overflows",
3197 build2_loc (loc, code, type, lhs, rhs));
3198 return (!flag_permissive || ctx->quiet);
3201 return false;
3204 /* Subroutine of cxx_eval_constant_expression.
3205 Attempt to reduce the unary expression tree T to a compile time value.
3206 If successful, return the value. Otherwise issue a diagnostic
3207 and return error_mark_node. */
3209 static tree
3210 cxx_eval_unary_expression (const constexpr_ctx *ctx, tree t,
3211 bool /*lval*/,
3212 bool *non_constant_p, bool *overflow_p)
3214 tree r;
3215 tree orig_arg = TREE_OPERAND (t, 0);
3216 tree arg = cxx_eval_constant_expression (ctx, orig_arg, /*lval*/false,
3217 non_constant_p, overflow_p);
3218 VERIFY_CONSTANT (arg);
3219 location_t loc = EXPR_LOCATION (t);
3220 enum tree_code code = TREE_CODE (t);
3221 tree type = TREE_TYPE (t);
3222 r = fold_unary_loc (loc, code, type, arg);
3223 if (r == NULL_TREE)
3225 if (arg == orig_arg)
3226 r = t;
3227 else
3228 r = build1_loc (loc, code, type, arg);
3230 VERIFY_CONSTANT (r);
3231 return r;
3234 /* Helper function for cxx_eval_binary_expression. Try to optimize
3235 original POINTER_PLUS_EXPR T, LHS p+ RHS, return NULL_TREE if the
3236 generic folding should be used. */
3238 static tree
3239 cxx_fold_pointer_plus_expression (const constexpr_ctx *ctx, tree t,
3240 tree lhs, tree rhs, bool *non_constant_p,
3241 bool *overflow_p)
3243 STRIP_NOPS (lhs);
3244 if (TREE_CODE (lhs) != ADDR_EXPR)
3245 return NULL_TREE;
3247 lhs = TREE_OPERAND (lhs, 0);
3249 /* &A[i] p+ j => &A[i + j] */
3250 if (TREE_CODE (lhs) == ARRAY_REF
3251 && TREE_CODE (TREE_OPERAND (lhs, 1)) == INTEGER_CST
3252 && TREE_CODE (rhs) == INTEGER_CST
3253 && TYPE_SIZE_UNIT (TREE_TYPE (lhs))
3254 && TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (lhs))) == INTEGER_CST)
3256 tree orig_type = TREE_TYPE (t);
3257 location_t loc = EXPR_LOCATION (t);
3258 tree type = TREE_TYPE (lhs);
3260 t = fold_convert_loc (loc, ssizetype, TREE_OPERAND (lhs, 1));
3261 tree nelts = array_type_nelts_top (TREE_TYPE (TREE_OPERAND (lhs, 0)));
3262 nelts = cxx_eval_constant_expression (ctx, nelts, false, non_constant_p,
3263 overflow_p);
3264 if (*non_constant_p)
3265 return NULL_TREE;
3266 /* Don't fold an out-of-bound access. */
3267 if (!tree_int_cst_le (t, nelts))
3268 return NULL_TREE;
3269 rhs = cp_fold_convert (ssizetype, rhs);
3270 /* Don't fold if rhs can't be divided exactly by TYPE_SIZE_UNIT.
3271 constexpr int A[1]; ... (char *)&A[0] + 1 */
3272 if (!integer_zerop (fold_build2_loc (loc, TRUNC_MOD_EXPR, sizetype,
3273 rhs, TYPE_SIZE_UNIT (type))))
3274 return NULL_TREE;
3275 /* Make sure to treat the second operand of POINTER_PLUS_EXPR
3276 as signed. */
3277 rhs = fold_build2_loc (loc, EXACT_DIV_EXPR, ssizetype, rhs,
3278 TYPE_SIZE_UNIT (type));
3279 t = size_binop_loc (loc, PLUS_EXPR, rhs, t);
3280 t = build4_loc (loc, ARRAY_REF, type, TREE_OPERAND (lhs, 0),
3281 t, NULL_TREE, NULL_TREE);
3282 t = cp_build_addr_expr (t, tf_warning_or_error);
3283 t = cp_fold_convert (orig_type, t);
3284 return cxx_eval_constant_expression (ctx, t, /*lval*/false,
3285 non_constant_p, overflow_p);
3288 return NULL_TREE;
3291 /* Try to fold expressions like
3292 (struct S *) (&a[0].D.2378 + 12)
3293 into
3294 &MEM <struct T> [(void *)&a + 12B]
3295 This is something normally done by gimple_fold_stmt_to_constant_1
3296 on GIMPLE, but is undesirable on GENERIC if we are e.g. going to
3297 dereference the address because some details are lost.
3298 For pointer comparisons we want such folding though so that
3299 match.pd address_compare optimization works. */
3301 static tree
3302 cxx_maybe_fold_addr_pointer_plus (tree t)
3304 while (CONVERT_EXPR_P (t)
3305 && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (t, 0))))
3306 t = TREE_OPERAND (t, 0);
3307 if (TREE_CODE (t) != POINTER_PLUS_EXPR)
3308 return NULL_TREE;
3309 tree op0 = TREE_OPERAND (t, 0);
3310 tree op1 = TREE_OPERAND (t, 1);
3311 if (TREE_CODE (op1) != INTEGER_CST)
3312 return NULL_TREE;
3313 while (CONVERT_EXPR_P (op0)
3314 && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (op0, 0))))
3315 op0 = TREE_OPERAND (op0, 0);
3316 if (TREE_CODE (op0) != ADDR_EXPR)
3317 return NULL_TREE;
3318 op1 = fold_convert (ptr_type_node, op1);
3319 tree r = fold_build2 (MEM_REF, TREE_TYPE (TREE_TYPE (op0)), op0, op1);
3320 return build1_loc (EXPR_LOCATION (t), ADDR_EXPR, TREE_TYPE (op0), r);
3323 /* Subroutine of cxx_eval_constant_expression.
3324 Like cxx_eval_unary_expression, except for binary expressions. */
3326 static tree
3327 cxx_eval_binary_expression (const constexpr_ctx *ctx, tree t,
3328 bool lval,
3329 bool *non_constant_p, bool *overflow_p)
3331 tree r = NULL_TREE;
3332 tree orig_lhs = TREE_OPERAND (t, 0);
3333 tree orig_rhs = TREE_OPERAND (t, 1);
3334 tree lhs, rhs;
3335 lhs = cxx_eval_constant_expression (ctx, orig_lhs, /*lval*/false,
3336 non_constant_p, overflow_p);
3337 /* Don't VERIFY_CONSTANT here, it's unnecessary and will break pointer
3338 subtraction. */
3339 if (*non_constant_p)
3340 return t;
3341 rhs = cxx_eval_constant_expression (ctx, orig_rhs, /*lval*/false,
3342 non_constant_p, overflow_p);
3343 if (*non_constant_p)
3344 return t;
3346 location_t loc = EXPR_LOCATION (t);
3347 enum tree_code code = TREE_CODE (t);
3348 tree type = TREE_TYPE (t);
3350 if (code == EQ_EXPR || code == NE_EXPR)
3352 bool is_code_eq = (code == EQ_EXPR);
3354 if (TREE_CODE (lhs) == PTRMEM_CST
3355 && TREE_CODE (rhs) == PTRMEM_CST)
3357 tree lmem = PTRMEM_CST_MEMBER (lhs);
3358 tree rmem = PTRMEM_CST_MEMBER (rhs);
3359 bool eq;
3360 if (TREE_CODE (lmem) == TREE_CODE (rmem)
3361 && TREE_CODE (lmem) == FIELD_DECL
3362 && TREE_CODE (DECL_CONTEXT (lmem)) == UNION_TYPE
3363 && same_type_p (DECL_CONTEXT (lmem),
3364 DECL_CONTEXT (rmem)))
3365 /* If both refer to (possibly different) members of the same union
3366 (12.3), they compare equal. */
3367 eq = true;
3368 else
3369 eq = cp_tree_equal (lhs, rhs);
3370 r = constant_boolean_node (eq == is_code_eq, type);
3372 else if ((TREE_CODE (lhs) == PTRMEM_CST
3373 || TREE_CODE (rhs) == PTRMEM_CST)
3374 && (null_member_pointer_value_p (lhs)
3375 || null_member_pointer_value_p (rhs)))
3376 r = constant_boolean_node (!is_code_eq, type);
3377 else if (TREE_CODE (lhs) == PTRMEM_CST)
3378 lhs = cplus_expand_constant (lhs);
3379 else if (TREE_CODE (rhs) == PTRMEM_CST)
3380 rhs = cplus_expand_constant (rhs);
3382 if (r == NULL_TREE
3383 && TREE_CODE_CLASS (code) == tcc_comparison
3384 && POINTER_TYPE_P (TREE_TYPE (lhs)))
3386 if (tree lhso = cxx_maybe_fold_addr_pointer_plus (lhs))
3387 lhs = fold_convert (TREE_TYPE (lhs), lhso);
3388 if (tree rhso = cxx_maybe_fold_addr_pointer_plus (rhs))
3389 rhs = fold_convert (TREE_TYPE (rhs), rhso);
3391 if (code == POINTER_PLUS_EXPR && !*non_constant_p
3392 && integer_zerop (lhs) && !integer_zerop (rhs))
3394 if (!ctx->quiet)
3395 error ("arithmetic involving a null pointer in %qE", lhs);
3396 *non_constant_p = true;
3397 return t;
3399 else if (code == POINTER_PLUS_EXPR)
3400 r = cxx_fold_pointer_plus_expression (ctx, t, lhs, rhs, non_constant_p,
3401 overflow_p);
3402 else if (code == SPACESHIP_EXPR)
3404 r = genericize_spaceship (loc, type, lhs, rhs);
3405 return cxx_eval_constant_expression (ctx, r, lval, non_constant_p,
3406 overflow_p);
3409 if (r == NULL_TREE)
3411 if (ctx->manifestly_const_eval
3412 && (flag_constexpr_fp_except
3413 || TREE_CODE (type) != REAL_TYPE))
3415 auto ofcc = make_temp_override (folding_cxx_constexpr, true);
3416 r = fold_binary_initializer_loc (loc, code, type, lhs, rhs);
3418 else
3419 r = fold_binary_loc (loc, code, type, lhs, rhs);
3422 if (r == NULL_TREE
3423 && (code == LSHIFT_EXPR || code == RSHIFT_EXPR)
3424 && TREE_CODE (lhs) == INTEGER_CST
3425 && TREE_CODE (rhs) == INTEGER_CST
3426 && wi::neg_p (wi::to_wide (rhs)))
3428 /* For diagnostics and -fpermissive emulate previous behavior of
3429 handling shifts by negative amount. */
3430 tree nrhs = const_unop (NEGATE_EXPR, TREE_TYPE (rhs), rhs);
3431 if (nrhs)
3432 r = fold_binary_loc (loc,
3433 code == LSHIFT_EXPR ? RSHIFT_EXPR : LSHIFT_EXPR,
3434 type, lhs, nrhs);
3437 if (r == NULL_TREE)
3439 if (lhs == orig_lhs && rhs == orig_rhs)
3440 r = t;
3441 else
3442 r = build2_loc (loc, code, type, lhs, rhs);
3444 else if (cxx_eval_check_shift_p (loc, ctx, code, type, lhs, rhs))
3445 *non_constant_p = true;
3446 /* Don't VERIFY_CONSTANT if this might be dealing with a pointer to
3447 a local array in a constexpr function. */
3448 bool ptr = INDIRECT_TYPE_P (TREE_TYPE (lhs));
3449 if (!ptr)
3450 VERIFY_CONSTANT (r);
3451 return r;
3454 /* Subroutine of cxx_eval_constant_expression.
3455 Attempt to evaluate condition expressions. Dead branches are not
3456 looked into. */
3458 static tree
3459 cxx_eval_conditional_expression (const constexpr_ctx *ctx, tree t,
3460 bool lval,
3461 bool *non_constant_p, bool *overflow_p,
3462 tree *jump_target)
3464 tree val = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
3465 /*lval*/false,
3466 non_constant_p, overflow_p);
3467 VERIFY_CONSTANT (val);
3468 if (TREE_CODE (t) == IF_STMT && IF_STMT_CONSTEVAL_P (t))
3470 /* Evaluate the condition as if it was
3471 if (__builtin_is_constant_evaluated ()), i.e. defer it if not
3472 ctx->manifestly_const_eval (as sometimes we try to constant evaluate
3473 without manifestly_const_eval even expressions or parts thereof which
3474 will later be manifestly const_eval evaluated), otherwise fold it to
3475 true. */
3476 if (ctx->manifestly_const_eval)
3477 val = boolean_true_node;
3478 else
3480 *non_constant_p = true;
3481 return t;
3484 /* Don't VERIFY_CONSTANT the other operands. */
3485 if (integer_zerop (val))
3486 val = TREE_OPERAND (t, 2);
3487 else
3488 val = TREE_OPERAND (t, 1);
3489 if (TREE_CODE (t) == IF_STMT && !val)
3490 val = void_node;
3491 return cxx_eval_constant_expression (ctx, val, lval, non_constant_p,
3492 overflow_p, jump_target);
3495 /* Subroutine of cxx_eval_constant_expression.
3496 Attempt to evaluate vector condition expressions. Unlike
3497 cxx_eval_conditional_expression, VEC_COND_EXPR acts like a normal
3498 ternary arithmetics operation, where all 3 arguments have to be
3499 evaluated as constants and then folding computes the result from
3500 them. */
3502 static tree
3503 cxx_eval_vector_conditional_expression (const constexpr_ctx *ctx, tree t,
3504 bool *non_constant_p, bool *overflow_p)
3506 tree arg1 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
3507 /*lval*/false,
3508 non_constant_p, overflow_p);
3509 VERIFY_CONSTANT (arg1);
3510 tree arg2 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
3511 /*lval*/false,
3512 non_constant_p, overflow_p);
3513 VERIFY_CONSTANT (arg2);
3514 tree arg3 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 2),
3515 /*lval*/false,
3516 non_constant_p, overflow_p);
3517 VERIFY_CONSTANT (arg3);
3518 location_t loc = EXPR_LOCATION (t);
3519 tree type = TREE_TYPE (t);
3520 tree r = fold_ternary_loc (loc, VEC_COND_EXPR, type, arg1, arg2, arg3);
3521 if (r == NULL_TREE)
3523 if (arg1 == TREE_OPERAND (t, 0)
3524 && arg2 == TREE_OPERAND (t, 1)
3525 && arg3 == TREE_OPERAND (t, 2))
3526 r = t;
3527 else
3528 r = build3_loc (loc, VEC_COND_EXPR, type, arg1, arg2, arg3);
3530 VERIFY_CONSTANT (r);
3531 return r;
3534 /* Returns less than, equal to, or greater than zero if KEY is found to be
3535 less than, to match, or to be greater than the constructor_elt's INDEX. */
3537 static int
3538 array_index_cmp (tree key, tree index)
3540 gcc_assert (TREE_CODE (key) == INTEGER_CST);
3542 switch (TREE_CODE (index))
3544 case INTEGER_CST:
3545 return tree_int_cst_compare (key, index);
3546 case RANGE_EXPR:
3548 tree lo = TREE_OPERAND (index, 0);
3549 tree hi = TREE_OPERAND (index, 1);
3550 if (tree_int_cst_lt (key, lo))
3551 return -1;
3552 else if (tree_int_cst_lt (hi, key))
3553 return 1;
3554 else
3555 return 0;
3557 default:
3558 gcc_unreachable ();
3562 /* Returns the index of the constructor_elt of ARY which matches DINDEX, or -1
3563 if none. If INSERT is true, insert a matching element rather than fail. */
3565 static HOST_WIDE_INT
3566 find_array_ctor_elt (tree ary, tree dindex, bool insert)
3568 if (tree_int_cst_sgn (dindex) < 0)
3569 return -1;
3571 unsigned HOST_WIDE_INT i = tree_to_uhwi (dindex);
3572 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ary);
3573 unsigned HOST_WIDE_INT len = vec_safe_length (elts);
3575 unsigned HOST_WIDE_INT end = len;
3576 unsigned HOST_WIDE_INT begin = 0;
3578 /* If the last element of the CONSTRUCTOR has its own index, we can assume
3579 that the same is true of the other elements and index directly. */
3580 if (end > 0)
3582 tree cindex = (*elts)[end - 1].index;
3583 if (cindex == NULL_TREE)
3585 /* Verify that if the last index is missing, all indexes
3586 are missing. */
3587 if (flag_checking)
3588 for (unsigned int j = 0; j < len - 1; ++j)
3589 gcc_assert ((*elts)[j].index == NULL_TREE);
3590 if (i < end)
3591 return i;
3592 else
3594 begin = end;
3595 if (i == end)
3596 /* If the element is to be added right at the end,
3597 make sure it is added with cleared index too. */
3598 dindex = NULL_TREE;
3599 else if (insert)
3600 /* Otherwise, in order not to break the assumption
3601 that CONSTRUCTOR either has all indexes or none,
3602 we need to add indexes to all elements. */
3603 for (unsigned int j = 0; j < len; ++j)
3604 (*elts)[j].index = build_int_cst (TREE_TYPE (dindex), j);
3607 else if (TREE_CODE (cindex) == INTEGER_CST
3608 && compare_tree_int (cindex, end - 1) == 0)
3610 if (i < end)
3611 return i;
3612 else
3613 begin = end;
3617 /* Otherwise, find a matching index by means of a binary search. */
3618 while (begin != end)
3620 unsigned HOST_WIDE_INT middle = (begin + end) / 2;
3621 constructor_elt &elt = (*elts)[middle];
3622 tree idx = elt.index;
3624 int cmp = array_index_cmp (dindex, idx);
3625 if (cmp < 0)
3626 end = middle;
3627 else if (cmp > 0)
3628 begin = middle + 1;
3629 else
3631 if (insert && TREE_CODE (idx) == RANGE_EXPR)
3633 /* We need to split the range. */
3634 constructor_elt e;
3635 tree lo = TREE_OPERAND (idx, 0);
3636 tree hi = TREE_OPERAND (idx, 1);
3637 tree value = elt.value;
3638 dindex = fold_convert (sizetype, dindex);
3639 if (tree_int_cst_lt (lo, dindex))
3641 /* There are still some lower elts; shorten the range. */
3642 tree new_hi = int_const_binop (MINUS_EXPR, dindex,
3643 size_one_node);
3644 if (tree_int_cst_equal (lo, new_hi))
3645 /* Only one element left, no longer a range. */
3646 elt.index = lo;
3647 else
3648 TREE_OPERAND (idx, 1) = new_hi;
3649 /* Append the element we want to insert. */
3650 ++middle;
3651 e.index = dindex;
3652 e.value = unshare_constructor (value);
3653 vec_safe_insert (CONSTRUCTOR_ELTS (ary), middle, e);
3655 else
3656 /* No lower elts, the range elt is now ours. */
3657 elt.index = dindex;
3659 if (tree_int_cst_lt (dindex, hi))
3661 /* There are still some higher elts; append a range. */
3662 tree new_lo = int_const_binop (PLUS_EXPR, dindex,
3663 size_one_node);
3664 if (tree_int_cst_equal (new_lo, hi))
3665 e.index = hi;
3666 else
3667 e.index = build2 (RANGE_EXPR, sizetype, new_lo, hi);
3668 e.value = unshare_constructor (value);
3669 vec_safe_insert (CONSTRUCTOR_ELTS (ary), middle + 1, e);
3672 return middle;
3676 if (insert)
3678 constructor_elt e = { dindex, NULL_TREE };
3679 vec_safe_insert (CONSTRUCTOR_ELTS (ary), end, e);
3680 return end;
3683 return -1;
3686 /* Return a pointer to the constructor_elt of CTOR which matches INDEX. If no
3687 matching constructor_elt exists, then add one to CTOR.
3689 As an optimization, if POS_HINT is non-negative then it is used as a guess
3690 for the (integer) index of the matching constructor_elt within CTOR. */
3692 static constructor_elt *
3693 get_or_insert_ctor_field (tree ctor, tree index, int pos_hint = -1)
3695 /* Check the hint first. */
3696 if (pos_hint >= 0 && (unsigned)pos_hint < CONSTRUCTOR_NELTS (ctor)
3697 && CONSTRUCTOR_ELT (ctor, pos_hint)->index == index)
3698 return CONSTRUCTOR_ELT (ctor, pos_hint);
3700 tree type = TREE_TYPE (ctor);
3701 if (TREE_CODE (type) == VECTOR_TYPE && index == NULL_TREE)
3703 CONSTRUCTOR_APPEND_ELT (CONSTRUCTOR_ELTS (ctor), index, NULL_TREE);
3704 return &CONSTRUCTOR_ELTS (ctor)->last();
3706 else if (TREE_CODE (type) == ARRAY_TYPE || TREE_CODE (type) == VECTOR_TYPE)
3708 if (TREE_CODE (index) == RANGE_EXPR)
3710 /* Support for RANGE_EXPR index lookups is currently limited to
3711 accessing an existing element via POS_HINT, or appending a new
3712 element to the end of CTOR. ??? Support for other access
3713 patterns may also be needed. */
3714 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ctor);
3715 if (vec_safe_length (elts))
3717 tree lo = TREE_OPERAND (index, 0);
3718 gcc_assert (array_index_cmp (elts->last().index, lo) < 0);
3720 CONSTRUCTOR_APPEND_ELT (elts, index, NULL_TREE);
3721 return &elts->last();
3724 HOST_WIDE_INT i = find_array_ctor_elt (ctor, index, /*insert*/true);
3725 gcc_assert (i >= 0);
3726 constructor_elt *cep = CONSTRUCTOR_ELT (ctor, i);
3727 gcc_assert (cep->index == NULL_TREE
3728 || TREE_CODE (cep->index) != RANGE_EXPR);
3729 return cep;
3731 else
3733 gcc_assert (TREE_CODE (index) == FIELD_DECL
3734 && (same_type_ignoring_top_level_qualifiers_p
3735 (DECL_CONTEXT (index), TREE_TYPE (ctor))));
3737 /* We must keep the CONSTRUCTOR's ELTS in FIELD order.
3738 Usually we meet initializers in that order, but it is
3739 possible for base types to be placed not in program
3740 order. */
3741 tree fields = TYPE_FIELDS (DECL_CONTEXT (index));
3742 unsigned HOST_WIDE_INT idx = 0;
3743 constructor_elt *cep = NULL;
3745 /* Check if we're changing the active member of a union. */
3746 if (TREE_CODE (type) == UNION_TYPE && CONSTRUCTOR_NELTS (ctor)
3747 && CONSTRUCTOR_ELT (ctor, 0)->index != index)
3748 vec_safe_truncate (CONSTRUCTOR_ELTS (ctor), 0);
3749 /* If the bit offset of INDEX is larger than that of the last
3750 constructor_elt, then we can just immediately append a new
3751 constructor_elt to the end of CTOR. */
3752 else if (CONSTRUCTOR_NELTS (ctor)
3753 && tree_int_cst_compare (bit_position (index),
3754 bit_position (CONSTRUCTOR_ELTS (ctor)
3755 ->last().index)) > 0)
3757 idx = CONSTRUCTOR_NELTS (ctor);
3758 goto insert;
3761 /* Otherwise, we need to iterate over CTOR to find or insert INDEX
3762 appropriately. */
3764 for (; vec_safe_iterate (CONSTRUCTOR_ELTS (ctor), idx, &cep);
3765 idx++, fields = DECL_CHAIN (fields))
3767 if (index == cep->index)
3768 goto found;
3770 /* The field we're initializing must be on the field
3771 list. Look to see if it is present before the
3772 field the current ELT initializes. */
3773 for (; fields != cep->index; fields = DECL_CHAIN (fields))
3774 if (index == fields)
3775 goto insert;
3777 /* We fell off the end of the CONSTRUCTOR, so insert a new
3778 entry at the end. */
3780 insert:
3782 constructor_elt ce = { index, NULL_TREE };
3784 vec_safe_insert (CONSTRUCTOR_ELTS (ctor), idx, ce);
3785 cep = CONSTRUCTOR_ELT (ctor, idx);
3787 found:;
3789 return cep;
3793 /* Under the control of CTX, issue a detailed diagnostic for
3794 an out-of-bounds subscript INDEX into the expression ARRAY. */
3796 static void
3797 diag_array_subscript (location_t loc, const constexpr_ctx *ctx, tree array, tree index)
3799 if (!ctx->quiet)
3801 tree arraytype = TREE_TYPE (array);
3803 /* Convert the unsigned array subscript to a signed integer to avoid
3804 printing huge numbers for small negative values. */
3805 tree sidx = fold_convert (ssizetype, index);
3806 STRIP_ANY_LOCATION_WRAPPER (array);
3807 if (DECL_P (array))
3809 if (TYPE_DOMAIN (arraytype))
3810 error_at (loc, "array subscript value %qE is outside the bounds "
3811 "of array %qD of type %qT", sidx, array, arraytype);
3812 else
3813 error_at (loc, "nonzero array subscript %qE is used with array %qD of "
3814 "type %qT with unknown bounds", sidx, array, arraytype);
3815 inform (DECL_SOURCE_LOCATION (array), "declared here");
3817 else if (TYPE_DOMAIN (arraytype))
3818 error_at (loc, "array subscript value %qE is outside the bounds "
3819 "of array type %qT", sidx, arraytype);
3820 else
3821 error_at (loc, "nonzero array subscript %qE is used with array of type %qT "
3822 "with unknown bounds", sidx, arraytype);
3826 /* Return the number of elements for TYPE (which is an ARRAY_TYPE or
3827 a VECTOR_TYPE). */
3829 static tree
3830 get_array_or_vector_nelts (const constexpr_ctx *ctx, tree type,
3831 bool *non_constant_p, bool *overflow_p)
3833 tree nelts;
3834 if (TREE_CODE (type) == ARRAY_TYPE)
3836 if (TYPE_DOMAIN (type))
3837 nelts = array_type_nelts_top (type);
3838 else
3839 nelts = size_zero_node;
3841 else if (VECTOR_TYPE_P (type))
3842 nelts = size_int (TYPE_VECTOR_SUBPARTS (type));
3843 else
3844 gcc_unreachable ();
3846 /* For VLAs, the number of elements won't be an integer constant. */
3847 nelts = cxx_eval_constant_expression (ctx, nelts, false,
3848 non_constant_p, overflow_p);
3849 return nelts;
3852 /* Extract element INDEX consisting of CHARS_PER_ELT chars from
3853 STRING_CST STRING. */
3855 static tree
3856 extract_string_elt (tree string, unsigned chars_per_elt, unsigned index)
3858 tree type = cv_unqualified (TREE_TYPE (TREE_TYPE (string)));
3859 tree r;
3861 if (chars_per_elt == 1)
3862 r = build_int_cst (type, TREE_STRING_POINTER (string)[index]);
3863 else
3865 const unsigned char *ptr
3866 = ((const unsigned char *)TREE_STRING_POINTER (string)
3867 + index * chars_per_elt);
3868 r = native_interpret_expr (type, ptr, chars_per_elt);
3870 return r;
3873 /* Subroutine of cxx_eval_array_reference. T is an ARRAY_REF; evaluate the
3874 subscript, diagnose any problems with it, and return the result. */
3876 static tree
3877 eval_and_check_array_index (const constexpr_ctx *ctx,
3878 tree t, bool allow_one_past,
3879 bool *non_constant_p, bool *overflow_p)
3881 location_t loc = cp_expr_loc_or_input_loc (t);
3882 tree ary = TREE_OPERAND (t, 0);
3883 t = TREE_OPERAND (t, 1);
3884 tree index = cxx_eval_constant_expression (ctx, t, false,
3885 non_constant_p, overflow_p);
3886 VERIFY_CONSTANT (index);
3888 if (!tree_fits_shwi_p (index)
3889 || tree_int_cst_sgn (index) < 0)
3891 diag_array_subscript (loc, ctx, ary, index);
3892 *non_constant_p = true;
3893 return t;
3896 tree nelts = get_array_or_vector_nelts (ctx, TREE_TYPE (ary), non_constant_p,
3897 overflow_p);
3898 VERIFY_CONSTANT (nelts);
3899 if (allow_one_past
3900 ? !tree_int_cst_le (index, nelts)
3901 : !tree_int_cst_lt (index, nelts))
3903 diag_array_subscript (loc, ctx, ary, index);
3904 *non_constant_p = true;
3905 return t;
3908 return index;
3911 /* Subroutine of cxx_eval_constant_expression.
3912 Attempt to reduce a reference to an array slot. */
3914 static tree
3915 cxx_eval_array_reference (const constexpr_ctx *ctx, tree t,
3916 bool lval,
3917 bool *non_constant_p, bool *overflow_p)
3919 tree oldary = TREE_OPERAND (t, 0);
3920 tree ary = cxx_eval_constant_expression (ctx, oldary,
3921 lval,
3922 non_constant_p, overflow_p);
3923 if (*non_constant_p)
3924 return t;
3925 if (!lval
3926 && TREE_CODE (ary) == VIEW_CONVERT_EXPR
3927 && VECTOR_TYPE_P (TREE_TYPE (TREE_OPERAND (ary, 0)))
3928 && TREE_TYPE (t) == TREE_TYPE (TREE_TYPE (TREE_OPERAND (ary, 0))))
3929 ary = TREE_OPERAND (ary, 0);
3931 tree oldidx = TREE_OPERAND (t, 1);
3932 tree index = eval_and_check_array_index (ctx, t, lval,
3933 non_constant_p, overflow_p);
3934 if (*non_constant_p)
3935 return t;
3937 if (lval && ary == oldary && index == oldidx)
3938 return t;
3939 else if (lval)
3940 return build4 (ARRAY_REF, TREE_TYPE (t), ary, index, NULL, NULL);
3942 unsigned len = 0, elem_nchars = 1;
3943 tree elem_type = TREE_TYPE (TREE_TYPE (ary));
3944 if (TREE_CODE (ary) == CONSTRUCTOR)
3945 len = CONSTRUCTOR_NELTS (ary);
3946 else if (TREE_CODE (ary) == STRING_CST)
3948 elem_nchars = (TYPE_PRECISION (elem_type)
3949 / TYPE_PRECISION (char_type_node));
3950 len = (unsigned) TREE_STRING_LENGTH (ary) / elem_nchars;
3952 else if (TREE_CODE (ary) == VECTOR_CST)
3953 /* We don't create variable-length VECTOR_CSTs. */
3954 len = VECTOR_CST_NELTS (ary).to_constant ();
3955 else
3957 /* We can't do anything with other tree codes, so use
3958 VERIFY_CONSTANT to complain and fail. */
3959 VERIFY_CONSTANT (ary);
3960 gcc_unreachable ();
3963 bool found;
3964 HOST_WIDE_INT i = 0;
3965 if (TREE_CODE (ary) == CONSTRUCTOR)
3967 HOST_WIDE_INT ix = find_array_ctor_elt (ary, index);
3968 found = (ix >= 0);
3969 if (found)
3970 i = ix;
3972 else
3974 i = tree_to_shwi (index);
3975 found = (i < len);
3978 if (found)
3980 tree r;
3981 if (TREE_CODE (ary) == CONSTRUCTOR)
3982 r = (*CONSTRUCTOR_ELTS (ary))[i].value;
3983 else if (TREE_CODE (ary) == VECTOR_CST)
3984 r = VECTOR_CST_ELT (ary, i);
3985 else
3986 r = extract_string_elt (ary, elem_nchars, i);
3988 if (r)
3989 /* Don't VERIFY_CONSTANT here. */
3990 return r;
3992 /* Otherwise the element doesn't have a value yet. */
3995 /* Not found. */
3997 if (TREE_CODE (ary) == CONSTRUCTOR
3998 && CONSTRUCTOR_NO_CLEARING (ary))
4000 /* 'ary' is part of the aggregate initializer we're currently
4001 building; if there's no initializer for this element yet,
4002 that's an error. */
4003 if (!ctx->quiet)
4004 error ("accessing uninitialized array element");
4005 *non_constant_p = true;
4006 return t;
4009 /* If it's within the array bounds but doesn't have an explicit
4010 initializer, it's initialized from {}. But use build_value_init
4011 directly for non-aggregates to avoid creating a garbage CONSTRUCTOR. */
4012 tree val;
4013 constexpr_ctx new_ctx;
4014 if (is_really_empty_class (elem_type, /*ignore_vptr*/false))
4015 return build_constructor (elem_type, NULL);
4016 else if (CP_AGGREGATE_TYPE_P (elem_type))
4018 tree empty_ctor = build_constructor (init_list_type_node, NULL);
4019 val = digest_init (elem_type, empty_ctor, tf_warning_or_error);
4021 else
4022 val = build_value_init (elem_type, tf_warning_or_error);
4024 if (!SCALAR_TYPE_P (elem_type))
4026 new_ctx = *ctx;
4027 if (ctx->object)
4028 /* If there was no object, don't add one: it could confuse us
4029 into thinking we're modifying a const object. */
4030 new_ctx.object = t;
4031 new_ctx.ctor = build_constructor (elem_type, NULL);
4032 ctx = &new_ctx;
4034 t = cxx_eval_constant_expression (ctx, val, lval, non_constant_p,
4035 overflow_p);
4036 if (!SCALAR_TYPE_P (elem_type) && t != ctx->ctor)
4037 free_constructor (ctx->ctor);
4038 return t;
4041 /* Subroutine of cxx_eval_constant_expression.
4042 Attempt to reduce a field access of a value of class type. */
4044 static tree
4045 cxx_eval_component_reference (const constexpr_ctx *ctx, tree t,
4046 bool lval,
4047 bool *non_constant_p, bool *overflow_p)
4049 unsigned HOST_WIDE_INT i;
4050 tree field;
4051 tree value;
4052 tree part = TREE_OPERAND (t, 1);
4053 tree orig_whole = TREE_OPERAND (t, 0);
4054 tree whole = cxx_eval_constant_expression (ctx, orig_whole,
4055 lval,
4056 non_constant_p, overflow_p);
4057 if (INDIRECT_REF_P (whole)
4058 && integer_zerop (TREE_OPERAND (whole, 0)))
4060 if (!ctx->quiet)
4061 error ("dereferencing a null pointer in %qE", orig_whole);
4062 *non_constant_p = true;
4063 return t;
4066 if (TREE_CODE (whole) == PTRMEM_CST)
4067 whole = cplus_expand_constant (whole);
4068 if (whole == orig_whole)
4069 return t;
4070 if (lval)
4071 return fold_build3 (COMPONENT_REF, TREE_TYPE (t),
4072 whole, part, NULL_TREE);
4073 /* Don't VERIFY_CONSTANT here; we only want to check that we got a
4074 CONSTRUCTOR. */
4075 if (!*non_constant_p && TREE_CODE (whole) != CONSTRUCTOR)
4077 if (!ctx->quiet)
4078 error ("%qE is not a constant expression", orig_whole);
4079 *non_constant_p = true;
4081 if (DECL_MUTABLE_P (part))
4083 if (!ctx->quiet)
4084 error ("mutable %qD is not usable in a constant expression", part);
4085 *non_constant_p = true;
4087 if (*non_constant_p)
4088 return t;
4089 bool pmf = TYPE_PTRMEMFUNC_P (TREE_TYPE (whole));
4090 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
4092 /* Use name match for PMF fields, as a variant will have a
4093 different FIELD_DECL with a different type. */
4094 if (pmf ? DECL_NAME (field) == DECL_NAME (part)
4095 : field == part)
4097 if (value)
4099 STRIP_ANY_LOCATION_WRAPPER (value);
4100 return value;
4102 else
4103 /* We're in the middle of initializing it. */
4104 break;
4107 if (TREE_CODE (TREE_TYPE (whole)) == UNION_TYPE
4108 && CONSTRUCTOR_NELTS (whole) > 0)
4110 /* DR 1188 says we don't have to deal with this. */
4111 if (!ctx->quiet)
4113 constructor_elt *cep = CONSTRUCTOR_ELT (whole, 0);
4114 if (cep->value == NULL_TREE)
4115 error ("accessing uninitialized member %qD", part);
4116 else
4117 error ("accessing %qD member instead of initialized %qD member in "
4118 "constant expression", part, cep->index);
4120 *non_constant_p = true;
4121 return t;
4124 /* We only create a CONSTRUCTOR for a subobject when we modify it, so empty
4125 classes never get represented; throw together a value now. */
4126 if (is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
4127 return build_constructor (TREE_TYPE (t), NULL);
4129 gcc_assert (DECL_CONTEXT (part) == TYPE_MAIN_VARIANT (TREE_TYPE (whole)));
4131 if (CONSTRUCTOR_NO_CLEARING (whole))
4133 /* 'whole' is part of the aggregate initializer we're currently
4134 building; if there's no initializer for this member yet, that's an
4135 error. */
4136 if (!ctx->quiet)
4137 error ("accessing uninitialized member %qD", part);
4138 *non_constant_p = true;
4139 return t;
4142 /* If there's no explicit init for this field, it's value-initialized. */
4143 value = build_value_init (TREE_TYPE (t), tf_warning_or_error);
4144 return cxx_eval_constant_expression (ctx, value,
4145 lval,
4146 non_constant_p, overflow_p);
4149 /* Subroutine of cxx_eval_constant_expression.
4150 Attempt to reduce a field access of a value of class type that is
4151 expressed as a BIT_FIELD_REF. */
4153 static tree
4154 cxx_eval_bit_field_ref (const constexpr_ctx *ctx, tree t,
4155 bool lval,
4156 bool *non_constant_p, bool *overflow_p)
4158 tree orig_whole = TREE_OPERAND (t, 0);
4159 tree retval, fldval, utype, mask;
4160 bool fld_seen = false;
4161 HOST_WIDE_INT istart, isize;
4162 tree whole = cxx_eval_constant_expression (ctx, orig_whole,
4163 lval,
4164 non_constant_p, overflow_p);
4165 tree start, field, value;
4166 unsigned HOST_WIDE_INT i;
4168 if (whole == orig_whole)
4169 return t;
4170 /* Don't VERIFY_CONSTANT here; we only want to check that we got a
4171 CONSTRUCTOR. */
4172 if (!*non_constant_p
4173 && TREE_CODE (whole) != VECTOR_CST
4174 && TREE_CODE (whole) != CONSTRUCTOR)
4176 if (!ctx->quiet)
4177 error ("%qE is not a constant expression", orig_whole);
4178 *non_constant_p = true;
4180 if (*non_constant_p)
4181 return t;
4183 if (TREE_CODE (whole) == VECTOR_CST)
4184 return fold_ternary (BIT_FIELD_REF, TREE_TYPE (t), whole,
4185 TREE_OPERAND (t, 1), TREE_OPERAND (t, 2));
4187 start = TREE_OPERAND (t, 2);
4188 istart = tree_to_shwi (start);
4189 isize = tree_to_shwi (TREE_OPERAND (t, 1));
4190 utype = TREE_TYPE (t);
4191 if (!TYPE_UNSIGNED (utype))
4192 utype = build_nonstandard_integer_type (TYPE_PRECISION (utype), 1);
4193 retval = build_int_cst (utype, 0);
4194 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
4196 tree bitpos = bit_position (field);
4197 STRIP_ANY_LOCATION_WRAPPER (value);
4198 if (bitpos == start && DECL_SIZE (field) == TREE_OPERAND (t, 1))
4199 return value;
4200 if (TREE_CODE (TREE_TYPE (field)) == INTEGER_TYPE
4201 && TREE_CODE (value) == INTEGER_CST
4202 && tree_fits_shwi_p (bitpos)
4203 && tree_fits_shwi_p (DECL_SIZE (field)))
4205 HOST_WIDE_INT bit = tree_to_shwi (bitpos);
4206 HOST_WIDE_INT sz = tree_to_shwi (DECL_SIZE (field));
4207 HOST_WIDE_INT shift;
4208 if (bit >= istart && bit + sz <= istart + isize)
4210 fldval = fold_convert (utype, value);
4211 mask = build_int_cst_type (utype, -1);
4212 mask = fold_build2 (LSHIFT_EXPR, utype, mask,
4213 size_int (TYPE_PRECISION (utype) - sz));
4214 mask = fold_build2 (RSHIFT_EXPR, utype, mask,
4215 size_int (TYPE_PRECISION (utype) - sz));
4216 fldval = fold_build2 (BIT_AND_EXPR, utype, fldval, mask);
4217 shift = bit - istart;
4218 if (BYTES_BIG_ENDIAN)
4219 shift = TYPE_PRECISION (utype) - shift - sz;
4220 fldval = fold_build2 (LSHIFT_EXPR, utype, fldval,
4221 size_int (shift));
4222 retval = fold_build2 (BIT_IOR_EXPR, utype, retval, fldval);
4223 fld_seen = true;
4227 if (fld_seen)
4228 return fold_convert (TREE_TYPE (t), retval);
4229 gcc_unreachable ();
4230 return error_mark_node;
4233 /* Helper for cxx_eval_bit_cast.
4234 Check [bit.cast]/3 rules, bit_cast is constexpr only if the To and From
4235 types and types of all subobjects have is_union_v<T>, is_pointer_v<T>,
4236 is_member_pointer_v<T>, is_volatile_v<T> false and has no non-static
4237 data members of reference type. */
4239 static bool
4240 check_bit_cast_type (const constexpr_ctx *ctx, location_t loc, tree type,
4241 tree orig_type)
4243 if (TREE_CODE (type) == UNION_TYPE)
4245 if (!ctx->quiet)
4247 if (type == orig_type)
4248 error_at (loc, "%qs is not a constant expression because %qT is "
4249 "a union type", "__builtin_bit_cast", type);
4250 else
4251 error_at (loc, "%qs is not a constant expression because %qT "
4252 "contains a union type", "__builtin_bit_cast",
4253 orig_type);
4255 return true;
4257 if (TREE_CODE (type) == POINTER_TYPE)
4259 if (!ctx->quiet)
4261 if (type == orig_type)
4262 error_at (loc, "%qs is not a constant expression because %qT is "
4263 "a pointer type", "__builtin_bit_cast", type);
4264 else
4265 error_at (loc, "%qs is not a constant expression because %qT "
4266 "contains a pointer type", "__builtin_bit_cast",
4267 orig_type);
4269 return true;
4271 if (TREE_CODE (type) == REFERENCE_TYPE)
4273 if (!ctx->quiet)
4275 if (type == orig_type)
4276 error_at (loc, "%qs is not a constant expression because %qT is "
4277 "a reference type", "__builtin_bit_cast", type);
4278 else
4279 error_at (loc, "%qs is not a constant expression because %qT "
4280 "contains a reference type", "__builtin_bit_cast",
4281 orig_type);
4283 return true;
4285 if (TYPE_PTRMEM_P (type))
4287 if (!ctx->quiet)
4289 if (type == orig_type)
4290 error_at (loc, "%qs is not a constant expression because %qT is "
4291 "a pointer to member type", "__builtin_bit_cast",
4292 type);
4293 else
4294 error_at (loc, "%qs is not a constant expression because %qT "
4295 "contains a pointer to member type",
4296 "__builtin_bit_cast", orig_type);
4298 return true;
4300 if (TYPE_VOLATILE (type))
4302 if (!ctx->quiet)
4304 if (type == orig_type)
4305 error_at (loc, "%qs is not a constant expression because %qT is "
4306 "volatile", "__builtin_bit_cast", type);
4307 else
4308 error_at (loc, "%qs is not a constant expression because %qT "
4309 "contains a volatile subobject",
4310 "__builtin_bit_cast", orig_type);
4312 return true;
4314 if (TREE_CODE (type) == RECORD_TYPE)
4315 for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
4316 if (TREE_CODE (field) == FIELD_DECL
4317 && check_bit_cast_type (ctx, loc, TREE_TYPE (field), orig_type))
4318 return true;
4319 return false;
4322 /* Helper function for cxx_eval_bit_cast. For unsigned char or
4323 std::byte members of CONSTRUCTOR (recursively) if they contain
4324 some indeterminate bits (as set in MASK), remove the ctor elts,
4325 mark the CONSTRUCTOR as CONSTRUCTOR_NO_CLEARING and clear the
4326 bits in MASK. */
4328 static void
4329 clear_uchar_or_std_byte_in_mask (location_t loc, tree t, unsigned char *mask)
4331 if (TREE_CODE (t) != CONSTRUCTOR)
4332 return;
4334 unsigned i, j = 0;
4335 tree index, value;
4336 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (t), i, index, value)
4338 tree type = TREE_TYPE (value);
4339 if (TREE_CODE (TREE_TYPE (t)) != ARRAY_TYPE
4340 && DECL_BIT_FIELD_TYPE (index) != NULL_TREE)
4342 if (is_byte_access_type_not_plain_char (DECL_BIT_FIELD_TYPE (index)))
4344 HOST_WIDE_INT fldsz = TYPE_PRECISION (TREE_TYPE (index));
4345 gcc_assert (fldsz != 0);
4346 HOST_WIDE_INT pos = int_byte_position (index);
4347 HOST_WIDE_INT bpos
4348 = tree_to_uhwi (DECL_FIELD_BIT_OFFSET (index));
4349 bpos %= BITS_PER_UNIT;
4350 HOST_WIDE_INT end
4351 = ROUND_UP (bpos + fldsz, BITS_PER_UNIT) / BITS_PER_UNIT;
4352 gcc_assert (end == 1 || end == 2);
4353 unsigned char *p = mask + pos;
4354 unsigned char mask_save[2];
4355 mask_save[0] = mask[pos];
4356 mask_save[1] = end == 2 ? mask[pos + 1] : 0;
4357 if (BYTES_BIG_ENDIAN != WORDS_BIG_ENDIAN)
4358 sorry_at (loc, "PDP11 bit-field handling unsupported"
4359 " in %qs", "__builtin_bit_cast");
4360 else if (BYTES_BIG_ENDIAN)
4362 /* Big endian. */
4363 if (bpos + fldsz <= BITS_PER_UNIT)
4364 *p &= ~(((1 << fldsz) - 1)
4365 << (BITS_PER_UNIT - bpos - fldsz));
4366 else
4368 gcc_assert (bpos);
4369 *p &= ~(((1U << BITS_PER_UNIT) - 1) >> bpos);
4370 p++;
4371 fldsz -= BITS_PER_UNIT - bpos;
4372 gcc_assert (fldsz && fldsz < BITS_PER_UNIT);
4373 *p &= ((1U << BITS_PER_UNIT) - 1) >> fldsz;
4376 else
4378 /* Little endian. */
4379 if (bpos + fldsz <= BITS_PER_UNIT)
4380 *p &= ~(((1 << fldsz) - 1) << bpos);
4381 else
4383 gcc_assert (bpos);
4384 *p &= ~(((1 << BITS_PER_UNIT) - 1) << bpos);
4385 p++;
4386 fldsz -= BITS_PER_UNIT - bpos;
4387 gcc_assert (fldsz && fldsz < BITS_PER_UNIT);
4388 *p &= ~((1 << fldsz) - 1);
4391 if (mask_save[0] != mask[pos]
4392 || (end == 2 && mask_save[1] != mask[pos + 1]))
4394 CONSTRUCTOR_NO_CLEARING (t) = 1;
4395 continue;
4399 else if (is_byte_access_type_not_plain_char (type))
4401 HOST_WIDE_INT pos;
4402 if (TREE_CODE (TREE_TYPE (t)) == ARRAY_TYPE)
4403 pos = tree_to_shwi (index);
4404 else
4405 pos = int_byte_position (index);
4406 if (mask[pos])
4408 CONSTRUCTOR_NO_CLEARING (t) = 1;
4409 mask[pos] = 0;
4410 continue;
4413 if (TREE_CODE (value) == CONSTRUCTOR)
4415 HOST_WIDE_INT pos;
4416 if (TREE_CODE (TREE_TYPE (t)) == ARRAY_TYPE)
4417 pos = tree_to_shwi (index)
4418 * tree_to_shwi (TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (t))));
4419 else
4420 pos = int_byte_position (index);
4421 clear_uchar_or_std_byte_in_mask (loc, value, mask + pos);
4423 if (i != j)
4425 CONSTRUCTOR_ELT (t, j)->index = index;
4426 CONSTRUCTOR_ELT (t, j)->value = value;
4428 ++j;
4430 if (CONSTRUCTOR_NELTS (t) != j)
4431 vec_safe_truncate (CONSTRUCTOR_ELTS (t), j);
4434 /* Subroutine of cxx_eval_constant_expression.
4435 Attempt to evaluate a BIT_CAST_EXPR. */
4437 static tree
4438 cxx_eval_bit_cast (const constexpr_ctx *ctx, tree t, bool *non_constant_p,
4439 bool *overflow_p)
4441 if (check_bit_cast_type (ctx, EXPR_LOCATION (t), TREE_TYPE (t),
4442 TREE_TYPE (t))
4443 || check_bit_cast_type (ctx, cp_expr_loc_or_loc (TREE_OPERAND (t, 0),
4444 EXPR_LOCATION (t)),
4445 TREE_TYPE (TREE_OPERAND (t, 0)),
4446 TREE_TYPE (TREE_OPERAND (t, 0))))
4448 *non_constant_p = true;
4449 return t;
4452 tree op = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), false,
4453 non_constant_p, overflow_p);
4454 if (*non_constant_p)
4455 return t;
4457 location_t loc = EXPR_LOCATION (t);
4458 if (BITS_PER_UNIT != 8 || CHAR_BIT != 8)
4460 if (!ctx->quiet)
4461 sorry_at (loc, "%qs cannot be constant evaluated on the target",
4462 "__builtin_bit_cast");
4463 *non_constant_p = true;
4464 return t;
4467 if (!tree_fits_shwi_p (TYPE_SIZE_UNIT (TREE_TYPE (t))))
4469 if (!ctx->quiet)
4470 sorry_at (loc, "%qs cannot be constant evaluated because the "
4471 "type is too large", "__builtin_bit_cast");
4472 *non_constant_p = true;
4473 return t;
4476 HOST_WIDE_INT len = tree_to_shwi (TYPE_SIZE_UNIT (TREE_TYPE (t)));
4477 if (len < 0 || (int) len != len)
4479 if (!ctx->quiet)
4480 sorry_at (loc, "%qs cannot be constant evaluated because the "
4481 "type is too large", "__builtin_bit_cast");
4482 *non_constant_p = true;
4483 return t;
4486 unsigned char buf[64];
4487 unsigned char *ptr, *mask;
4488 size_t alen = (size_t) len * 2;
4489 if (alen <= sizeof (buf))
4490 ptr = buf;
4491 else
4492 ptr = XNEWVEC (unsigned char, alen);
4493 mask = ptr + (size_t) len;
4494 /* At the beginning consider everything indeterminate. */
4495 memset (mask, ~0, (size_t) len);
4497 if (native_encode_initializer (op, ptr, len, 0, mask) != len)
4499 if (!ctx->quiet)
4500 sorry_at (loc, "%qs cannot be constant evaluated because the "
4501 "argument cannot be encoded", "__builtin_bit_cast");
4502 *non_constant_p = true;
4503 if (ptr != buf)
4504 XDELETE (ptr);
4505 return t;
4508 tree r = NULL_TREE;
4509 if (can_native_interpret_type_p (TREE_TYPE (t)))
4511 r = native_interpret_expr (TREE_TYPE (t), ptr, len);
4512 if (is_byte_access_type_not_plain_char (TREE_TYPE (t)))
4514 gcc_assert (len == 1);
4515 if (mask[0])
4517 memset (mask, 0, len);
4518 r = build_constructor (TREE_TYPE (r), NULL);
4519 CONSTRUCTOR_NO_CLEARING (r) = 1;
4523 else if (TREE_CODE (TREE_TYPE (t)) == RECORD_TYPE)
4525 r = native_interpret_aggregate (TREE_TYPE (t), ptr, 0, len);
4526 if (r != NULL_TREE)
4528 clear_type_padding_in_mask (TREE_TYPE (t), mask);
4529 clear_uchar_or_std_byte_in_mask (loc, r, mask);
4533 if (r != NULL_TREE)
4535 for (int i = 0; i < len; i++)
4536 if (mask[i])
4538 if (!ctx->quiet)
4539 error_at (loc, "%qs accessing uninitialized byte at offset %d",
4540 "__builtin_bit_cast", i);
4541 *non_constant_p = true;
4542 r = t;
4543 break;
4545 if (ptr != buf)
4546 XDELETE (ptr);
4547 return r;
4550 if (!ctx->quiet)
4551 sorry_at (loc, "%qs cannot be constant evaluated because the "
4552 "argument cannot be interpreted", "__builtin_bit_cast");
4553 *non_constant_p = true;
4554 if (ptr != buf)
4555 XDELETE (ptr);
4556 return t;
4559 /* Subroutine of cxx_eval_constant_expression.
4560 Evaluate a short-circuited logical expression T in the context
4561 of a given constexpr CALL. BAILOUT_VALUE is the value for
4562 early return. CONTINUE_VALUE is used here purely for
4563 sanity check purposes. */
4565 static tree
4566 cxx_eval_logical_expression (const constexpr_ctx *ctx, tree t,
4567 tree bailout_value, tree continue_value,
4568 bool *non_constant_p, bool *overflow_p)
4570 tree r;
4571 tree lhs = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
4572 /*lval*/false, non_constant_p,
4573 overflow_p);
4574 VERIFY_CONSTANT (lhs);
4575 if (tree_int_cst_equal (lhs, bailout_value))
4576 return lhs;
4577 gcc_assert (tree_int_cst_equal (lhs, continue_value));
4578 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
4579 /*lval*/false, non_constant_p,
4580 overflow_p);
4581 VERIFY_CONSTANT (r);
4582 return r;
4585 /* REF is a COMPONENT_REF designating a particular field. V is a vector of
4586 CONSTRUCTOR elements to initialize (part of) an object containing that
4587 field. Return a pointer to the constructor_elt corresponding to the
4588 initialization of the field. */
4590 static constructor_elt *
4591 base_field_constructor_elt (vec<constructor_elt, va_gc> *v, tree ref)
4593 tree aggr = TREE_OPERAND (ref, 0);
4594 tree field = TREE_OPERAND (ref, 1);
4595 HOST_WIDE_INT i;
4596 constructor_elt *ce;
4598 gcc_assert (TREE_CODE (ref) == COMPONENT_REF);
4600 if (TREE_CODE (aggr) == COMPONENT_REF)
4602 constructor_elt *base_ce
4603 = base_field_constructor_elt (v, aggr);
4604 v = CONSTRUCTOR_ELTS (base_ce->value);
4607 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
4608 if (ce->index == field)
4609 return ce;
4611 gcc_unreachable ();
4612 return NULL;
4615 /* Some of the expressions fed to the constexpr mechanism are calls to
4616 constructors, which have type void. In that case, return the type being
4617 initialized by the constructor. */
4619 static tree
4620 initialized_type (tree t)
4622 if (TYPE_P (t))
4623 return t;
4624 tree type = TREE_TYPE (t);
4625 if (TREE_CODE (t) == CALL_EXPR)
4627 /* A constructor call has void type, so we need to look deeper. */
4628 tree fn = get_function_named_in_call (t);
4629 if (fn && TREE_CODE (fn) == FUNCTION_DECL
4630 && DECL_CXX_CONSTRUCTOR_P (fn))
4631 type = DECL_CONTEXT (fn);
4633 else if (TREE_CODE (t) == COMPOUND_EXPR)
4634 return initialized_type (TREE_OPERAND (t, 1));
4635 else if (TREE_CODE (t) == AGGR_INIT_EXPR)
4636 type = TREE_TYPE (AGGR_INIT_EXPR_SLOT (t));
4637 return cv_unqualified (type);
4640 /* We're about to initialize element INDEX of an array or class from VALUE.
4641 Set up NEW_CTX appropriately by adjusting .object to refer to the
4642 subobject and creating a new CONSTRUCTOR if the element is itself
4643 a class or array. */
4645 static void
4646 init_subob_ctx (const constexpr_ctx *ctx, constexpr_ctx &new_ctx,
4647 tree index, tree &value)
4649 new_ctx = *ctx;
4651 if (index && TREE_CODE (index) != INTEGER_CST
4652 && TREE_CODE (index) != FIELD_DECL
4653 && TREE_CODE (index) != RANGE_EXPR)
4654 /* This won't have an element in the new CONSTRUCTOR. */
4655 return;
4657 tree type = initialized_type (value);
4658 if (!AGGREGATE_TYPE_P (type) && !VECTOR_TYPE_P (type))
4659 /* A non-aggregate member doesn't get its own CONSTRUCTOR. */
4660 return;
4661 if (VECTOR_TYPE_P (type)
4662 && VECTOR_TYPE_P (TREE_TYPE (ctx->ctor))
4663 && index == NULL_TREE)
4664 /* A vector inside of a vector CONSTRUCTOR, e.g. when a larger
4665 vector is constructed from smaller vectors, doesn't get its own
4666 CONSTRUCTOR either. */
4667 return;
4669 /* The sub-aggregate initializer might contain a placeholder;
4670 update object to refer to the subobject and ctor to refer to
4671 the (newly created) sub-initializer. */
4672 if (ctx->object)
4674 if (index == NULL_TREE || TREE_CODE (index) == RANGE_EXPR)
4675 /* There's no well-defined subobject for this index. */
4676 new_ctx.object = NULL_TREE;
4677 else
4678 new_ctx.object = build_ctor_subob_ref (index, type, ctx->object);
4680 tree elt = build_constructor (type, NULL);
4681 CONSTRUCTOR_NO_CLEARING (elt) = true;
4682 new_ctx.ctor = elt;
4684 if (TREE_CODE (value) == TARGET_EXPR)
4685 /* Avoid creating another CONSTRUCTOR when we expand the TARGET_EXPR. */
4686 value = TARGET_EXPR_INITIAL (value);
4689 /* We're about to process an initializer for a class or array TYPE. Make
4690 sure that CTX is set up appropriately. */
4692 static void
4693 verify_ctor_sanity (const constexpr_ctx *ctx, tree type)
4695 /* We don't bother building a ctor for an empty base subobject. */
4696 if (is_empty_class (type))
4697 return;
4699 /* We're in the middle of an initializer that might involve placeholders;
4700 our caller should have created a CONSTRUCTOR for us to put the
4701 initializer into. We will either return that constructor or T. */
4702 gcc_assert (ctx->ctor);
4703 gcc_assert (same_type_ignoring_top_level_qualifiers_p
4704 (type, TREE_TYPE (ctx->ctor)));
4705 /* We used to check that ctx->ctor was empty, but that isn't the case when
4706 the object is zero-initialized before calling the constructor. */
4707 if (ctx->object)
4709 tree otype = TREE_TYPE (ctx->object);
4710 gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, otype)
4711 /* Handle flexible array members. */
4712 || (TREE_CODE (otype) == ARRAY_TYPE
4713 && TYPE_DOMAIN (otype) == NULL_TREE
4714 && TREE_CODE (type) == ARRAY_TYPE
4715 && (same_type_ignoring_top_level_qualifiers_p
4716 (TREE_TYPE (type), TREE_TYPE (otype)))));
4718 gcc_assert (!ctx->object || !DECL_P (ctx->object)
4719 || *(ctx->global->values.get (ctx->object)) == ctx->ctor);
4722 /* Subroutine of cxx_eval_constant_expression.
4723 The expression tree T denotes a C-style array or a C-style
4724 aggregate. Reduce it to a constant expression. */
4726 static tree
4727 cxx_eval_bare_aggregate (const constexpr_ctx *ctx, tree t,
4728 bool lval,
4729 bool *non_constant_p, bool *overflow_p)
4731 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
4732 bool changed = false;
4733 gcc_assert (!BRACE_ENCLOSED_INITIALIZER_P (t));
4734 tree type = TREE_TYPE (t);
4736 constexpr_ctx new_ctx;
4737 if (TYPE_PTRMEMFUNC_P (type) || VECTOR_TYPE_P (type))
4739 /* We don't really need the ctx->ctor business for a PMF or
4740 vector, but it's simpler to use the same code. */
4741 new_ctx = *ctx;
4742 new_ctx.ctor = build_constructor (type, NULL);
4743 new_ctx.object = NULL_TREE;
4744 ctx = &new_ctx;
4746 verify_ctor_sanity (ctx, type);
4747 vec<constructor_elt, va_gc> **p = &CONSTRUCTOR_ELTS (ctx->ctor);
4748 vec_alloc (*p, vec_safe_length (v));
4750 if (CONSTRUCTOR_PLACEHOLDER_BOUNDARY (t))
4751 CONSTRUCTOR_PLACEHOLDER_BOUNDARY (ctx->ctor) = 1;
4753 unsigned i;
4754 tree index, value;
4755 bool constant_p = true;
4756 bool side_effects_p = false;
4757 FOR_EACH_CONSTRUCTOR_ELT (v, i, index, value)
4759 tree orig_value = value;
4760 /* Like in cxx_eval_store_expression, omit entries for empty fields. */
4761 bool no_slot = TREE_CODE (type) == RECORD_TYPE && is_empty_field (index);
4762 if (no_slot)
4763 new_ctx = *ctx;
4764 else
4765 init_subob_ctx (ctx, new_ctx, index, value);
4766 int pos_hint = -1;
4767 if (new_ctx.ctor != ctx->ctor)
4769 /* If we built a new CONSTRUCTOR, attach it now so that other
4770 initializers can refer to it. */
4771 constructor_elt *cep = get_or_insert_ctor_field (ctx->ctor, index);
4772 cep->value = new_ctx.ctor;
4773 pos_hint = cep - (*p)->begin();
4775 else if (TREE_CODE (type) == UNION_TYPE)
4776 /* Otherwise if we're constructing a non-aggregate union member, set
4777 the active union member now so that we can later detect and diagnose
4778 if its initializer attempts to activate another member. */
4779 get_or_insert_ctor_field (ctx->ctor, index);
4780 tree elt = cxx_eval_constant_expression (&new_ctx, value,
4781 lval,
4782 non_constant_p, overflow_p);
4783 /* Don't VERIFY_CONSTANT here. */
4784 if (ctx->quiet && *non_constant_p)
4785 break;
4786 if (elt != orig_value)
4787 changed = true;
4789 if (!TREE_CONSTANT (elt))
4790 constant_p = false;
4791 if (TREE_SIDE_EFFECTS (elt))
4792 side_effects_p = true;
4793 if (index && TREE_CODE (index) == COMPONENT_REF)
4795 /* This is an initialization of a vfield inside a base
4796 subaggregate that we already initialized; push this
4797 initialization into the previous initialization. */
4798 constructor_elt *inner = base_field_constructor_elt (*p, index);
4799 inner->value = elt;
4800 changed = true;
4802 else if (index
4803 && (TREE_CODE (index) == NOP_EXPR
4804 || TREE_CODE (index) == POINTER_PLUS_EXPR))
4806 /* This is an initializer for an empty base; now that we've
4807 checked that it's constant, we can ignore it. */
4808 gcc_assert (is_empty_class (TREE_TYPE (TREE_TYPE (index))));
4809 changed = true;
4811 else if (no_slot)
4812 changed = true;
4813 else
4815 if (TREE_CODE (type) == UNION_TYPE
4816 && (*p)->last().index != index)
4817 /* The initializer erroneously changed the active union member that
4818 we're initializing. */
4819 gcc_assert (*non_constant_p);
4820 else
4822 /* The initializer might have mutated the underlying CONSTRUCTOR,
4823 so recompute the location of the target constructer_elt. */
4824 constructor_elt *cep
4825 = get_or_insert_ctor_field (ctx->ctor, index, pos_hint);
4826 cep->value = elt;
4829 /* Adding or replacing an element might change the ctor's flags. */
4830 TREE_CONSTANT (ctx->ctor) = constant_p;
4831 TREE_SIDE_EFFECTS (ctx->ctor) = side_effects_p;
4834 if (*non_constant_p || !changed)
4835 return t;
4836 t = ctx->ctor;
4837 /* We're done building this CONSTRUCTOR, so now we can interpret an
4838 element without an explicit initializer as value-initialized. */
4839 CONSTRUCTOR_NO_CLEARING (t) = false;
4840 TREE_CONSTANT (t) = constant_p;
4841 TREE_SIDE_EFFECTS (t) = side_effects_p;
4842 if (VECTOR_TYPE_P (type))
4843 t = fold (t);
4844 return t;
4847 /* Subroutine of cxx_eval_constant_expression.
4848 The expression tree T is a VEC_INIT_EXPR which denotes the desired
4849 initialization of a non-static data member of array type. Reduce it to a
4850 CONSTRUCTOR.
4852 Note that apart from value-initialization (when VALUE_INIT is true),
4853 this is only intended to support value-initialization and the
4854 initializations done by defaulted constructors for classes with
4855 non-static data members of array type. In this case, VEC_INIT_EXPR_INIT
4856 will either be NULL_TREE for the default constructor, or a COMPONENT_REF
4857 for the copy/move constructor. */
4859 static tree
4860 cxx_eval_vec_init_1 (const constexpr_ctx *ctx, tree atype, tree init,
4861 bool value_init, bool lval,
4862 bool *non_constant_p, bool *overflow_p)
4864 tree elttype = TREE_TYPE (atype);
4865 verify_ctor_sanity (ctx, atype);
4866 vec<constructor_elt, va_gc> **p = &CONSTRUCTOR_ELTS (ctx->ctor);
4867 bool pre_init = false;
4868 unsigned HOST_WIDE_INT i;
4869 tsubst_flags_t complain = ctx->quiet ? tf_none : tf_warning_or_error;
4871 if (init && TREE_CODE (init) == CONSTRUCTOR)
4872 return cxx_eval_bare_aggregate (ctx, init, lval,
4873 non_constant_p, overflow_p);
4875 /* For the default constructor, build up a call to the default
4876 constructor of the element type. We only need to handle class types
4877 here, as for a constructor to be constexpr, all members must be
4878 initialized, which for a defaulted default constructor means they must
4879 be of a class type with a constexpr default constructor. */
4880 if (TREE_CODE (elttype) == ARRAY_TYPE)
4881 /* We only do this at the lowest level. */;
4882 else if (value_init)
4884 init = build_value_init (elttype, complain);
4885 pre_init = true;
4887 else if (!init)
4889 releasing_vec argvec;
4890 init = build_special_member_call (NULL_TREE, complete_ctor_identifier,
4891 &argvec, elttype, LOOKUP_NORMAL,
4892 complain);
4893 init = build_aggr_init_expr (elttype, init);
4894 pre_init = true;
4897 bool zeroed_out = false;
4898 if (!CONSTRUCTOR_NO_CLEARING (ctx->ctor))
4900 /* We're initializing an array object that had been zero-initialized
4901 earlier. Truncate ctx->ctor, and propagate its zeroed state by
4902 clearing CONSTRUCTOR_NO_CLEARING on each of the aggregate element
4903 initializers we append to it. */
4904 gcc_checking_assert (initializer_zerop (ctx->ctor));
4905 zeroed_out = true;
4906 vec_safe_truncate (*p, 0);
4909 tree nelts = get_array_or_vector_nelts (ctx, atype, non_constant_p,
4910 overflow_p);
4911 unsigned HOST_WIDE_INT max = tree_to_uhwi (nelts);
4912 for (i = 0; i < max; ++i)
4914 tree idx = build_int_cst (size_type_node, i);
4915 tree eltinit;
4916 bool reuse = false;
4917 constexpr_ctx new_ctx;
4918 init_subob_ctx (ctx, new_ctx, idx, pre_init ? init : elttype);
4919 if (new_ctx.ctor != ctx->ctor)
4921 if (zeroed_out)
4922 CONSTRUCTOR_NO_CLEARING (new_ctx.ctor) = false;
4923 CONSTRUCTOR_APPEND_ELT (*p, idx, new_ctx.ctor);
4925 if (TREE_CODE (elttype) == ARRAY_TYPE)
4927 /* A multidimensional array; recurse. */
4928 if (value_init || init == NULL_TREE)
4930 eltinit = NULL_TREE;
4931 reuse = i == 0;
4933 else
4934 eltinit = cp_build_array_ref (input_location, init, idx, complain);
4935 eltinit = cxx_eval_vec_init_1 (&new_ctx, elttype, eltinit, value_init,
4936 lval,
4937 non_constant_p, overflow_p);
4939 else if (pre_init)
4941 /* Initializing an element using value or default initialization
4942 we just pre-built above. */
4943 if (init == void_node)
4944 /* Trivial default-init, don't do anything to the CONSTRUCTOR. */
4945 return ctx->ctor;
4946 eltinit = cxx_eval_constant_expression (&new_ctx, init, lval,
4947 non_constant_p, overflow_p);
4948 reuse = i == 0;
4950 else
4952 /* Copying an element. */
4953 gcc_assert (same_type_ignoring_top_level_qualifiers_p
4954 (atype, TREE_TYPE (init)));
4955 eltinit = cp_build_array_ref (input_location, init, idx, complain);
4956 if (!lvalue_p (init))
4957 eltinit = move (eltinit);
4958 eltinit = force_rvalue (eltinit, complain);
4959 eltinit = cxx_eval_constant_expression (&new_ctx, eltinit, lval,
4960 non_constant_p, overflow_p);
4962 if (*non_constant_p)
4963 break;
4964 if (new_ctx.ctor != ctx->ctor)
4966 /* We appended this element above; update the value. */
4967 gcc_assert ((*p)->last().index == idx);
4968 (*p)->last().value = eltinit;
4970 else
4971 CONSTRUCTOR_APPEND_ELT (*p, idx, eltinit);
4972 /* Reuse the result of cxx_eval_constant_expression call
4973 from the first iteration to all others if it is a constant
4974 initializer that doesn't require relocations. */
4975 if (reuse
4976 && max > 1
4977 && (eltinit == NULL_TREE
4978 || (initializer_constant_valid_p (eltinit, TREE_TYPE (eltinit))
4979 == null_pointer_node)))
4981 if (new_ctx.ctor != ctx->ctor)
4982 eltinit = new_ctx.ctor;
4983 tree range = build2 (RANGE_EXPR, size_type_node,
4984 build_int_cst (size_type_node, 1),
4985 build_int_cst (size_type_node, max - 1));
4986 CONSTRUCTOR_APPEND_ELT (*p, range, unshare_constructor (eltinit));
4987 break;
4989 else if (i == 0)
4990 vec_safe_reserve (*p, max);
4993 if (!*non_constant_p)
4995 init = ctx->ctor;
4996 CONSTRUCTOR_NO_CLEARING (init) = false;
4998 return init;
5001 static tree
5002 cxx_eval_vec_init (const constexpr_ctx *ctx, tree t,
5003 bool lval,
5004 bool *non_constant_p, bool *overflow_p)
5006 tree atype = TREE_TYPE (t);
5007 tree init = VEC_INIT_EXPR_INIT (t);
5008 bool value_init = VEC_INIT_EXPR_VALUE_INIT (t);
5009 if (!init || !BRACE_ENCLOSED_INITIALIZER_P (init))
5011 else if (CONSTRUCTOR_NELTS (init) == 0
5012 && !CP_AGGREGATE_TYPE_P (strip_array_types (atype)))
5014 /* Handle {} as value-init. */
5015 init = NULL_TREE;
5016 value_init = true;
5018 else
5020 /* This is a more complicated case, like needing to loop over trailing
5021 elements; call build_vec_init and evaluate the result. */
5022 tsubst_flags_t complain = ctx->quiet ? tf_none : tf_warning_or_error;
5023 constexpr_ctx new_ctx = *ctx;
5024 if (!ctx->object)
5026 /* We want to have an initialization target for an VEC_INIT_EXPR.
5027 If we don't already have one in CTX, use the VEC_INIT_EXPR_SLOT. */
5028 new_ctx.object = VEC_INIT_EXPR_SLOT (t);
5029 tree ctor = new_ctx.ctor = build_constructor (atype, NULL);
5030 CONSTRUCTOR_NO_CLEARING (ctor) = true;
5031 ctx->global->values.put (new_ctx.object, ctor);
5032 ctx = &new_ctx;
5034 init = expand_vec_init_expr (ctx->object, t, complain);
5035 return cxx_eval_constant_expression (ctx, init, lval, non_constant_p,
5036 overflow_p);
5038 tree r = cxx_eval_vec_init_1 (ctx, atype, init, value_init,
5039 lval, non_constant_p, overflow_p);
5040 if (*non_constant_p)
5041 return t;
5042 else
5043 return r;
5046 /* Like same_type_ignoring_top_level_qualifiers_p, but also handle the case
5047 where the desired type is an array of unknown bounds because the variable
5048 has had its bounds deduced since the wrapping expression was created. */
5050 static bool
5051 same_type_ignoring_tlq_and_bounds_p (tree type1, tree type2)
5053 while (TREE_CODE (type1) == ARRAY_TYPE
5054 && TREE_CODE (type2) == ARRAY_TYPE
5055 && (!TYPE_DOMAIN (type1) || !TYPE_DOMAIN (type2)))
5057 type1 = TREE_TYPE (type1);
5058 type2 = TREE_TYPE (type2);
5060 return same_type_ignoring_top_level_qualifiers_p (type1, type2);
5063 /* Try to determine the currently active union member for an expression
5064 with UNION_TYPE. If it can be determined, return the FIELD_DECL,
5065 otherwise return NULL_TREE. */
5067 static tree
5068 cxx_union_active_member (const constexpr_ctx *ctx, tree t)
5070 constexpr_ctx new_ctx = *ctx;
5071 new_ctx.quiet = true;
5072 bool non_constant_p = false, overflow_p = false;
5073 tree ctor = cxx_eval_constant_expression (&new_ctx, t, false,
5074 &non_constant_p,
5075 &overflow_p);
5076 if (TREE_CODE (ctor) == CONSTRUCTOR
5077 && CONSTRUCTOR_NELTS (ctor) == 1
5078 && CONSTRUCTOR_ELT (ctor, 0)->index
5079 && TREE_CODE (CONSTRUCTOR_ELT (ctor, 0)->index) == FIELD_DECL)
5080 return CONSTRUCTOR_ELT (ctor, 0)->index;
5081 return NULL_TREE;
5084 /* Helper function for cxx_fold_indirect_ref_1, called recursively. */
5086 static tree
5087 cxx_fold_indirect_ref_1 (const constexpr_ctx *ctx, location_t loc, tree type,
5088 tree op, unsigned HOST_WIDE_INT off, bool *empty_base)
5090 tree optype = TREE_TYPE (op);
5091 unsigned HOST_WIDE_INT const_nunits;
5092 if (off == 0 && similar_type_p (optype, type))
5093 return op;
5094 else if (TREE_CODE (optype) == COMPLEX_TYPE
5095 && similar_type_p (type, TREE_TYPE (optype)))
5097 /* *(foo *)&complexfoo => __real__ complexfoo */
5098 if (off == 0)
5099 return build1_loc (loc, REALPART_EXPR, type, op);
5100 /* ((foo*)&complexfoo)[1] => __imag__ complexfoo */
5101 else if (tree_to_uhwi (TYPE_SIZE_UNIT (type)) == off)
5102 return build1_loc (loc, IMAGPART_EXPR, type, op);
5104 /* ((foo*)&vectorfoo)[x] => BIT_FIELD_REF<vectorfoo,...> */
5105 else if (VECTOR_TYPE_P (optype)
5106 && similar_type_p (type, TREE_TYPE (optype))
5107 && TYPE_VECTOR_SUBPARTS (optype).is_constant (&const_nunits))
5109 unsigned HOST_WIDE_INT part_width = tree_to_uhwi (TYPE_SIZE_UNIT (type));
5110 unsigned HOST_WIDE_INT max_offset = part_width * const_nunits;
5111 if (off < max_offset && off % part_width == 0)
5113 tree index = bitsize_int (off * BITS_PER_UNIT);
5114 return build3_loc (loc, BIT_FIELD_REF, type, op,
5115 TYPE_SIZE (type), index);
5118 /* ((foo *)&fooarray)[x] => fooarray[x] */
5119 else if (TREE_CODE (optype) == ARRAY_TYPE
5120 && tree_fits_uhwi_p (TYPE_SIZE_UNIT (TREE_TYPE (optype)))
5121 && !integer_zerop (TYPE_SIZE_UNIT (TREE_TYPE (optype))))
5123 tree type_domain = TYPE_DOMAIN (optype);
5124 tree min_val = size_zero_node;
5125 if (type_domain && TYPE_MIN_VALUE (type_domain))
5126 min_val = TYPE_MIN_VALUE (type_domain);
5127 unsigned HOST_WIDE_INT el_sz
5128 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (optype)));
5129 unsigned HOST_WIDE_INT idx = off / el_sz;
5130 unsigned HOST_WIDE_INT rem = off % el_sz;
5131 if (tree_fits_uhwi_p (min_val))
5133 tree index = size_int (idx + tree_to_uhwi (min_val));
5134 op = build4_loc (loc, ARRAY_REF, TREE_TYPE (optype), op, index,
5135 NULL_TREE, NULL_TREE);
5136 return cxx_fold_indirect_ref_1 (ctx, loc, type, op, rem,
5137 empty_base);
5140 /* ((foo *)&struct_with_foo_field)[x] => COMPONENT_REF */
5141 else if (TREE_CODE (optype) == RECORD_TYPE
5142 || TREE_CODE (optype) == UNION_TYPE)
5144 if (TREE_CODE (optype) == UNION_TYPE)
5145 /* For unions prefer the currently active member. */
5146 if (tree field = cxx_union_active_member (ctx, op))
5148 unsigned HOST_WIDE_INT el_sz
5149 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (field)));
5150 if (off < el_sz)
5152 tree cop = build3 (COMPONENT_REF, TREE_TYPE (field),
5153 op, field, NULL_TREE);
5154 if (tree ret = cxx_fold_indirect_ref_1 (ctx, loc, type, cop,
5155 off, empty_base))
5156 return ret;
5159 for (tree field = TYPE_FIELDS (optype);
5160 field; field = DECL_CHAIN (field))
5161 if (TREE_CODE (field) == FIELD_DECL
5162 && TREE_TYPE (field) != error_mark_node
5163 && tree_fits_uhwi_p (TYPE_SIZE_UNIT (TREE_TYPE (field))))
5165 tree pos = byte_position (field);
5166 if (!tree_fits_uhwi_p (pos))
5167 continue;
5168 unsigned HOST_WIDE_INT upos = tree_to_uhwi (pos);
5169 unsigned HOST_WIDE_INT el_sz
5170 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (field)));
5171 if (upos <= off && off < upos + el_sz)
5173 tree cop = build3 (COMPONENT_REF, TREE_TYPE (field),
5174 op, field, NULL_TREE);
5175 if (tree ret = cxx_fold_indirect_ref_1 (ctx, loc, type, cop,
5176 off - upos,
5177 empty_base))
5178 return ret;
5181 /* Also handle conversion to an empty base class, which
5182 is represented with a NOP_EXPR. */
5183 if (is_empty_class (type)
5184 && CLASS_TYPE_P (optype)
5185 && DERIVED_FROM_P (type, optype))
5187 *empty_base = true;
5188 return op;
5192 return NULL_TREE;
5195 /* A less strict version of fold_indirect_ref_1, which requires cv-quals to
5196 match. We want to be less strict for simple *& folding; if we have a
5197 non-const temporary that we access through a const pointer, that should
5198 work. We handle this here rather than change fold_indirect_ref_1
5199 because we're dealing with things like ADDR_EXPR of INTEGER_CST which
5200 don't really make sense outside of constant expression evaluation. Also
5201 we want to allow folding to COMPONENT_REF, which could cause trouble
5202 with TBAA in fold_indirect_ref_1. */
5204 static tree
5205 cxx_fold_indirect_ref (const constexpr_ctx *ctx, location_t loc, tree type,
5206 tree op0, bool *empty_base)
5208 tree sub = op0;
5209 tree subtype;
5210 poly_uint64 const_op01;
5212 /* STRIP_NOPS, but stop if REINTERPRET_CAST_P. */
5213 while (CONVERT_EXPR_P (sub) || TREE_CODE (sub) == NON_LVALUE_EXPR
5214 || TREE_CODE (sub) == VIEW_CONVERT_EXPR)
5216 if (TREE_CODE (sub) == NOP_EXPR
5217 && REINTERPRET_CAST_P (sub))
5218 return NULL_TREE;
5219 sub = TREE_OPERAND (sub, 0);
5222 subtype = TREE_TYPE (sub);
5223 if (!INDIRECT_TYPE_P (subtype))
5224 return NULL_TREE;
5226 /* Canonicalizes the given OBJ/OFF pair by iteratively absorbing
5227 the innermost component into the offset until it would make the
5228 offset positive, so that cxx_fold_indirect_ref_1 can identify
5229 more folding opportunities. */
5230 auto canonicalize_obj_off = [] (tree& obj, tree& off) {
5231 while (TREE_CODE (obj) == COMPONENT_REF
5232 && (tree_int_cst_sign_bit (off) || integer_zerop (off)))
5234 tree field = TREE_OPERAND (obj, 1);
5235 tree pos = byte_position (field);
5236 if (integer_zerop (off) && integer_nonzerop (pos))
5237 /* If the offset is already 0, keep going as long as the
5238 component is at position 0. */
5239 break;
5240 off = int_const_binop (PLUS_EXPR, off, pos);
5241 obj = TREE_OPERAND (obj, 0);
5245 if (TREE_CODE (sub) == ADDR_EXPR)
5247 tree op = TREE_OPERAND (sub, 0);
5248 tree optype = TREE_TYPE (op);
5250 /* *&CONST_DECL -> to the value of the const decl. */
5251 if (TREE_CODE (op) == CONST_DECL)
5252 return DECL_INITIAL (op);
5253 /* *&p => p; make sure to handle *&"str"[cst] here. */
5254 if (similar_type_p (optype, type))
5256 tree fop = fold_read_from_constant_string (op);
5257 if (fop)
5258 return fop;
5259 else
5260 return op;
5262 else
5264 tree off = integer_zero_node;
5265 canonicalize_obj_off (op, off);
5266 gcc_assert (integer_zerop (off));
5267 return cxx_fold_indirect_ref_1 (ctx, loc, type, op, 0, empty_base);
5270 else if (TREE_CODE (sub) == POINTER_PLUS_EXPR
5271 && tree_fits_uhwi_p (TREE_OPERAND (sub, 1)))
5273 tree op00 = TREE_OPERAND (sub, 0);
5274 tree off = TREE_OPERAND (sub, 1);
5276 STRIP_NOPS (op00);
5277 if (TREE_CODE (op00) == ADDR_EXPR)
5279 tree obj = TREE_OPERAND (op00, 0);
5280 canonicalize_obj_off (obj, off);
5281 return cxx_fold_indirect_ref_1 (ctx, loc, type, obj,
5282 tree_to_uhwi (off), empty_base);
5285 /* *(foo *)fooarrptr => (*fooarrptr)[0] */
5286 else if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
5287 && similar_type_p (type, TREE_TYPE (TREE_TYPE (subtype))))
5289 tree type_domain;
5290 tree min_val = size_zero_node;
5291 tree newsub
5292 = cxx_fold_indirect_ref (ctx, loc, TREE_TYPE (subtype), sub, NULL);
5293 if (newsub)
5294 sub = newsub;
5295 else
5296 sub = build1_loc (loc, INDIRECT_REF, TREE_TYPE (subtype), sub);
5297 type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
5298 if (type_domain && TYPE_MIN_VALUE (type_domain))
5299 min_val = TYPE_MIN_VALUE (type_domain);
5300 return build4_loc (loc, ARRAY_REF, type, sub, min_val, NULL_TREE,
5301 NULL_TREE);
5304 return NULL_TREE;
5307 static tree
5308 cxx_eval_indirect_ref (const constexpr_ctx *ctx, tree t,
5309 bool lval,
5310 bool *non_constant_p, bool *overflow_p)
5312 tree orig_op0 = TREE_OPERAND (t, 0);
5313 bool empty_base = false;
5315 /* We can handle a MEM_REF like an INDIRECT_REF, if MEM_REF's second
5316 operand is an integer-zero. Otherwise reject the MEM_REF for now. */
5318 if (TREE_CODE (t) == MEM_REF
5319 && (!TREE_OPERAND (t, 1) || !integer_zerop (TREE_OPERAND (t, 1))))
5321 gcc_assert (ctx->quiet);
5322 *non_constant_p = true;
5323 return t;
5326 /* First try to simplify it directly. */
5327 tree r = cxx_fold_indirect_ref (ctx, EXPR_LOCATION (t), TREE_TYPE (t),
5328 orig_op0, &empty_base);
5329 if (!r)
5331 /* If that didn't work, evaluate the operand first. */
5332 tree op0 = cxx_eval_constant_expression (ctx, orig_op0,
5333 /*lval*/false, non_constant_p,
5334 overflow_p);
5335 /* Don't VERIFY_CONSTANT here. */
5336 if (*non_constant_p)
5337 return t;
5339 if (!lval && integer_zerop (op0))
5341 if (!ctx->quiet)
5342 error ("dereferencing a null pointer");
5343 *non_constant_p = true;
5344 return t;
5347 r = cxx_fold_indirect_ref (ctx, EXPR_LOCATION (t), TREE_TYPE (t), op0,
5348 &empty_base);
5349 if (r == NULL_TREE)
5351 /* We couldn't fold to a constant value. Make sure it's not
5352 something we should have been able to fold. */
5353 tree sub = op0;
5354 STRIP_NOPS (sub);
5355 if (TREE_CODE (sub) == ADDR_EXPR)
5357 gcc_assert (!similar_type_p
5358 (TREE_TYPE (TREE_TYPE (sub)), TREE_TYPE (t)));
5359 /* DR 1188 says we don't have to deal with this. */
5360 if (!ctx->quiet)
5361 error_at (cp_expr_loc_or_input_loc (t),
5362 "accessing value of %qE through a %qT glvalue in a "
5363 "constant expression", build_fold_indirect_ref (sub),
5364 TREE_TYPE (t));
5365 *non_constant_p = true;
5366 return t;
5369 if (lval && op0 != orig_op0)
5370 return build1 (INDIRECT_REF, TREE_TYPE (t), op0);
5371 if (!lval)
5372 VERIFY_CONSTANT (t);
5373 return t;
5377 r = cxx_eval_constant_expression (ctx, r,
5378 lval, non_constant_p, overflow_p);
5379 if (*non_constant_p)
5380 return t;
5382 /* If we're pulling out the value of an empty base, just return an empty
5383 CONSTRUCTOR. */
5384 if (empty_base && !lval)
5386 r = build_constructor (TREE_TYPE (t), NULL);
5387 TREE_CONSTANT (r) = true;
5390 return r;
5393 /* Complain about R, a VAR_DECL, not being usable in a constant expression.
5394 Shared between potential_constant_expression and
5395 cxx_eval_constant_expression. */
5397 static void
5398 non_const_var_error (location_t loc, tree r)
5400 auto_diagnostic_group d;
5401 tree type = TREE_TYPE (r);
5402 if (DECL_NAME (r) == heap_uninit_identifier
5403 || DECL_NAME (r) == heap_identifier
5404 || DECL_NAME (r) == heap_vec_uninit_identifier
5405 || DECL_NAME (r) == heap_vec_identifier)
5407 error_at (loc, "the content of uninitialized storage is not usable "
5408 "in a constant expression");
5409 inform (DECL_SOURCE_LOCATION (r), "allocated here");
5410 return;
5412 if (DECL_NAME (r) == heap_deleted_identifier)
5414 error_at (loc, "use of allocated storage after deallocation in a "
5415 "constant expression");
5416 inform (DECL_SOURCE_LOCATION (r), "allocated here");
5417 return;
5419 error_at (loc, "the value of %qD is not usable in a constant "
5420 "expression", r);
5421 /* Avoid error cascade. */
5422 if (DECL_INITIAL (r) == error_mark_node)
5423 return;
5424 if (DECL_DECLARED_CONSTEXPR_P (r))
5425 inform (DECL_SOURCE_LOCATION (r),
5426 "%qD used in its own initializer", r);
5427 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5429 if (!CP_TYPE_CONST_P (type))
5430 inform (DECL_SOURCE_LOCATION (r),
5431 "%q#D is not const", r);
5432 else if (CP_TYPE_VOLATILE_P (type))
5433 inform (DECL_SOURCE_LOCATION (r),
5434 "%q#D is volatile", r);
5435 else if (!DECL_INITIAL (r)
5436 || !TREE_CONSTANT (DECL_INITIAL (r))
5437 || !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r))
5438 inform (DECL_SOURCE_LOCATION (r),
5439 "%qD was not initialized with a constant "
5440 "expression", r);
5441 else
5442 gcc_unreachable ();
5444 else if (TYPE_REF_P (type))
5445 inform (DECL_SOURCE_LOCATION (r),
5446 "%qD was not initialized with a constant "
5447 "expression", r);
5448 else
5450 if (cxx_dialect >= cxx11 && !DECL_DECLARED_CONSTEXPR_P (r))
5451 inform (DECL_SOURCE_LOCATION (r),
5452 "%qD was not declared %<constexpr%>", r);
5453 else
5454 inform (DECL_SOURCE_LOCATION (r),
5455 "%qD does not have integral or enumeration type",
5460 /* Subroutine of cxx_eval_constant_expression.
5461 Like cxx_eval_unary_expression, except for trinary expressions. */
5463 static tree
5464 cxx_eval_trinary_expression (const constexpr_ctx *ctx, tree t,
5465 bool lval,
5466 bool *non_constant_p, bool *overflow_p)
5468 int i;
5469 tree args[3];
5470 tree val;
5472 for (i = 0; i < 3; i++)
5474 args[i] = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, i),
5475 lval,
5476 non_constant_p, overflow_p);
5477 VERIFY_CONSTANT (args[i]);
5480 val = fold_ternary_loc (EXPR_LOCATION (t), TREE_CODE (t), TREE_TYPE (t),
5481 args[0], args[1], args[2]);
5482 if (val == NULL_TREE)
5483 return t;
5484 VERIFY_CONSTANT (val);
5485 return val;
5488 /* True if T was declared in a function declared to be constexpr, and
5489 therefore potentially constant in C++14. */
5491 bool
5492 var_in_constexpr_fn (tree t)
5494 tree ctx = DECL_CONTEXT (t);
5495 return (ctx && TREE_CODE (ctx) == FUNCTION_DECL
5496 && DECL_DECLARED_CONSTEXPR_P (ctx));
5499 /* True if a function might be constexpr: either a function that was
5500 declared constexpr, or a C++17 lambda op(). */
5502 bool
5503 maybe_constexpr_fn (tree t)
5505 return (DECL_DECLARED_CONSTEXPR_P (t)
5506 || (cxx_dialect >= cxx17 && LAMBDA_FUNCTION_P (t))
5507 || (flag_implicit_constexpr
5508 && DECL_DECLARED_INLINE_P (STRIP_TEMPLATE (t))));
5511 /* True if T was declared in a function that might be constexpr: either a
5512 function that was declared constexpr, or a C++17 lambda op(). */
5514 bool
5515 var_in_maybe_constexpr_fn (tree t)
5517 return (DECL_FUNCTION_SCOPE_P (t)
5518 && maybe_constexpr_fn (DECL_CONTEXT (t)));
5521 /* We're assigning INIT to TARGET. In do_build_copy_constructor and
5522 build_over_call we implement trivial copy of a class with tail padding using
5523 assignment of character arrays, which is valid in normal code, but not in
5524 constexpr evaluation. We don't need to worry about clobbering tail padding
5525 in constexpr evaluation, so strip the type punning. */
5527 static void
5528 maybe_simplify_trivial_copy (tree &target, tree &init)
5530 if (TREE_CODE (target) == MEM_REF
5531 && TREE_CODE (init) == MEM_REF
5532 && TREE_TYPE (target) == TREE_TYPE (init)
5533 && TREE_CODE (TREE_TYPE (target)) == ARRAY_TYPE
5534 && TREE_TYPE (TREE_TYPE (target)) == unsigned_char_type_node)
5536 target = build_fold_indirect_ref (TREE_OPERAND (target, 0));
5537 init = build_fold_indirect_ref (TREE_OPERAND (init, 0));
5541 /* Returns true if REF, which is a COMPONENT_REF, has any fields
5542 of constant type. This does not check for 'mutable', so the
5543 caller is expected to be mindful of that. */
5545 static bool
5546 cref_has_const_field (tree ref)
5548 while (TREE_CODE (ref) == COMPONENT_REF)
5550 if (CP_TYPE_CONST_P (TREE_TYPE (TREE_OPERAND (ref, 1))))
5551 return true;
5552 ref = TREE_OPERAND (ref, 0);
5554 return false;
5557 /* Return true if we are modifying something that is const during constant
5558 expression evaluation. CODE is the code of the statement, OBJ is the
5559 object in question, MUTABLE_P is true if one of the subobjects were
5560 declared mutable. */
5562 static bool
5563 modifying_const_object_p (tree_code code, tree obj, bool mutable_p)
5565 /* If this is initialization, there's no problem. */
5566 if (code != MODIFY_EXPR)
5567 return false;
5569 /* [basic.type.qualifier] "A const object is an object of type
5570 const T or a non-mutable subobject of a const object." */
5571 if (mutable_p)
5572 return false;
5574 if (TREE_READONLY (obj))
5575 return true;
5577 if (CP_TYPE_CONST_P (TREE_TYPE (obj)))
5579 /* Although a COMPONENT_REF may have a const type, we should
5580 only consider it modifying a const object when any of the
5581 field components is const. This can happen when using
5582 constructs such as const_cast<const T &>(m), making something
5583 const even though it wasn't declared const. */
5584 if (TREE_CODE (obj) == COMPONENT_REF)
5585 return cref_has_const_field (obj);
5586 else
5587 return true;
5590 return false;
5593 /* Evaluate an INIT_EXPR or MODIFY_EXPR. */
5595 static tree
5596 cxx_eval_store_expression (const constexpr_ctx *ctx, tree t,
5597 bool lval,
5598 bool *non_constant_p, bool *overflow_p)
5600 constexpr_ctx new_ctx = *ctx;
5602 tree init = TREE_OPERAND (t, 1);
5603 if (TREE_CLOBBER_P (init))
5604 /* Just ignore clobbers. */
5605 return void_node;
5607 /* First we figure out where we're storing to. */
5608 tree target = TREE_OPERAND (t, 0);
5610 maybe_simplify_trivial_copy (target, init);
5612 tree type = TREE_TYPE (target);
5613 bool preeval = SCALAR_TYPE_P (type) || TREE_CODE (t) == MODIFY_EXPR;
5614 if (preeval)
5616 /* Evaluate the value to be stored without knowing what object it will be
5617 stored in, so that any side-effects happen first. */
5618 if (!SCALAR_TYPE_P (type))
5619 new_ctx.ctor = new_ctx.object = NULL_TREE;
5620 init = cxx_eval_constant_expression (&new_ctx, init, false,
5621 non_constant_p, overflow_p);
5622 if (*non_constant_p)
5623 return t;
5626 bool evaluated = false;
5627 if (lval)
5629 /* If we want to return a reference to the target, we need to evaluate it
5630 as a whole; otherwise, only evaluate the innermost piece to avoid
5631 building up unnecessary *_REFs. */
5632 target = cxx_eval_constant_expression (ctx, target, true,
5633 non_constant_p, overflow_p);
5634 evaluated = true;
5635 if (*non_constant_p)
5636 return t;
5639 /* Find the underlying variable. */
5640 releasing_vec refs;
5641 tree object = NULL_TREE;
5642 /* If we're modifying a const object, save it. */
5643 tree const_object_being_modified = NULL_TREE;
5644 bool mutable_p = false;
5645 for (tree probe = target; object == NULL_TREE; )
5647 switch (TREE_CODE (probe))
5649 case BIT_FIELD_REF:
5650 case COMPONENT_REF:
5651 case ARRAY_REF:
5653 tree ob = TREE_OPERAND (probe, 0);
5654 tree elt = TREE_OPERAND (probe, 1);
5655 if (TREE_CODE (elt) == FIELD_DECL && DECL_MUTABLE_P (elt))
5656 mutable_p = true;
5657 if (TREE_CODE (probe) == ARRAY_REF)
5659 elt = eval_and_check_array_index (ctx, probe, false,
5660 non_constant_p, overflow_p);
5661 if (*non_constant_p)
5662 return t;
5664 /* We don't check modifying_const_object_p for ARRAY_REFs. Given
5665 "int a[10]", an ARRAY_REF "a[2]" can be "const int", even though
5666 the array isn't const. Instead, check "a" in the next iteration;
5667 that will detect modifying "const int a[10]". */
5668 else if (evaluated
5669 && modifying_const_object_p (TREE_CODE (t), probe,
5670 mutable_p)
5671 && const_object_being_modified == NULL_TREE)
5672 const_object_being_modified = probe;
5673 vec_safe_push (refs, elt);
5674 vec_safe_push (refs, TREE_TYPE (probe));
5675 probe = ob;
5677 break;
5679 default:
5680 if (evaluated)
5681 object = probe;
5682 else
5684 probe = cxx_eval_constant_expression (ctx, probe, true,
5685 non_constant_p, overflow_p);
5686 evaluated = true;
5687 if (*non_constant_p)
5688 return t;
5690 break;
5694 if (modifying_const_object_p (TREE_CODE (t), object, mutable_p)
5695 && const_object_being_modified == NULL_TREE)
5696 const_object_being_modified = object;
5698 /* And then find/build up our initializer for the path to the subobject
5699 we're initializing. */
5700 tree *valp;
5701 if (DECL_P (object))
5702 valp = ctx->global->values.get (object);
5703 else
5704 valp = NULL;
5705 if (!valp)
5707 /* A constant-expression cannot modify objects from outside the
5708 constant-expression. */
5709 if (!ctx->quiet)
5710 error ("modification of %qE is not a constant expression", object);
5711 *non_constant_p = true;
5712 return t;
5714 type = TREE_TYPE (object);
5715 bool no_zero_init = true;
5717 releasing_vec ctors, indexes;
5718 auto_vec<int> index_pos_hints;
5719 bool activated_union_member_p = false;
5720 bool empty_base = false;
5721 while (!refs->is_empty ())
5723 if (*valp == NULL_TREE)
5725 *valp = build_constructor (type, NULL);
5726 CONSTRUCTOR_NO_CLEARING (*valp) = no_zero_init;
5728 else if (TREE_CODE (*valp) == STRING_CST)
5730 /* An array was initialized with a string constant, and now
5731 we're writing into one of its elements. Explode the
5732 single initialization into a set of element
5733 initializations. */
5734 gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
5736 tree string = *valp;
5737 tree elt_type = TREE_TYPE (type);
5738 unsigned chars_per_elt = (TYPE_PRECISION (elt_type)
5739 / TYPE_PRECISION (char_type_node));
5740 unsigned num_elts = TREE_STRING_LENGTH (string) / chars_per_elt;
5741 tree ary_ctor = build_constructor (type, NULL);
5743 vec_safe_reserve (CONSTRUCTOR_ELTS (ary_ctor), num_elts);
5744 for (unsigned ix = 0; ix != num_elts; ix++)
5746 constructor_elt elt =
5748 build_int_cst (size_type_node, ix),
5749 extract_string_elt (string, chars_per_elt, ix)
5751 CONSTRUCTOR_ELTS (ary_ctor)->quick_push (elt);
5754 *valp = ary_ctor;
5757 /* If the value of object is already zero-initialized, any new ctors for
5758 subobjects will also be zero-initialized. */
5759 no_zero_init = CONSTRUCTOR_NO_CLEARING (*valp);
5761 enum tree_code code = TREE_CODE (type);
5762 tree reftype = refs->pop();
5763 tree index = refs->pop();
5765 if (code == RECORD_TYPE && is_empty_field (index))
5766 /* Don't build a sub-CONSTRUCTOR for an empty base or field, as they
5767 have no data and might have an offset lower than previously declared
5768 fields, which confuses the middle-end. The code below will notice
5769 that we don't have a CONSTRUCTOR for our inner target and just
5770 return init. */
5772 empty_base = true;
5773 break;
5776 type = reftype;
5778 if (code == UNION_TYPE && CONSTRUCTOR_NELTS (*valp)
5779 && CONSTRUCTOR_ELT (*valp, 0)->index != index)
5781 if (cxx_dialect < cxx20)
5783 if (!ctx->quiet)
5784 error_at (cp_expr_loc_or_input_loc (t),
5785 "change of the active member of a union "
5786 "from %qD to %qD",
5787 CONSTRUCTOR_ELT (*valp, 0)->index,
5788 index);
5789 *non_constant_p = true;
5791 else if (TREE_CODE (t) == MODIFY_EXPR
5792 && CONSTRUCTOR_NO_CLEARING (*valp))
5794 /* Diagnose changing the active union member while the union
5795 is in the process of being initialized. */
5796 if (!ctx->quiet)
5797 error_at (cp_expr_loc_or_input_loc (t),
5798 "change of the active member of a union "
5799 "from %qD to %qD during initialization",
5800 CONSTRUCTOR_ELT (*valp, 0)->index,
5801 index);
5802 *non_constant_p = true;
5804 no_zero_init = true;
5807 vec_safe_push (ctors, *valp);
5808 vec_safe_push (indexes, index);
5810 constructor_elt *cep
5811 = get_or_insert_ctor_field (*valp, index);
5812 index_pos_hints.safe_push (cep - CONSTRUCTOR_ELTS (*valp)->begin());
5814 if (code == UNION_TYPE)
5815 activated_union_member_p = true;
5817 valp = &cep->value;
5820 /* Detect modifying a constant object in constexpr evaluation.
5821 We have found a const object that is being modified. Figure out
5822 if we need to issue an error. Consider
5824 struct A {
5825 int n;
5826 constexpr A() : n(1) { n = 2; } // #1
5828 struct B {
5829 const A a;
5830 constexpr B() { a.n = 3; } // #2
5832 constexpr B b{};
5834 #1 is OK, since we're modifying an object under construction, but
5835 #2 is wrong, since "a" is const and has been fully constructed.
5836 To track it, we use the TREE_READONLY bit in the object's CONSTRUCTOR
5837 which means that the object is read-only. For the example above, the
5838 *ctors stack at the point of #2 will look like:
5840 ctors[0] = {.a={.n=2}} TREE_READONLY = 0
5841 ctors[1] = {.n=2} TREE_READONLY = 1
5843 and we're modifying "b.a", so we search the stack and see if the
5844 constructor for "b.a" has already run. */
5845 if (const_object_being_modified)
5847 bool fail = false;
5848 tree const_objtype
5849 = strip_array_types (TREE_TYPE (const_object_being_modified));
5850 if (!CLASS_TYPE_P (const_objtype))
5851 fail = true;
5852 else
5854 /* [class.ctor]p5 "A constructor can be invoked for a const,
5855 volatile, or const volatile object. const and volatile
5856 semantics are not applied on an object under construction.
5857 They come into effect when the constructor for the most
5858 derived object ends." */
5859 for (tree elt : *ctors)
5860 if (same_type_ignoring_top_level_qualifiers_p
5861 (TREE_TYPE (const_object_being_modified), TREE_TYPE (elt)))
5863 fail = TREE_READONLY (elt);
5864 break;
5867 if (fail)
5869 if (!ctx->quiet)
5870 modifying_const_object_error (t, const_object_being_modified);
5871 *non_constant_p = true;
5872 return t;
5876 if (!preeval)
5878 /* We're handling an INIT_EXPR of class type, so the value of the
5879 initializer can depend on the object it's initializing. */
5881 /* Create a new CONSTRUCTOR in case evaluation of the initializer
5882 wants to modify it. */
5883 if (*valp == NULL_TREE)
5885 *valp = build_constructor (type, NULL);
5886 CONSTRUCTOR_NO_CLEARING (*valp) = no_zero_init;
5888 new_ctx.ctor = *valp;
5889 new_ctx.object = target;
5890 /* Avoid temporary materialization when initializing from a TARGET_EXPR.
5891 We don't need to mess with AGGR_EXPR_SLOT/VEC_INIT_EXPR_SLOT because
5892 expansion of those trees uses ctx instead. */
5893 if (TREE_CODE (init) == TARGET_EXPR)
5894 if (tree tinit = TARGET_EXPR_INITIAL (init))
5895 init = tinit;
5896 init = cxx_eval_constant_expression (&new_ctx, init, false,
5897 non_constant_p, overflow_p);
5898 /* The hash table might have moved since the get earlier, and the
5899 initializer might have mutated the underlying CONSTRUCTORs, so we must
5900 recompute VALP. */
5901 valp = ctx->global->values.get (object);
5902 for (unsigned i = 0; i < vec_safe_length (indexes); i++)
5904 constructor_elt *cep
5905 = get_or_insert_ctor_field (*valp, indexes[i], index_pos_hints[i]);
5906 valp = &cep->value;
5910 if (*non_constant_p)
5911 return t;
5913 /* Don't share a CONSTRUCTOR that might be changed later. */
5914 init = unshare_constructor (init);
5916 gcc_checking_assert (!*valp || (same_type_ignoring_top_level_qualifiers_p
5917 (TREE_TYPE (*valp), type)));
5918 if (empty_base || !(same_type_ignoring_top_level_qualifiers_p
5919 (TREE_TYPE (init), type)))
5921 /* For initialization of an empty base, the original target will be
5922 *(base*)this, evaluation of which resolves to the object
5923 argument, which has the derived type rather than the base type. In
5924 this situation, just evaluate the initializer and return, since
5925 there's no actual data to store, and we didn't build a CONSTRUCTOR. */
5926 empty_base = true;
5927 gcc_assert (is_empty_class (TREE_TYPE (init)));
5928 if (!*valp)
5930 /* But do make sure we have something in *valp. */
5931 *valp = build_constructor (type, nullptr);
5932 CONSTRUCTOR_NO_CLEARING (*valp) = no_zero_init;
5935 else if (*valp && TREE_CODE (*valp) == CONSTRUCTOR
5936 && TREE_CODE (init) == CONSTRUCTOR)
5938 /* An outer ctx->ctor might be pointing to *valp, so replace
5939 its contents. */
5940 CONSTRUCTOR_ELTS (*valp) = CONSTRUCTOR_ELTS (init);
5941 TREE_CONSTANT (*valp) = TREE_CONSTANT (init);
5942 TREE_SIDE_EFFECTS (*valp) = TREE_SIDE_EFFECTS (init);
5943 CONSTRUCTOR_NO_CLEARING (*valp)
5944 = CONSTRUCTOR_NO_CLEARING (init);
5946 else
5947 *valp = init;
5949 /* After initialization, 'const' semantics apply to the value of the
5950 object. Make a note of this fact by marking the CONSTRUCTOR
5951 TREE_READONLY. */
5952 if (TREE_CODE (t) == INIT_EXPR
5953 && TREE_CODE (*valp) == CONSTRUCTOR
5954 && TYPE_READONLY (type))
5956 if (INDIRECT_REF_P (target)
5957 && (is_this_parameter
5958 (tree_strip_nop_conversions (TREE_OPERAND (target, 0)))))
5959 /* We've just initialized '*this' (perhaps via the target
5960 constructor of a delegating constructor). Leave it up to the
5961 caller that set 'this' to set TREE_READONLY appropriately. */
5962 gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
5963 (TREE_TYPE (target), type) || empty_base);
5964 else
5965 TREE_READONLY (*valp) = true;
5968 /* Update TREE_CONSTANT and TREE_SIDE_EFFECTS on enclosing
5969 CONSTRUCTORs, if any. */
5970 bool c = TREE_CONSTANT (init);
5971 bool s = TREE_SIDE_EFFECTS (init);
5972 if (!c || s || activated_union_member_p)
5973 for (tree elt : *ctors)
5975 if (!c)
5976 TREE_CONSTANT (elt) = false;
5977 if (s)
5978 TREE_SIDE_EFFECTS (elt) = true;
5979 /* Clear CONSTRUCTOR_NO_CLEARING since we've activated a member of
5980 this union. */
5981 if (TREE_CODE (TREE_TYPE (elt)) == UNION_TYPE)
5982 CONSTRUCTOR_NO_CLEARING (elt) = false;
5985 if (lval)
5986 return target;
5987 else
5988 return init;
5991 /* Evaluate a ++ or -- expression. */
5993 static tree
5994 cxx_eval_increment_expression (const constexpr_ctx *ctx, tree t,
5995 bool lval,
5996 bool *non_constant_p, bool *overflow_p)
5998 enum tree_code code = TREE_CODE (t);
5999 tree type = TREE_TYPE (t);
6000 tree op = TREE_OPERAND (t, 0);
6001 tree offset = TREE_OPERAND (t, 1);
6002 gcc_assert (TREE_CONSTANT (offset));
6004 /* OFFSET is constant, but perhaps not constant enough. We need to
6005 e.g. bash FLOAT_EXPRs to REAL_CSTs. */
6006 offset = fold_simple (offset);
6008 /* The operand as an lvalue. */
6009 op = cxx_eval_constant_expression (ctx, op, true,
6010 non_constant_p, overflow_p);
6012 /* The operand as an rvalue. */
6013 tree val
6014 = cxx_eval_constant_expression (ctx, op, false,
6015 non_constant_p, overflow_p);
6016 /* Don't VERIFY_CONSTANT if this might be dealing with a pointer to
6017 a local array in a constexpr function. */
6018 bool ptr = INDIRECT_TYPE_P (TREE_TYPE (val));
6019 if (!ptr)
6020 VERIFY_CONSTANT (val);
6022 /* The modified value. */
6023 bool inc = (code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR);
6024 tree mod;
6025 if (INDIRECT_TYPE_P (type))
6027 /* The middle end requires pointers to use POINTER_PLUS_EXPR. */
6028 offset = convert_to_ptrofftype (offset);
6029 if (!inc)
6030 offset = fold_build1 (NEGATE_EXPR, TREE_TYPE (offset), offset);
6031 mod = fold_build2 (POINTER_PLUS_EXPR, type, val, offset);
6033 else
6034 mod = fold_build2 (inc ? PLUS_EXPR : MINUS_EXPR, type, val, offset);
6035 if (!ptr)
6036 VERIFY_CONSTANT (mod);
6038 /* Storing the modified value. */
6039 tree store = build2_loc (cp_expr_loc_or_loc (t, input_location),
6040 MODIFY_EXPR, type, op, mod);
6041 mod = cxx_eval_constant_expression (ctx, store, lval,
6042 non_constant_p, overflow_p);
6043 ggc_free (store);
6044 if (*non_constant_p)
6045 return t;
6047 /* And the value of the expression. */
6048 if (code == PREINCREMENT_EXPR || code == PREDECREMENT_EXPR)
6049 /* Prefix ops are lvalues, but the caller might want an rvalue;
6050 lval has already been taken into account in the store above. */
6051 return mod;
6052 else
6053 /* Postfix ops are rvalues. */
6054 return val;
6057 /* Predicates for the meaning of *jump_target. */
6059 static bool
6060 returns (tree *jump_target)
6062 return *jump_target
6063 && TREE_CODE (*jump_target) == RETURN_EXPR;
6066 static bool
6067 breaks (tree *jump_target)
6069 return *jump_target
6070 && ((TREE_CODE (*jump_target) == LABEL_DECL
6071 && LABEL_DECL_BREAK (*jump_target))
6072 || TREE_CODE (*jump_target) == BREAK_STMT
6073 || TREE_CODE (*jump_target) == EXIT_EXPR);
6076 static bool
6077 continues (tree *jump_target)
6079 return *jump_target
6080 && ((TREE_CODE (*jump_target) == LABEL_DECL
6081 && LABEL_DECL_CONTINUE (*jump_target))
6082 || TREE_CODE (*jump_target) == CONTINUE_STMT);
6086 static bool
6087 switches (tree *jump_target)
6089 return *jump_target
6090 && TREE_CODE (*jump_target) == INTEGER_CST;
6093 /* Subroutine of cxx_eval_statement_list. Determine whether the statement
6094 STMT matches *jump_target. If we're looking for a case label and we see
6095 the default label, note it in ctx->css_state. */
6097 static bool
6098 label_matches (const constexpr_ctx *ctx, tree *jump_target, tree stmt)
6100 switch (TREE_CODE (*jump_target))
6102 case LABEL_DECL:
6103 if (TREE_CODE (stmt) == LABEL_EXPR
6104 && LABEL_EXPR_LABEL (stmt) == *jump_target)
6105 return true;
6106 break;
6108 case INTEGER_CST:
6109 if (TREE_CODE (stmt) == CASE_LABEL_EXPR)
6111 gcc_assert (ctx->css_state != NULL);
6112 if (!CASE_LOW (stmt))
6114 /* default: should appear just once in a SWITCH_EXPR
6115 body (excluding nested SWITCH_EXPR). */
6116 gcc_assert (*ctx->css_state != css_default_seen);
6117 /* When evaluating SWITCH_EXPR body for the second time,
6118 return true for the default: label. */
6119 if (*ctx->css_state == css_default_processing)
6120 return true;
6121 *ctx->css_state = css_default_seen;
6123 else if (CASE_HIGH (stmt))
6125 if (tree_int_cst_le (CASE_LOW (stmt), *jump_target)
6126 && tree_int_cst_le (*jump_target, CASE_HIGH (stmt)))
6127 return true;
6129 else if (tree_int_cst_equal (*jump_target, CASE_LOW (stmt)))
6130 return true;
6132 break;
6134 case BREAK_STMT:
6135 case CONTINUE_STMT:
6136 /* These two are handled directly in cxx_eval_loop_expr by testing
6137 breaks (jump_target) or continues (jump_target). */
6138 break;
6140 default:
6141 gcc_unreachable ();
6143 return false;
6146 /* Evaluate a STATEMENT_LIST for side-effects. Handles various jump
6147 semantics, for switch, break, continue, and return. */
6149 static tree
6150 cxx_eval_statement_list (const constexpr_ctx *ctx, tree t,
6151 bool *non_constant_p, bool *overflow_p,
6152 tree *jump_target)
6154 tree local_target;
6155 /* In a statement-expression we want to return the last value.
6156 For empty statement expression return void_node. */
6157 tree r = void_node;
6158 if (!jump_target)
6160 local_target = NULL_TREE;
6161 jump_target = &local_target;
6163 for (tree stmt : tsi_range (t))
6165 /* We've found a continue, so skip everything until we reach
6166 the label its jumping to. */
6167 if (continues (jump_target))
6169 if (label_matches (ctx, jump_target, stmt))
6170 /* Found it. */
6171 *jump_target = NULL_TREE;
6172 else
6173 continue;
6175 if (TREE_CODE (stmt) == DEBUG_BEGIN_STMT)
6176 continue;
6177 r = cxx_eval_constant_expression (ctx, stmt, false,
6178 non_constant_p, overflow_p,
6179 jump_target);
6180 if (*non_constant_p)
6181 break;
6182 if (returns (jump_target) || breaks (jump_target))
6183 break;
6185 if (*jump_target && jump_target == &local_target)
6187 /* We aren't communicating the jump to our caller, so give up. We don't
6188 need to support evaluation of jumps out of statement-exprs. */
6189 if (!ctx->quiet)
6190 error_at (cp_expr_loc_or_input_loc (r),
6191 "statement is not a constant expression");
6192 *non_constant_p = true;
6194 return r;
6197 /* Evaluate a LOOP_EXPR for side-effects. Handles break and return
6198 semantics; continue semantics are covered by cxx_eval_statement_list. */
6200 static tree
6201 cxx_eval_loop_expr (const constexpr_ctx *ctx, tree t,
6202 bool *non_constant_p, bool *overflow_p,
6203 tree *jump_target)
6205 constexpr_ctx new_ctx = *ctx;
6206 tree local_target;
6207 if (!jump_target)
6209 local_target = NULL_TREE;
6210 jump_target = &local_target;
6213 tree body, cond = NULL_TREE, expr = NULL_TREE;
6214 int count = 0;
6215 switch (TREE_CODE (t))
6217 case LOOP_EXPR:
6218 body = LOOP_EXPR_BODY (t);
6219 break;
6220 case DO_STMT:
6221 body = DO_BODY (t);
6222 cond = DO_COND (t);
6223 break;
6224 case WHILE_STMT:
6225 body = WHILE_BODY (t);
6226 cond = WHILE_COND (t);
6227 count = -1;
6228 break;
6229 case FOR_STMT:
6230 if (FOR_INIT_STMT (t))
6231 cxx_eval_constant_expression (ctx, FOR_INIT_STMT (t), /*lval*/false,
6232 non_constant_p, overflow_p, jump_target);
6233 if (*non_constant_p)
6234 return NULL_TREE;
6235 body = FOR_BODY (t);
6236 cond = FOR_COND (t);
6237 expr = FOR_EXPR (t);
6238 count = -1;
6239 break;
6240 default:
6241 gcc_unreachable ();
6243 auto_vec<tree, 10> save_exprs;
6244 new_ctx.save_exprs = &save_exprs;
6247 if (count != -1)
6249 if (body)
6250 cxx_eval_constant_expression (&new_ctx, body, /*lval*/false,
6251 non_constant_p, overflow_p,
6252 jump_target);
6253 if (breaks (jump_target))
6255 *jump_target = NULL_TREE;
6256 break;
6259 if (TREE_CODE (t) != LOOP_EXPR && continues (jump_target))
6260 *jump_target = NULL_TREE;
6262 if (expr)
6263 cxx_eval_constant_expression (&new_ctx, expr, /*lval*/false,
6264 non_constant_p, overflow_p,
6265 jump_target);
6268 if (cond)
6270 tree res
6271 = cxx_eval_constant_expression (&new_ctx, cond, /*lval*/false,
6272 non_constant_p, overflow_p,
6273 jump_target);
6274 if (res)
6276 if (verify_constant (res, ctx->quiet, non_constant_p,
6277 overflow_p))
6278 break;
6279 if (integer_zerop (res))
6280 break;
6282 else
6283 gcc_assert (*jump_target);
6286 /* Forget saved values of SAVE_EXPRs and TARGET_EXPRs. */
6287 for (tree save_expr : save_exprs)
6288 ctx->global->values.remove (save_expr);
6289 save_exprs.truncate (0);
6291 if (++count >= constexpr_loop_limit)
6293 if (!ctx->quiet)
6294 error_at (cp_expr_loc_or_input_loc (t),
6295 "%<constexpr%> loop iteration count exceeds limit of %d "
6296 "(use %<-fconstexpr-loop-limit=%> to increase the limit)",
6297 constexpr_loop_limit);
6298 *non_constant_p = true;
6299 break;
6302 while (!returns (jump_target)
6303 && !breaks (jump_target)
6304 && !continues (jump_target)
6305 && (!switches (jump_target) || count == 0)
6306 && !*non_constant_p);
6308 /* Forget saved values of SAVE_EXPRs and TARGET_EXPRs. */
6309 for (tree save_expr : save_exprs)
6310 ctx->global->values.remove (save_expr);
6312 return NULL_TREE;
6315 /* Evaluate a SWITCH_EXPR for side-effects. Handles switch and break jump
6316 semantics. */
6318 static tree
6319 cxx_eval_switch_expr (const constexpr_ctx *ctx, tree t,
6320 bool *non_constant_p, bool *overflow_p,
6321 tree *jump_target)
6323 tree cond
6324 = TREE_CODE (t) == SWITCH_STMT ? SWITCH_STMT_COND (t) : SWITCH_COND (t);
6325 cond = cxx_eval_constant_expression (ctx, cond, false,
6326 non_constant_p, overflow_p);
6327 VERIFY_CONSTANT (cond);
6328 *jump_target = cond;
6330 tree body
6331 = TREE_CODE (t) == SWITCH_STMT ? SWITCH_STMT_BODY (t) : SWITCH_BODY (t);
6332 constexpr_ctx new_ctx = *ctx;
6333 constexpr_switch_state css = css_default_not_seen;
6334 new_ctx.css_state = &css;
6335 cxx_eval_constant_expression (&new_ctx, body, false,
6336 non_constant_p, overflow_p, jump_target);
6337 if (switches (jump_target) && css == css_default_seen)
6339 /* If the SWITCH_EXPR body has default: label, process it once again,
6340 this time instructing label_matches to return true for default:
6341 label on switches (jump_target). */
6342 css = css_default_processing;
6343 cxx_eval_constant_expression (&new_ctx, body, false,
6344 non_constant_p, overflow_p, jump_target);
6346 if (breaks (jump_target) || switches (jump_target))
6347 *jump_target = NULL_TREE;
6348 return NULL_TREE;
6351 /* Find the object of TYPE under initialization in CTX. */
6353 static tree
6354 lookup_placeholder (const constexpr_ctx *ctx, bool lval, tree type)
6356 if (!ctx)
6357 return NULL_TREE;
6359 /* Prefer the outermost matching object, but don't cross
6360 CONSTRUCTOR_PLACEHOLDER_BOUNDARY constructors. */
6361 if (ctx->ctor && !CONSTRUCTOR_PLACEHOLDER_BOUNDARY (ctx->ctor))
6362 if (tree outer_ob = lookup_placeholder (ctx->parent, lval, type))
6363 return outer_ob;
6365 /* We could use ctx->object unconditionally, but using ctx->ctor when we
6366 can is a minor optimization. */
6367 if (!lval && ctx->ctor && same_type_p (TREE_TYPE (ctx->ctor), type))
6368 return ctx->ctor;
6370 if (!ctx->object)
6371 return NULL_TREE;
6373 /* Since an object cannot have a field of its own type, we can search outward
6374 from ctx->object to find the unique containing object of TYPE. */
6375 tree ob = ctx->object;
6376 while (ob)
6378 if (same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (ob), type))
6379 break;
6380 if (handled_component_p (ob))
6381 ob = TREE_OPERAND (ob, 0);
6382 else
6383 ob = NULL_TREE;
6386 return ob;
6389 /* Complain about an attempt to evaluate inline assembly. */
6391 static void
6392 inline_asm_in_constexpr_error (location_t loc)
6394 auto_diagnostic_group d;
6395 error_at (loc, "inline assembly is not a constant expression");
6396 inform (loc, "only unevaluated inline assembly is allowed in a "
6397 "%<constexpr%> function in C++20");
6400 /* We're getting the constant value of DECL in a manifestly constant-evaluated
6401 context; maybe complain about that. */
6403 static void
6404 maybe_warn_about_constant_value (location_t loc, tree decl)
6406 static bool explained = false;
6407 if (cxx_dialect >= cxx17
6408 && warn_interference_size
6409 && !OPTION_SET_P (param_destruct_interfere_size)
6410 && DECL_CONTEXT (decl) == std_node
6411 && id_equal (DECL_NAME (decl), "hardware_destructive_interference_size")
6412 && (LOCATION_FILE (input_location) != main_input_filename
6413 || module_exporting_p ())
6414 && warning_at (loc, OPT_Winterference_size, "use of %qD", decl)
6415 && !explained)
6417 explained = true;
6418 inform (loc, "its value can vary between compiler versions or "
6419 "with different %<-mtune%> or %<-mcpu%> flags");
6420 inform (loc, "if this use is part of a public ABI, change it to "
6421 "instead use a constant variable you define");
6422 inform (loc, "the default value for the current CPU tuning "
6423 "is %d bytes", param_destruct_interfere_size);
6424 inform (loc, "you can stabilize this value with %<--param "
6425 "hardware_destructive_interference_size=%d%>, or disable "
6426 "this warning with %<-Wno-interference-size%>",
6427 param_destruct_interfere_size);
6431 /* For element type ELT_TYPE, return the appropriate type of the heap object
6432 containing such element(s). COOKIE_SIZE is NULL or the size of cookie
6433 in bytes. If COOKIE_SIZE is NULL, return array type
6434 ELT_TYPE[FULL_SIZE / sizeof(ELT_TYPE)], otherwise return
6435 struct { size_t[COOKIE_SIZE/sizeof(size_t)]; ELT_TYPE[N]; }
6436 where N is is computed such that the size of the struct fits into FULL_SIZE.
6437 If ARG_SIZE is non-NULL, it is the first argument to the new operator.
6438 It should be passed if ELT_TYPE is zero sized type in which case FULL_SIZE
6439 will be also 0 and so it is not possible to determine the actual array
6440 size. CTX, NON_CONSTANT_P and OVERFLOW_P are used during constant
6441 expression evaluation of subexpressions of ARG_SIZE. */
6443 static tree
6444 build_new_constexpr_heap_type (const constexpr_ctx *ctx, tree elt_type,
6445 tree cookie_size, tree full_size, tree arg_size,
6446 bool *non_constant_p, bool *overflow_p)
6448 gcc_assert (cookie_size == NULL_TREE || tree_fits_uhwi_p (cookie_size));
6449 gcc_assert (tree_fits_uhwi_p (full_size));
6450 unsigned HOST_WIDE_INT csz = cookie_size ? tree_to_uhwi (cookie_size) : 0;
6451 if (arg_size)
6453 STRIP_NOPS (arg_size);
6454 if (cookie_size)
6456 if (TREE_CODE (arg_size) != PLUS_EXPR)
6457 arg_size = NULL_TREE;
6458 else if (TREE_CODE (TREE_OPERAND (arg_size, 0)) == INTEGER_CST
6459 && tree_int_cst_equal (cookie_size,
6460 TREE_OPERAND (arg_size, 0)))
6462 arg_size = TREE_OPERAND (arg_size, 1);
6463 STRIP_NOPS (arg_size);
6465 else if (TREE_CODE (TREE_OPERAND (arg_size, 1)) == INTEGER_CST
6466 && tree_int_cst_equal (cookie_size,
6467 TREE_OPERAND (arg_size, 1)))
6469 arg_size = TREE_OPERAND (arg_size, 0);
6470 STRIP_NOPS (arg_size);
6472 else
6473 arg_size = NULL_TREE;
6475 if (arg_size && TREE_CODE (arg_size) == MULT_EXPR)
6477 tree op0 = TREE_OPERAND (arg_size, 0);
6478 tree op1 = TREE_OPERAND (arg_size, 1);
6479 if (integer_zerop (op0))
6480 arg_size
6481 = cxx_eval_constant_expression (ctx, op1, false, non_constant_p,
6482 overflow_p);
6483 else if (integer_zerop (op1))
6484 arg_size
6485 = cxx_eval_constant_expression (ctx, op0, false, non_constant_p,
6486 overflow_p);
6487 else
6488 arg_size = NULL_TREE;
6490 else
6491 arg_size = NULL_TREE;
6494 unsigned HOST_WIDE_INT fsz = tree_to_uhwi (arg_size ? arg_size : full_size);
6495 if (!arg_size)
6497 unsigned HOST_WIDE_INT esz = int_size_in_bytes (elt_type);
6498 gcc_assert (fsz >= csz);
6499 fsz -= csz;
6500 if (esz)
6501 fsz /= esz;
6503 tree itype2 = build_index_type (size_int (fsz - 1));
6504 if (!cookie_size)
6505 return build_cplus_array_type (elt_type, itype2);
6506 return build_new_constexpr_heap_type (elt_type, cookie_size, itype2);
6509 /* Attempt to reduce the expression T to a constant value.
6510 On failure, issue diagnostic and return error_mark_node. */
6511 /* FIXME unify with c_fully_fold */
6512 /* FIXME overflow_p is too global */
6514 static tree
6515 cxx_eval_constant_expression (const constexpr_ctx *ctx, tree t,
6516 bool lval,
6517 bool *non_constant_p, bool *overflow_p,
6518 tree *jump_target /* = NULL */)
6520 if (jump_target && *jump_target)
6522 /* If we are jumping, ignore all statements/expressions except those
6523 that could have LABEL_EXPR or CASE_LABEL_EXPR in their bodies. */
6524 switch (TREE_CODE (t))
6526 case BIND_EXPR:
6527 case STATEMENT_LIST:
6528 case LOOP_EXPR:
6529 case COND_EXPR:
6530 case IF_STMT:
6531 case DO_STMT:
6532 case WHILE_STMT:
6533 case FOR_STMT:
6534 break;
6535 case LABEL_EXPR:
6536 case CASE_LABEL_EXPR:
6537 if (label_matches (ctx, jump_target, t))
6538 /* Found it. */
6539 *jump_target = NULL_TREE;
6540 return NULL_TREE;
6541 default:
6542 return NULL_TREE;
6545 if (error_operand_p (t))
6547 *non_constant_p = true;
6548 return t;
6551 location_t loc = cp_expr_loc_or_input_loc (t);
6553 STRIP_ANY_LOCATION_WRAPPER (t);
6555 if (CONSTANT_CLASS_P (t))
6557 if (TREE_OVERFLOW (t))
6559 if (!ctx->quiet)
6560 permerror (input_location, "overflow in constant expression");
6561 if (!flag_permissive || ctx->quiet)
6562 *overflow_p = true;
6565 if (TREE_CODE (t) == INTEGER_CST
6566 && TYPE_PTR_P (TREE_TYPE (t))
6567 /* INTEGER_CST with pointer-to-method type is only used
6568 for a virtual method in a pointer to member function.
6569 Don't reject those. */
6570 && TREE_CODE (TREE_TYPE (TREE_TYPE (t))) != METHOD_TYPE
6571 && !integer_zerop (t))
6573 if (!ctx->quiet)
6574 error ("value %qE of type %qT is not a constant expression",
6575 t, TREE_TYPE (t));
6576 *non_constant_p = true;
6579 return t;
6582 /* Avoid excessively long constexpr evaluations. */
6583 if (++ctx->global->constexpr_ops_count >= constexpr_ops_limit)
6585 if (!ctx->quiet)
6586 error_at (loc,
6587 "%<constexpr%> evaluation operation count exceeds limit of "
6588 "%wd (use %<-fconstexpr-ops-limit=%> to increase the limit)",
6589 constexpr_ops_limit);
6590 ctx->global->constexpr_ops_count = INTTYPE_MINIMUM (HOST_WIDE_INT);
6591 *non_constant_p = true;
6592 return t;
6595 constexpr_ctx new_ctx;
6596 tree r = t;
6598 tree_code tcode = TREE_CODE (t);
6599 switch (tcode)
6601 case RESULT_DECL:
6602 if (lval)
6603 return t;
6604 /* We ask for an rvalue for the RESULT_DECL when indirecting
6605 through an invisible reference, or in named return value
6606 optimization. */
6607 if (tree *p = ctx->global->values.get (t))
6608 return *p;
6609 else
6611 if (!ctx->quiet)
6612 error ("%qE is not a constant expression", t);
6613 *non_constant_p = true;
6615 break;
6617 case VAR_DECL:
6618 if (DECL_HAS_VALUE_EXPR_P (t))
6620 if (is_normal_capture_proxy (t)
6621 && current_function_decl == DECL_CONTEXT (t))
6623 /* Function parms aren't constexpr within the function
6624 definition, so don't try to look at the closure. But if the
6625 captured variable is constant, try to evaluate it directly. */
6626 r = DECL_CAPTURED_VARIABLE (t);
6627 tree type = TREE_TYPE (t);
6628 if (TYPE_REF_P (type) != TYPE_REF_P (TREE_TYPE (r)))
6630 /* Adjust r to match the reference-ness of t. */
6631 if (TYPE_REF_P (type))
6632 r = build_address (r);
6633 else
6634 r = convert_from_reference (r);
6637 else
6638 r = DECL_VALUE_EXPR (t);
6639 return cxx_eval_constant_expression (ctx, r, lval, non_constant_p,
6640 overflow_p);
6642 /* fall through */
6643 case CONST_DECL:
6644 /* We used to not check lval for CONST_DECL, but darwin.cc uses
6645 CONST_DECL for aggregate constants. */
6646 if (lval)
6647 return t;
6648 else if (t == ctx->object)
6649 return ctx->ctor;
6650 if (VAR_P (t))
6651 if (tree *p = ctx->global->values.get (t))
6652 if (*p != NULL_TREE)
6654 r = *p;
6655 break;
6657 if (ctx->manifestly_const_eval)
6658 maybe_warn_about_constant_value (loc, t);
6659 if (COMPLETE_TYPE_P (TREE_TYPE (t))
6660 && is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
6662 /* If the class is empty, we aren't actually loading anything. */
6663 r = build_constructor (TREE_TYPE (t), NULL);
6664 TREE_CONSTANT (r) = true;
6666 else if (ctx->strict)
6667 r = decl_really_constant_value (t, /*unshare_p=*/false);
6668 else
6669 r = decl_constant_value (t, /*unshare_p=*/false);
6670 if (TREE_CODE (r) == TARGET_EXPR
6671 && TREE_CODE (TARGET_EXPR_INITIAL (r)) == CONSTRUCTOR)
6672 r = TARGET_EXPR_INITIAL (r);
6673 if (DECL_P (r))
6675 if (!ctx->quiet)
6676 non_const_var_error (loc, r);
6677 *non_constant_p = true;
6679 break;
6681 case DEBUG_BEGIN_STMT:
6682 /* ??? It might be nice to retain this information somehow, so
6683 as to be able to step into a constexpr function call. */
6684 /* Fall through. */
6686 case FUNCTION_DECL:
6687 case TEMPLATE_DECL:
6688 case LABEL_DECL:
6689 case LABEL_EXPR:
6690 case CASE_LABEL_EXPR:
6691 case PREDICT_EXPR:
6692 return t;
6694 case PARM_DECL:
6695 if (lval && !TYPE_REF_P (TREE_TYPE (t)))
6696 /* glvalue use. */;
6697 else if (tree *p = ctx->global->values.get (r))
6698 r = *p;
6699 else if (lval)
6700 /* Defer in case this is only used for its type. */;
6701 else if (COMPLETE_TYPE_P (TREE_TYPE (t))
6702 && is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
6704 /* If the class is empty, we aren't actually loading anything. */
6705 r = build_constructor (TREE_TYPE (t), NULL);
6706 TREE_CONSTANT (r) = true;
6708 else
6710 if (!ctx->quiet)
6711 error ("%qE is not a constant expression", t);
6712 *non_constant_p = true;
6714 break;
6716 case CALL_EXPR:
6717 case AGGR_INIT_EXPR:
6718 r = cxx_eval_call_expression (ctx, t, lval,
6719 non_constant_p, overflow_p);
6720 break;
6722 case DECL_EXPR:
6724 r = DECL_EXPR_DECL (t);
6725 if (TREE_CODE (r) == USING_DECL)
6727 r = void_node;
6728 break;
6731 if (VAR_P (r)
6732 && (TREE_STATIC (r)
6733 || (CP_DECL_THREAD_LOCAL_P (r) && !DECL_REALLY_EXTERN (r)))
6734 /* Allow __FUNCTION__ etc. */
6735 && !DECL_ARTIFICIAL (r))
6737 if (!ctx->quiet)
6739 if (CP_DECL_THREAD_LOCAL_P (r))
6740 error_at (loc, "control passes through definition of %qD "
6741 "with thread storage duration", r);
6742 else
6743 error_at (loc, "control passes through definition of %qD "
6744 "with static storage duration", r);
6746 *non_constant_p = true;
6747 break;
6750 if (AGGREGATE_TYPE_P (TREE_TYPE (r))
6751 || VECTOR_TYPE_P (TREE_TYPE (r)))
6753 new_ctx = *ctx;
6754 new_ctx.object = r;
6755 new_ctx.ctor = build_constructor (TREE_TYPE (r), NULL);
6756 CONSTRUCTOR_NO_CLEARING (new_ctx.ctor) = true;
6757 ctx->global->values.put (r, new_ctx.ctor);
6758 ctx = &new_ctx;
6761 if (tree init = DECL_INITIAL (r))
6763 init = cxx_eval_constant_expression (ctx, init,
6764 false,
6765 non_constant_p, overflow_p);
6766 /* Don't share a CONSTRUCTOR that might be changed. */
6767 init = unshare_constructor (init);
6768 /* Remember that a constant object's constructor has already
6769 run. */
6770 if (CLASS_TYPE_P (TREE_TYPE (r))
6771 && CP_TYPE_CONST_P (TREE_TYPE (r)))
6772 TREE_READONLY (init) = true;
6773 ctx->global->values.put (r, init);
6775 else if (ctx == &new_ctx)
6776 /* We gave it a CONSTRUCTOR above. */;
6777 else
6778 ctx->global->values.put (r, NULL_TREE);
6780 break;
6782 case TARGET_EXPR:
6784 tree type = TREE_TYPE (t);
6786 if (!literal_type_p (type))
6788 if (!ctx->quiet)
6790 auto_diagnostic_group d;
6791 error ("temporary of non-literal type %qT in a "
6792 "constant expression", type);
6793 explain_non_literal_class (type);
6795 *non_constant_p = true;
6796 break;
6798 gcc_checking_assert (!TARGET_EXPR_DIRECT_INIT_P (t));
6799 /* Avoid evaluating a TARGET_EXPR more than once. */
6800 tree slot = TARGET_EXPR_SLOT (t);
6801 if (tree *p = ctx->global->values.get (slot))
6803 if (lval)
6804 return slot;
6805 r = *p;
6806 break;
6808 if ((AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type)))
6810 /* We're being expanded without an explicit target, so start
6811 initializing a new object; expansion with an explicit target
6812 strips the TARGET_EXPR before we get here. */
6813 new_ctx = *ctx;
6814 /* Link CTX to NEW_CTX so that lookup_placeholder can resolve
6815 any PLACEHOLDER_EXPR within the initializer that refers to the
6816 former object under construction. */
6817 new_ctx.parent = ctx;
6818 new_ctx.ctor = build_constructor (type, NULL);
6819 CONSTRUCTOR_NO_CLEARING (new_ctx.ctor) = true;
6820 new_ctx.object = slot;
6821 ctx->global->values.put (new_ctx.object, new_ctx.ctor);
6822 ctx = &new_ctx;
6824 /* Pass false for 'lval' because this indicates
6825 initialization of a temporary. */
6826 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
6827 false,
6828 non_constant_p, overflow_p);
6829 if (*non_constant_p)
6830 break;
6831 /* Adjust the type of the result to the type of the temporary. */
6832 r = adjust_temp_type (type, r);
6833 if (TARGET_EXPR_CLEANUP (t) && !CLEANUP_EH_ONLY (t))
6834 ctx->global->cleanups->safe_push (TARGET_EXPR_CLEANUP (t));
6835 r = unshare_constructor (r);
6836 ctx->global->values.put (slot, r);
6837 if (ctx->save_exprs)
6838 ctx->save_exprs->safe_push (slot);
6839 if (lval)
6840 return slot;
6842 break;
6844 case INIT_EXPR:
6845 case MODIFY_EXPR:
6846 gcc_assert (jump_target == NULL || *jump_target == NULL_TREE);
6847 r = cxx_eval_store_expression (ctx, t, lval,
6848 non_constant_p, overflow_p);
6849 break;
6851 case SCOPE_REF:
6852 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
6853 lval,
6854 non_constant_p, overflow_p);
6855 break;
6857 case RETURN_EXPR:
6858 if (TREE_OPERAND (t, 0) != NULL_TREE)
6859 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
6860 lval,
6861 non_constant_p, overflow_p);
6862 /* FALLTHRU */
6863 case BREAK_STMT:
6864 case CONTINUE_STMT:
6865 if (jump_target)
6866 *jump_target = t;
6867 else
6869 /* Can happen with ({ return true; }) && false; passed to
6870 maybe_constant_value. There is nothing to jump over in this
6871 case, and the bug will be diagnosed later. */
6872 gcc_assert (ctx->quiet);
6873 *non_constant_p = true;
6875 break;
6877 case SAVE_EXPR:
6878 /* Avoid evaluating a SAVE_EXPR more than once. */
6879 if (tree *p = ctx->global->values.get (t))
6880 r = *p;
6881 else
6883 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), false,
6884 non_constant_p, overflow_p);
6885 if (*non_constant_p)
6886 break;
6887 ctx->global->values.put (t, r);
6888 if (ctx->save_exprs)
6889 ctx->save_exprs->safe_push (t);
6891 break;
6893 case TRY_CATCH_EXPR:
6894 if (TREE_OPERAND (t, 0) == NULL_TREE)
6896 r = void_node;
6897 break;
6899 /* FALLTHRU */
6900 case NON_LVALUE_EXPR:
6901 case TRY_BLOCK:
6902 case MUST_NOT_THROW_EXPR:
6903 case EXPR_STMT:
6904 case EH_SPEC_BLOCK:
6905 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
6906 lval,
6907 non_constant_p, overflow_p,
6908 jump_target);
6909 break;
6911 case CLEANUP_POINT_EXPR:
6913 auto_vec<tree, 2> cleanups;
6914 vec<tree> *prev_cleanups = ctx->global->cleanups;
6915 ctx->global->cleanups = &cleanups;
6916 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
6917 lval,
6918 non_constant_p, overflow_p,
6919 jump_target);
6920 ctx->global->cleanups = prev_cleanups;
6921 unsigned int i;
6922 tree cleanup;
6923 /* Evaluate the cleanups. */
6924 FOR_EACH_VEC_ELT_REVERSE (cleanups, i, cleanup)
6925 cxx_eval_constant_expression (ctx, cleanup, false,
6926 non_constant_p, overflow_p);
6928 break;
6930 case TRY_FINALLY_EXPR:
6931 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
6932 non_constant_p, overflow_p,
6933 jump_target);
6934 if (!*non_constant_p)
6935 /* Also evaluate the cleanup. */
6936 cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1), true,
6937 non_constant_p, overflow_p);
6938 break;
6940 case CLEANUP_STMT:
6941 r = cxx_eval_constant_expression (ctx, CLEANUP_BODY (t), lval,
6942 non_constant_p, overflow_p,
6943 jump_target);
6944 if (!CLEANUP_EH_ONLY (t) && !*non_constant_p)
6946 iloc_sentinel ils (loc);
6947 /* Also evaluate the cleanup. */
6948 cxx_eval_constant_expression (ctx, CLEANUP_EXPR (t), true,
6949 non_constant_p, overflow_p);
6951 break;
6953 /* These differ from cxx_eval_unary_expression in that this doesn't
6954 check for a constant operand or result; an address can be
6955 constant without its operand being, and vice versa. */
6956 case MEM_REF:
6957 case INDIRECT_REF:
6958 r = cxx_eval_indirect_ref (ctx, t, lval,
6959 non_constant_p, overflow_p);
6960 break;
6962 case ADDR_EXPR:
6964 tree oldop = TREE_OPERAND (t, 0);
6965 tree op = cxx_eval_constant_expression (ctx, oldop,
6966 /*lval*/true,
6967 non_constant_p, overflow_p);
6968 /* Don't VERIFY_CONSTANT here. */
6969 if (*non_constant_p)
6970 return t;
6971 gcc_checking_assert (TREE_CODE (op) != CONSTRUCTOR);
6972 /* This function does more aggressive folding than fold itself. */
6973 r = build_fold_addr_expr_with_type (op, TREE_TYPE (t));
6974 if (TREE_CODE (r) == ADDR_EXPR && TREE_OPERAND (r, 0) == oldop)
6976 ggc_free (r);
6977 return t;
6979 break;
6982 case REALPART_EXPR:
6983 case IMAGPART_EXPR:
6984 if (lval)
6986 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
6987 non_constant_p, overflow_p);
6988 if (r == error_mark_node)
6990 else if (r == TREE_OPERAND (t, 0))
6991 r = t;
6992 else
6993 r = fold_build1 (TREE_CODE (t), TREE_TYPE (t), r);
6994 break;
6996 /* FALLTHRU */
6997 case CONJ_EXPR:
6998 case FIX_TRUNC_EXPR:
6999 case FLOAT_EXPR:
7000 case NEGATE_EXPR:
7001 case ABS_EXPR:
7002 case ABSU_EXPR:
7003 case BIT_NOT_EXPR:
7004 case TRUTH_NOT_EXPR:
7005 case FIXED_CONVERT_EXPR:
7006 r = cxx_eval_unary_expression (ctx, t, lval,
7007 non_constant_p, overflow_p);
7008 break;
7010 case SIZEOF_EXPR:
7011 r = fold_sizeof_expr (t);
7012 /* In a template, fold_sizeof_expr may merely create a new SIZEOF_EXPR,
7013 which could lead to an infinite recursion. */
7014 if (TREE_CODE (r) != SIZEOF_EXPR)
7015 r = cxx_eval_constant_expression (ctx, r, lval,
7016 non_constant_p, overflow_p,
7017 jump_target);
7018 else
7020 *non_constant_p = true;
7021 gcc_assert (ctx->quiet);
7024 break;
7026 case COMPOUND_EXPR:
7028 /* check_return_expr sometimes wraps a TARGET_EXPR in a
7029 COMPOUND_EXPR; don't get confused. Also handle EMPTY_CLASS_EXPR
7030 introduced by build_call_a. */
7031 tree op0 = TREE_OPERAND (t, 0);
7032 tree op1 = TREE_OPERAND (t, 1);
7033 STRIP_NOPS (op1);
7034 if ((TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
7035 || TREE_CODE (op1) == EMPTY_CLASS_EXPR)
7036 r = cxx_eval_constant_expression (ctx, op0,
7037 lval, non_constant_p, overflow_p,
7038 jump_target);
7039 else
7041 /* Check that the LHS is constant and then discard it. */
7042 cxx_eval_constant_expression (ctx, op0,
7043 true, non_constant_p, overflow_p,
7044 jump_target);
7045 if (*non_constant_p)
7046 return t;
7047 op1 = TREE_OPERAND (t, 1);
7048 r = cxx_eval_constant_expression (ctx, op1,
7049 lval, non_constant_p, overflow_p,
7050 jump_target);
7053 break;
7055 case POINTER_PLUS_EXPR:
7056 case POINTER_DIFF_EXPR:
7057 case PLUS_EXPR:
7058 case MINUS_EXPR:
7059 case MULT_EXPR:
7060 case TRUNC_DIV_EXPR:
7061 case CEIL_DIV_EXPR:
7062 case FLOOR_DIV_EXPR:
7063 case ROUND_DIV_EXPR:
7064 case TRUNC_MOD_EXPR:
7065 case CEIL_MOD_EXPR:
7066 case ROUND_MOD_EXPR:
7067 case RDIV_EXPR:
7068 case EXACT_DIV_EXPR:
7069 case MIN_EXPR:
7070 case MAX_EXPR:
7071 case LSHIFT_EXPR:
7072 case RSHIFT_EXPR:
7073 case LROTATE_EXPR:
7074 case RROTATE_EXPR:
7075 case BIT_IOR_EXPR:
7076 case BIT_XOR_EXPR:
7077 case BIT_AND_EXPR:
7078 case TRUTH_XOR_EXPR:
7079 case LT_EXPR:
7080 case LE_EXPR:
7081 case GT_EXPR:
7082 case GE_EXPR:
7083 case EQ_EXPR:
7084 case NE_EXPR:
7085 case SPACESHIP_EXPR:
7086 case UNORDERED_EXPR:
7087 case ORDERED_EXPR:
7088 case UNLT_EXPR:
7089 case UNLE_EXPR:
7090 case UNGT_EXPR:
7091 case UNGE_EXPR:
7092 case UNEQ_EXPR:
7093 case LTGT_EXPR:
7094 case RANGE_EXPR:
7095 case COMPLEX_EXPR:
7096 r = cxx_eval_binary_expression (ctx, t, lval,
7097 non_constant_p, overflow_p);
7098 break;
7100 /* fold can introduce non-IF versions of these; still treat them as
7101 short-circuiting. */
7102 case TRUTH_AND_EXPR:
7103 case TRUTH_ANDIF_EXPR:
7104 r = cxx_eval_logical_expression (ctx, t, boolean_false_node,
7105 boolean_true_node,
7106 non_constant_p, overflow_p);
7107 break;
7109 case TRUTH_OR_EXPR:
7110 case TRUTH_ORIF_EXPR:
7111 r = cxx_eval_logical_expression (ctx, t, boolean_true_node,
7112 boolean_false_node,
7113 non_constant_p, overflow_p);
7114 break;
7116 case ARRAY_REF:
7117 r = cxx_eval_array_reference (ctx, t, lval,
7118 non_constant_p, overflow_p);
7119 break;
7121 case COMPONENT_REF:
7122 if (is_overloaded_fn (t))
7124 /* We can only get here in checking mode via
7125 build_non_dependent_expr, because any expression that
7126 calls or takes the address of the function will have
7127 pulled a FUNCTION_DECL out of the COMPONENT_REF. */
7128 gcc_checking_assert (ctx->quiet || errorcount);
7129 *non_constant_p = true;
7130 return t;
7132 r = cxx_eval_component_reference (ctx, t, lval,
7133 non_constant_p, overflow_p);
7134 break;
7136 case BIT_FIELD_REF:
7137 r = cxx_eval_bit_field_ref (ctx, t, lval,
7138 non_constant_p, overflow_p);
7139 break;
7141 case COND_EXPR:
7142 case IF_STMT:
7143 if (jump_target && *jump_target)
7145 tree orig_jump = *jump_target;
7146 tree arg = ((TREE_CODE (t) != IF_STMT || TREE_OPERAND (t, 1))
7147 ? TREE_OPERAND (t, 1) : void_node);
7148 /* When jumping to a label, the label might be either in the
7149 then or else blocks, so process then block first in skipping
7150 mode first, and if we are still in the skipping mode at its end,
7151 process the else block too. */
7152 r = cxx_eval_constant_expression (ctx, arg, lval, non_constant_p,
7153 overflow_p, jump_target);
7154 /* It's possible that we found the label in the then block. But
7155 it could have been followed by another jumping statement, e.g.
7156 say we're looking for case 1:
7157 if (cond)
7159 // skipped statements
7160 case 1:; // clears up *jump_target
7161 return 1; // and sets it to a RETURN_EXPR
7163 else { ... }
7164 in which case we need not go looking to the else block.
7165 (goto is not allowed in a constexpr function.) */
7166 if (*jump_target == orig_jump)
7168 arg = ((TREE_CODE (t) != IF_STMT || TREE_OPERAND (t, 2))
7169 ? TREE_OPERAND (t, 2) : void_node);
7170 r = cxx_eval_constant_expression (ctx, arg, lval, non_constant_p,
7171 overflow_p, jump_target);
7173 break;
7175 r = cxx_eval_conditional_expression (ctx, t, lval,
7176 non_constant_p, overflow_p,
7177 jump_target);
7178 break;
7179 case VEC_COND_EXPR:
7180 r = cxx_eval_vector_conditional_expression (ctx, t, non_constant_p,
7181 overflow_p);
7182 break;
7184 case CONSTRUCTOR:
7185 if (TREE_CONSTANT (t) && reduced_constant_expression_p (t))
7187 /* Don't re-process a constant CONSTRUCTOR, but do fold it to
7188 VECTOR_CST if applicable. */
7189 verify_constructor_flags (t);
7190 if (TREE_CONSTANT (t))
7191 return fold (t);
7193 r = cxx_eval_bare_aggregate (ctx, t, lval,
7194 non_constant_p, overflow_p);
7195 break;
7197 case VEC_INIT_EXPR:
7198 /* We can get this in a defaulted constructor for a class with a
7199 non-static data member of array type. Either the initializer will
7200 be NULL, meaning default-initialization, or it will be an lvalue
7201 or xvalue of the same type, meaning direct-initialization from the
7202 corresponding member. */
7203 r = cxx_eval_vec_init (ctx, t, lval,
7204 non_constant_p, overflow_p);
7205 break;
7207 case VEC_PERM_EXPR:
7208 r = cxx_eval_trinary_expression (ctx, t, lval,
7209 non_constant_p, overflow_p);
7210 break;
7212 case PAREN_EXPR:
7213 gcc_assert (!REF_PARENTHESIZED_P (t));
7214 /* A PAREN_EXPR resulting from __builtin_assoc_barrier has no effect in
7215 constant expressions since it's unaffected by -fassociative-math. */
7216 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
7217 non_constant_p, overflow_p);
7218 break;
7220 case NOP_EXPR:
7221 if (REINTERPRET_CAST_P (t))
7223 if (!ctx->quiet)
7224 error_at (loc,
7225 "%<reinterpret_cast%> is not a constant expression");
7226 *non_constant_p = true;
7227 return t;
7229 /* FALLTHROUGH. */
7230 case CONVERT_EXPR:
7231 case VIEW_CONVERT_EXPR:
7232 case UNARY_PLUS_EXPR:
7234 tree oldop = TREE_OPERAND (t, 0);
7236 tree op = cxx_eval_constant_expression (ctx, oldop,
7237 lval,
7238 non_constant_p, overflow_p);
7239 if (*non_constant_p)
7240 return t;
7241 tree type = TREE_TYPE (t);
7243 if (VOID_TYPE_P (type))
7244 return void_node;
7246 if (TREE_CODE (t) == CONVERT_EXPR
7247 && ARITHMETIC_TYPE_P (type)
7248 && INDIRECT_TYPE_P (TREE_TYPE (op))
7249 && ctx->manifestly_const_eval)
7251 if (!ctx->quiet)
7252 error_at (loc,
7253 "conversion from pointer type %qT to arithmetic type "
7254 "%qT in a constant expression", TREE_TYPE (op), type);
7255 *non_constant_p = true;
7256 return t;
7259 /* [expr.const]: a conversion from type cv void* to a pointer-to-object
7260 type cannot be part of a core constant expression as a resolution to
7261 DR 1312. */
7262 if (TYPE_PTROB_P (type)
7263 && TYPE_PTR_P (TREE_TYPE (op))
7264 && VOID_TYPE_P (TREE_TYPE (TREE_TYPE (op)))
7265 /* Inside a call to std::construct_at or to
7266 std::allocator<T>::{,de}allocate, we permit casting from void*
7267 because that is compiler-generated code. */
7268 && !is_std_construct_at (ctx->call)
7269 && !is_std_allocator_allocate (ctx->call))
7271 /* Likewise, don't error when casting from void* when OP is
7272 &heap uninit and similar. */
7273 tree sop = tree_strip_nop_conversions (op);
7274 if (TREE_CODE (sop) == ADDR_EXPR
7275 && VAR_P (TREE_OPERAND (sop, 0))
7276 && DECL_ARTIFICIAL (TREE_OPERAND (sop, 0)))
7277 /* OK */;
7278 else
7280 if (!ctx->quiet)
7281 error_at (loc, "cast from %qT is not allowed",
7282 TREE_TYPE (op));
7283 *non_constant_p = true;
7284 return t;
7288 if (TREE_CODE (op) == PTRMEM_CST && !TYPE_PTRMEM_P (type))
7289 op = cplus_expand_constant (op);
7291 if (TREE_CODE (op) == PTRMEM_CST && tcode == NOP_EXPR)
7293 if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (op))
7294 && !can_convert_qual (type, op))
7295 op = cplus_expand_constant (op);
7296 return cp_fold_convert (type, op);
7299 if (INDIRECT_TYPE_P (type) && TREE_CODE (op) == INTEGER_CST)
7301 if (integer_zerop (op))
7303 if (TYPE_REF_P (type))
7305 if (!ctx->quiet)
7306 error_at (loc, "dereferencing a null pointer");
7307 *non_constant_p = true;
7308 return t;
7311 else
7313 /* This detects for example:
7314 reinterpret_cast<void*>(sizeof 0)
7316 if (!ctx->quiet)
7317 error_at (loc, "%<reinterpret_cast<%T>(%E)%> is not "
7318 "a constant expression",
7319 type, op);
7320 *non_constant_p = true;
7321 return t;
7325 if (INDIRECT_TYPE_P (type)
7326 && TREE_CODE (op) == NOP_EXPR
7327 && TREE_TYPE (op) == ptr_type_node
7328 && TREE_CODE (TREE_OPERAND (op, 0)) == ADDR_EXPR
7329 && VAR_P (TREE_OPERAND (TREE_OPERAND (op, 0), 0))
7330 && (DECL_NAME (TREE_OPERAND (TREE_OPERAND (op, 0),
7331 0)) == heap_uninit_identifier
7332 || DECL_NAME (TREE_OPERAND (TREE_OPERAND (op, 0),
7333 0)) == heap_vec_uninit_identifier))
7335 tree var = TREE_OPERAND (TREE_OPERAND (op, 0), 0);
7336 tree var_size = TYPE_SIZE_UNIT (TREE_TYPE (var));
7337 tree elt_type = TREE_TYPE (type);
7338 tree cookie_size = NULL_TREE;
7339 tree arg_size = NULL_TREE;
7340 if (TREE_CODE (elt_type) == RECORD_TYPE
7341 && TYPE_NAME (elt_type) == heap_identifier)
7343 tree fld1 = TYPE_FIELDS (elt_type);
7344 tree fld2 = DECL_CHAIN (fld1);
7345 elt_type = TREE_TYPE (TREE_TYPE (fld2));
7346 cookie_size = TYPE_SIZE_UNIT (TREE_TYPE (fld1));
7348 DECL_NAME (var)
7349 = (DECL_NAME (var) == heap_uninit_identifier
7350 ? heap_identifier : heap_vec_identifier);
7351 /* For zero sized elt_type, try to recover how many outer_nelts
7352 it should have. */
7353 if ((cookie_size ? tree_int_cst_equal (var_size, cookie_size)
7354 : integer_zerop (var_size))
7355 && !int_size_in_bytes (elt_type)
7356 && TREE_CODE (oldop) == CALL_EXPR
7357 && call_expr_nargs (oldop) >= 1)
7358 if (tree fun = get_function_named_in_call (oldop))
7359 if (cxx_replaceable_global_alloc_fn (fun)
7360 && IDENTIFIER_NEW_OP_P (DECL_NAME (fun)))
7361 arg_size = CALL_EXPR_ARG (oldop, 0);
7362 TREE_TYPE (var)
7363 = build_new_constexpr_heap_type (ctx, elt_type, cookie_size,
7364 var_size, arg_size,
7365 non_constant_p, overflow_p);
7366 TREE_TYPE (TREE_OPERAND (op, 0))
7367 = build_pointer_type (TREE_TYPE (var));
7370 if (op == oldop && tcode != UNARY_PLUS_EXPR)
7371 /* We didn't fold at the top so we could check for ptr-int
7372 conversion. */
7373 return fold (t);
7375 tree sop;
7377 /* Handle an array's bounds having been deduced after we built
7378 the wrapping expression. */
7379 if (same_type_ignoring_tlq_and_bounds_p (type, TREE_TYPE (op)))
7380 r = op;
7381 else if (sop = tree_strip_nop_conversions (op),
7382 sop != op && (same_type_ignoring_tlq_and_bounds_p
7383 (type, TREE_TYPE (sop))))
7384 r = sop;
7385 else if (tcode == UNARY_PLUS_EXPR)
7386 r = fold_convert (TREE_TYPE (t), op);
7387 else
7388 r = fold_build1 (tcode, type, op);
7390 /* Conversion of an out-of-range value has implementation-defined
7391 behavior; the language considers it different from arithmetic
7392 overflow, which is undefined. */
7393 if (TREE_OVERFLOW_P (r) && !TREE_OVERFLOW_P (op))
7394 TREE_OVERFLOW (r) = false;
7396 break;
7398 case EMPTY_CLASS_EXPR:
7399 /* Handle EMPTY_CLASS_EXPR produced by build_call_a by lowering
7400 it to an appropriate CONSTRUCTOR. */
7401 return build_constructor (TREE_TYPE (t), NULL);
7403 case STATEMENT_LIST:
7404 new_ctx = *ctx;
7405 new_ctx.ctor = new_ctx.object = NULL_TREE;
7406 return cxx_eval_statement_list (&new_ctx, t,
7407 non_constant_p, overflow_p, jump_target);
7409 case BIND_EXPR:
7410 return cxx_eval_constant_expression (ctx, BIND_EXPR_BODY (t),
7411 lval,
7412 non_constant_p, overflow_p,
7413 jump_target);
7415 case PREINCREMENT_EXPR:
7416 case POSTINCREMENT_EXPR:
7417 case PREDECREMENT_EXPR:
7418 case POSTDECREMENT_EXPR:
7419 return cxx_eval_increment_expression (ctx, t,
7420 lval, non_constant_p, overflow_p);
7422 case LAMBDA_EXPR:
7423 case NEW_EXPR:
7424 case VEC_NEW_EXPR:
7425 case DELETE_EXPR:
7426 case VEC_DELETE_EXPR:
7427 case THROW_EXPR:
7428 case MODOP_EXPR:
7429 /* GCC internal stuff. */
7430 case VA_ARG_EXPR:
7431 case NON_DEPENDENT_EXPR:
7432 case BASELINK:
7433 case OFFSET_REF:
7434 if (!ctx->quiet)
7435 error_at (loc, "expression %qE is not a constant expression", t);
7436 *non_constant_p = true;
7437 break;
7439 case OBJ_TYPE_REF:
7440 /* Virtual function lookup. We don't need to do anything fancy. */
7441 return cxx_eval_constant_expression (ctx, OBJ_TYPE_REF_EXPR (t),
7442 lval, non_constant_p, overflow_p);
7444 case PLACEHOLDER_EXPR:
7445 /* Use of the value or address of the current object. */
7446 if (tree ctor = lookup_placeholder (ctx, lval, TREE_TYPE (t)))
7448 if (TREE_CODE (ctor) == CONSTRUCTOR)
7449 return ctor;
7450 else
7451 return cxx_eval_constant_expression (ctx, ctor, lval,
7452 non_constant_p, overflow_p);
7454 /* A placeholder without a referent. We can get here when
7455 checking whether NSDMIs are noexcept, or in massage_init_elt;
7456 just say it's non-constant for now. */
7457 gcc_assert (ctx->quiet);
7458 *non_constant_p = true;
7459 break;
7461 case EXIT_EXPR:
7463 tree cond = TREE_OPERAND (t, 0);
7464 cond = cxx_eval_constant_expression (ctx, cond, /*lval*/false,
7465 non_constant_p, overflow_p);
7466 VERIFY_CONSTANT (cond);
7467 if (integer_nonzerop (cond))
7468 *jump_target = t;
7470 break;
7472 case GOTO_EXPR:
7473 if (breaks (&TREE_OPERAND (t, 0))
7474 || continues (&TREE_OPERAND (t, 0)))
7475 *jump_target = TREE_OPERAND (t, 0);
7476 else
7478 gcc_assert (cxx_dialect >= cxx23);
7479 if (!ctx->quiet)
7480 error_at (loc, "%<goto%> is not a constant expression");
7481 *non_constant_p = true;
7483 break;
7485 case LOOP_EXPR:
7486 case DO_STMT:
7487 case WHILE_STMT:
7488 case FOR_STMT:
7489 cxx_eval_loop_expr (ctx, t,
7490 non_constant_p, overflow_p, jump_target);
7491 break;
7493 case SWITCH_EXPR:
7494 case SWITCH_STMT:
7495 cxx_eval_switch_expr (ctx, t,
7496 non_constant_p, overflow_p, jump_target);
7497 break;
7499 case REQUIRES_EXPR:
7500 /* It's possible to get a requires-expression in a constant
7501 expression. For example:
7503 template<typename T> concept bool C() {
7504 return requires (T t) { t; };
7507 template<typename T> requires !C<T>() void f(T);
7509 Normalization leaves f with the associated constraint
7510 '!requires (T t) { ... }' which is not transformed into
7511 a constraint. */
7512 if (!processing_template_decl)
7513 return evaluate_requires_expr (t);
7514 else
7515 *non_constant_p = true;
7516 return t;
7518 case ANNOTATE_EXPR:
7519 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
7520 lval,
7521 non_constant_p, overflow_p,
7522 jump_target);
7523 break;
7525 case USING_STMT:
7526 r = void_node;
7527 break;
7529 case TEMPLATE_ID_EXPR:
7531 /* We can evaluate template-id that refers to a concept only if
7532 the template arguments are non-dependent. */
7533 tree id = unpack_concept_check (t);
7534 tree tmpl = TREE_OPERAND (id, 0);
7535 if (!concept_definition_p (tmpl))
7536 internal_error ("unexpected template-id %qE", t);
7538 if (function_concept_p (tmpl))
7540 if (!ctx->quiet)
7541 error_at (cp_expr_loc_or_input_loc (t),
7542 "function concept must be called");
7543 r = error_mark_node;
7544 break;
7547 if (!value_dependent_expression_p (t)
7548 && !uid_sensitive_constexpr_evaluation_p ())
7549 r = evaluate_concept_check (t);
7550 else
7551 *non_constant_p = true;
7553 break;
7556 case ASM_EXPR:
7557 if (!ctx->quiet)
7558 inline_asm_in_constexpr_error (loc);
7559 *non_constant_p = true;
7560 return t;
7562 case BIT_CAST_EXPR:
7563 if (lval)
7565 if (!ctx->quiet)
7566 error_at (EXPR_LOCATION (t),
7567 "address of a call to %qs is not a constant expression",
7568 "__builtin_bit_cast");
7569 *non_constant_p = true;
7570 return t;
7572 r = cxx_eval_bit_cast (ctx, t, non_constant_p, overflow_p);
7573 break;
7575 default:
7576 if (STATEMENT_CODE_P (TREE_CODE (t)))
7578 /* This function doesn't know how to deal with pre-genericize
7579 statements; this can only happen with statement-expressions,
7580 so for now just fail. */
7581 if (!ctx->quiet)
7582 error_at (EXPR_LOCATION (t),
7583 "statement is not a constant expression");
7585 else
7586 internal_error ("unexpected expression %qE of kind %s", t,
7587 get_tree_code_name (TREE_CODE (t)));
7588 *non_constant_p = true;
7589 break;
7592 if (r == error_mark_node)
7593 *non_constant_p = true;
7595 if (*non_constant_p)
7596 return t;
7597 else
7598 return r;
7601 /* P0859: A function is needed for constant evaluation if it is a constexpr
7602 function that is named by an expression ([basic.def.odr]) that is
7603 potentially constant evaluated.
7605 So we need to instantiate any constexpr functions mentioned by the
7606 expression even if the definition isn't needed for evaluating the
7607 expression. */
7609 static tree
7610 instantiate_cx_fn_r (tree *tp, int *walk_subtrees, void */*data*/)
7612 if (TREE_CODE (*tp) == FUNCTION_DECL
7613 && DECL_DECLARED_CONSTEXPR_P (*tp)
7614 && !DECL_INITIAL (*tp)
7615 && !trivial_fn_p (*tp)
7616 && DECL_TEMPLOID_INSTANTIATION (*tp)
7617 && !uid_sensitive_constexpr_evaluation_p ())
7619 ++function_depth;
7620 instantiate_decl (*tp, /*defer_ok*/false, /*expl_inst*/false);
7621 --function_depth;
7623 else if (TREE_CODE (*tp) == CALL_EXPR
7624 || TREE_CODE (*tp) == AGGR_INIT_EXPR)
7626 if (EXPR_HAS_LOCATION (*tp))
7627 input_location = EXPR_LOCATION (*tp);
7630 if (!EXPR_P (*tp))
7631 *walk_subtrees = 0;
7633 return NULL_TREE;
7636 static void
7637 instantiate_constexpr_fns (tree t)
7639 location_t loc = input_location;
7640 cp_walk_tree_without_duplicates (&t, instantiate_cx_fn_r, NULL);
7641 input_location = loc;
7644 /* Look for heap variables in the expression *TP. */
7646 static tree
7647 find_heap_var_refs (tree *tp, int *walk_subtrees, void */*data*/)
7649 if (VAR_P (*tp)
7650 && (DECL_NAME (*tp) == heap_uninit_identifier
7651 || DECL_NAME (*tp) == heap_identifier
7652 || DECL_NAME (*tp) == heap_vec_uninit_identifier
7653 || DECL_NAME (*tp) == heap_vec_identifier
7654 || DECL_NAME (*tp) == heap_deleted_identifier))
7655 return *tp;
7657 if (TYPE_P (*tp))
7658 *walk_subtrees = 0;
7659 return NULL_TREE;
7662 /* Find immediate function decls in *TP if any. */
7664 static tree
7665 find_immediate_fndecl (tree *tp, int */*walk_subtrees*/, void */*data*/)
7667 if (TREE_CODE (*tp) == FUNCTION_DECL && DECL_IMMEDIATE_FUNCTION_P (*tp))
7668 return *tp;
7669 if (TREE_CODE (*tp) == PTRMEM_CST
7670 && TREE_CODE (PTRMEM_CST_MEMBER (*tp)) == FUNCTION_DECL
7671 && DECL_IMMEDIATE_FUNCTION_P (PTRMEM_CST_MEMBER (*tp)))
7672 return PTRMEM_CST_MEMBER (*tp);
7673 return NULL_TREE;
7676 /* T has TREE_CONSTANT set but has been deemed not a valid C++ constant
7677 expression. Return a version of T that has TREE_CONSTANT cleared. */
7679 static tree
7680 mark_non_constant (tree t)
7682 gcc_checking_assert (TREE_CONSTANT (t));
7684 /* This isn't actually constant, so unset TREE_CONSTANT.
7685 Don't clear TREE_CONSTANT on ADDR_EXPR, as the middle-end requires
7686 it to be set if it is invariant address, even when it is not
7687 a valid C++ constant expression. Wrap it with a NOP_EXPR
7688 instead. */
7689 if (EXPR_P (t) && TREE_CODE (t) != ADDR_EXPR)
7690 t = copy_node (t);
7691 else if (TREE_CODE (t) == CONSTRUCTOR)
7692 t = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (t), t);
7693 else
7694 t = build_nop (TREE_TYPE (t), t);
7695 TREE_CONSTANT (t) = false;
7696 return t;
7699 /* ALLOW_NON_CONSTANT is false if T is required to be a constant expression.
7700 STRICT has the same sense as for constant_value_1: true if we only allow
7701 conforming C++ constant expressions, or false if we want a constant value
7702 even if it doesn't conform.
7703 MANIFESTLY_CONST_EVAL is true if T is manifestly const-evaluated as
7704 per P0595 even when ALLOW_NON_CONSTANT is true.
7705 CONSTEXPR_DTOR is true when evaluating the dtor of a constexpr variable.
7706 OBJECT must be non-NULL in that case. */
7708 static tree
7709 cxx_eval_outermost_constant_expr (tree t, bool allow_non_constant,
7710 bool strict = true,
7711 bool manifestly_const_eval = false,
7712 bool constexpr_dtor = false,
7713 tree object = NULL_TREE)
7715 auto_timevar time (TV_CONSTEXPR);
7717 bool non_constant_p = false;
7718 bool overflow_p = false;
7720 if (BRACE_ENCLOSED_INITIALIZER_P (t))
7722 gcc_checking_assert (allow_non_constant);
7723 return t;
7726 constexpr_global_ctx global_ctx;
7727 constexpr_ctx ctx = { &global_ctx, NULL, NULL, NULL, NULL, NULL, NULL,
7728 allow_non_constant, strict,
7729 manifestly_const_eval || !allow_non_constant };
7731 /* Turn off -frounding-math for manifestly constant evaluation. */
7732 warning_sentinel rm (flag_rounding_math, ctx.manifestly_const_eval);
7733 tree type = initialized_type (t);
7734 tree r = t;
7735 bool is_consteval = false;
7736 if (VOID_TYPE_P (type))
7738 if (constexpr_dtor)
7739 /* Used for destructors of array elements. */
7740 type = TREE_TYPE (object);
7741 else
7743 if (cxx_dialect < cxx20)
7744 return t;
7745 if (TREE_CODE (t) != CALL_EXPR && TREE_CODE (t) != AGGR_INIT_EXPR)
7746 return t;
7747 /* Calls to immediate functions returning void need to be
7748 evaluated. */
7749 tree fndecl = cp_get_callee_fndecl_nofold (t);
7750 if (fndecl == NULL_TREE || !DECL_IMMEDIATE_FUNCTION_P (fndecl))
7751 return t;
7752 else
7753 is_consteval = true;
7756 else if (cxx_dialect >= cxx20
7757 && (TREE_CODE (t) == CALL_EXPR
7758 || TREE_CODE (t) == AGGR_INIT_EXPR
7759 || TREE_CODE (t) == TARGET_EXPR))
7761 /* For non-concept checks, determine if it is consteval. */
7762 if (!concept_check_p (t))
7764 tree x = t;
7765 if (TREE_CODE (x) == TARGET_EXPR)
7766 x = TARGET_EXPR_INITIAL (x);
7767 tree fndecl = cp_get_callee_fndecl_nofold (x);
7768 if (fndecl && DECL_IMMEDIATE_FUNCTION_P (fndecl))
7769 is_consteval = true;
7772 if (AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type))
7774 /* In C++14 an NSDMI can participate in aggregate initialization,
7775 and can refer to the address of the object being initialized, so
7776 we need to pass in the relevant VAR_DECL if we want to do the
7777 evaluation in a single pass. The evaluation will dynamically
7778 update ctx.values for the VAR_DECL. We use the same strategy
7779 for C++11 constexpr constructors that refer to the object being
7780 initialized. */
7781 if (constexpr_dtor)
7783 gcc_assert (object && VAR_P (object));
7784 gcc_assert (DECL_DECLARED_CONSTEXPR_P (object));
7785 gcc_assert (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (object));
7786 if (error_operand_p (DECL_INITIAL (object)))
7787 return t;
7788 ctx.ctor = unshare_expr (DECL_INITIAL (object));
7789 TREE_READONLY (ctx.ctor) = false;
7790 /* Temporarily force decl_really_constant_value to return false
7791 for it, we want to use ctx.ctor for the current value instead. */
7792 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (object) = false;
7794 else
7796 ctx.ctor = build_constructor (type, NULL);
7797 CONSTRUCTOR_NO_CLEARING (ctx.ctor) = true;
7799 if (!object)
7801 if (TREE_CODE (t) == TARGET_EXPR)
7802 object = TARGET_EXPR_SLOT (t);
7803 else if (TREE_CODE (t) == AGGR_INIT_EXPR)
7804 object = AGGR_INIT_EXPR_SLOT (t);
7806 ctx.object = object;
7807 if (object)
7808 gcc_assert (same_type_ignoring_top_level_qualifiers_p
7809 (type, TREE_TYPE (object)));
7810 if (object && DECL_P (object))
7811 global_ctx.values.put (object, ctx.ctor);
7812 if (TREE_CODE (r) == TARGET_EXPR)
7813 /* Avoid creating another CONSTRUCTOR when we expand the
7814 TARGET_EXPR. */
7815 r = TARGET_EXPR_INITIAL (r);
7818 auto_vec<tree, 16> cleanups;
7819 global_ctx.cleanups = &cleanups;
7821 if (manifestly_const_eval)
7822 instantiate_constexpr_fns (r);
7823 r = cxx_eval_constant_expression (&ctx, r,
7824 false, &non_constant_p, &overflow_p);
7826 if (!constexpr_dtor)
7827 verify_constant (r, allow_non_constant, &non_constant_p, &overflow_p);
7828 else
7829 DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (object) = true;
7831 unsigned int i;
7832 tree cleanup;
7833 /* Evaluate the cleanups. */
7834 FOR_EACH_VEC_ELT_REVERSE (cleanups, i, cleanup)
7835 cxx_eval_constant_expression (&ctx, cleanup, false,
7836 &non_constant_p, &overflow_p);
7838 /* Mutable logic is a bit tricky: we want to allow initialization of
7839 constexpr variables with mutable members, but we can't copy those
7840 members to another constexpr variable. */
7841 if (TREE_CODE (r) == CONSTRUCTOR && CONSTRUCTOR_MUTABLE_POISON (r))
7843 if (!allow_non_constant)
7844 error ("%qE is not a constant expression because it refers to "
7845 "mutable subobjects of %qT", t, type);
7846 non_constant_p = true;
7849 if (TREE_CODE (r) == CONSTRUCTOR && CONSTRUCTOR_NO_CLEARING (r))
7851 if (!allow_non_constant)
7852 error ("%qE is not a constant expression because it refers to "
7853 "an incompletely initialized variable", t);
7854 TREE_CONSTANT (r) = false;
7855 non_constant_p = true;
7858 if (!global_ctx.heap_vars.is_empty ())
7860 tree heap_var = cp_walk_tree_without_duplicates (&r, find_heap_var_refs,
7861 NULL);
7862 unsigned int i;
7863 if (heap_var)
7865 if (!allow_non_constant && !non_constant_p)
7866 error_at (DECL_SOURCE_LOCATION (heap_var),
7867 "%qE is not a constant expression because it refers to "
7868 "a result of %<operator new%>", t);
7869 r = t;
7870 non_constant_p = true;
7872 FOR_EACH_VEC_ELT (global_ctx.heap_vars, i, heap_var)
7874 if (DECL_NAME (heap_var) != heap_deleted_identifier)
7876 if (!allow_non_constant && !non_constant_p)
7877 error_at (DECL_SOURCE_LOCATION (heap_var),
7878 "%qE is not a constant expression because allocated "
7879 "storage has not been deallocated", t);
7880 r = t;
7881 non_constant_p = true;
7883 varpool_node::get (heap_var)->remove ();
7887 /* Check that immediate invocation does not return an expression referencing
7888 any immediate function decls. */
7889 if (is_consteval || in_immediate_context ())
7890 if (tree immediate_fndecl
7891 = cp_walk_tree_without_duplicates (&r, find_immediate_fndecl,
7892 NULL))
7894 if (!allow_non_constant && !non_constant_p)
7895 error_at (cp_expr_loc_or_input_loc (t),
7896 "immediate evaluation returns address of immediate "
7897 "function %qD", immediate_fndecl);
7898 r = t;
7899 non_constant_p = true;
7902 if (non_constant_p)
7903 /* If we saw something bad, go back to our argument. The wrapping below is
7904 only for the cases of TREE_CONSTANT argument or overflow. */
7905 r = t;
7907 if (!non_constant_p && overflow_p)
7908 non_constant_p = true;
7910 /* Unshare the result. */
7911 bool should_unshare = true;
7912 if (r == t || (TREE_CODE (t) == TARGET_EXPR
7913 && TARGET_EXPR_INITIAL (t) == r))
7914 should_unshare = false;
7916 if (non_constant_p && !allow_non_constant)
7917 return error_mark_node;
7918 else if (constexpr_dtor)
7919 return r;
7920 else if (non_constant_p && TREE_CONSTANT (r))
7921 r = mark_non_constant (r);
7922 else if (non_constant_p)
7923 return t;
7925 if (should_unshare)
7926 r = unshare_expr (r);
7928 if (TREE_CODE (r) == CONSTRUCTOR && CLASS_TYPE_P (TREE_TYPE (r)))
7930 r = adjust_temp_type (type, r);
7931 if (TREE_CODE (t) == TARGET_EXPR
7932 && TARGET_EXPR_INITIAL (t) == r)
7933 return t;
7934 else if (TREE_CODE (t) == CONSTRUCTOR)
7936 else if (TREE_CODE (t) == TARGET_EXPR && TARGET_EXPR_CLEANUP (t))
7937 r = get_target_expr (r);
7938 else
7940 r = get_target_expr_sfinae (r, tf_warning_or_error | tf_no_cleanup);
7941 TREE_CONSTANT (r) = true;
7945 /* Remember the original location if that wouldn't need a wrapper. */
7946 if (location_t loc = EXPR_LOCATION (t))
7947 protected_set_expr_location (r, loc);
7949 return r;
7952 /* If T represents a constant expression returns its reduced value.
7953 Otherwise return error_mark_node. If T is dependent, then
7954 return NULL. */
7956 tree
7957 cxx_constant_value (tree t, tree decl)
7959 return cxx_eval_outermost_constant_expr (t, false, true, true, false, decl);
7962 /* As above, but respect SFINAE. */
7964 tree
7965 cxx_constant_value_sfinae (tree t, tree decl, tsubst_flags_t complain)
7967 bool sfinae = !(complain & tf_error);
7968 tree r = cxx_eval_outermost_constant_expr (t, sfinae, true, true, false, decl);
7969 if (sfinae && !TREE_CONSTANT (r))
7970 r = error_mark_node;
7971 return r;
7974 /* Like cxx_constant_value, but used for evaluation of constexpr destructors
7975 of constexpr variables. The actual initializer of DECL is not modified. */
7977 void
7978 cxx_constant_dtor (tree t, tree decl)
7980 cxx_eval_outermost_constant_expr (t, false, true, true, true, decl);
7983 /* Helper routine for fold_simple function. Either return simplified
7984 expression T, otherwise NULL_TREE.
7985 In contrast to cp_fully_fold, and to maybe_constant_value, we try to fold
7986 even if we are within template-declaration. So be careful on call, as in
7987 such case types can be undefined. */
7989 static tree
7990 fold_simple_1 (tree t)
7992 tree op1;
7993 enum tree_code code = TREE_CODE (t);
7995 switch (code)
7997 case INTEGER_CST:
7998 case REAL_CST:
7999 case VECTOR_CST:
8000 case FIXED_CST:
8001 case COMPLEX_CST:
8002 return t;
8004 case SIZEOF_EXPR:
8005 return fold_sizeof_expr (t);
8007 case ABS_EXPR:
8008 case ABSU_EXPR:
8009 case CONJ_EXPR:
8010 case REALPART_EXPR:
8011 case IMAGPART_EXPR:
8012 case NEGATE_EXPR:
8013 case BIT_NOT_EXPR:
8014 case TRUTH_NOT_EXPR:
8015 case VIEW_CONVERT_EXPR:
8016 CASE_CONVERT:
8017 case FLOAT_EXPR:
8018 case FIX_TRUNC_EXPR:
8019 case FIXED_CONVERT_EXPR:
8020 case ADDR_SPACE_CONVERT_EXPR:
8022 op1 = TREE_OPERAND (t, 0);
8024 t = const_unop (code, TREE_TYPE (t), op1);
8025 if (!t)
8026 return NULL_TREE;
8028 if (CONVERT_EXPR_CODE_P (code)
8029 && TREE_OVERFLOW_P (t) && !TREE_OVERFLOW_P (op1))
8030 TREE_OVERFLOW (t) = false;
8031 return t;
8033 default:
8034 return NULL_TREE;
8038 /* If T is a simple constant expression, returns its simplified value.
8039 Otherwise returns T. In contrast to maybe_constant_value we
8040 simplify only few operations on constant-expressions, and we don't
8041 try to simplify constexpressions. */
8043 tree
8044 fold_simple (tree t)
8046 if (processing_template_decl)
8047 return t;
8049 tree r = fold_simple_1 (t);
8050 if (r)
8051 return r;
8053 return t;
8056 /* If T is a constant expression, returns its reduced value.
8057 Otherwise, if T does not have TREE_CONSTANT set, returns T.
8058 Otherwise, returns a version of T without TREE_CONSTANT.
8059 MANIFESTLY_CONST_EVAL is true if T is manifestly const-evaluated
8060 as per P0595. */
8062 static GTY((deletable)) hash_map<tree, tree> *cv_cache;
8064 tree
8065 maybe_constant_value (tree t, tree decl, bool manifestly_const_eval)
8067 tree r;
8069 if (!is_nondependent_constant_expression (t))
8071 if (TREE_OVERFLOW_P (t)
8072 || (!processing_template_decl && TREE_CONSTANT (t)))
8073 t = mark_non_constant (t);
8074 return t;
8076 else if (CONSTANT_CLASS_P (t))
8077 /* No caching or evaluation needed. */
8078 return t;
8080 if (manifestly_const_eval)
8081 return cxx_eval_outermost_constant_expr (t, true, true, true, false, decl);
8083 if (cv_cache == NULL)
8084 cv_cache = hash_map<tree, tree>::create_ggc (101);
8085 if (tree *cached = cv_cache->get (t))
8087 r = *cached;
8088 if (r != t)
8090 r = break_out_target_exprs (r, /*clear_loc*/true);
8091 protected_set_expr_location (r, EXPR_LOCATION (t));
8093 return r;
8096 /* Don't evaluate an unevaluated operand. */
8097 if (cp_unevaluated_operand)
8098 return t;
8100 uid_sensitive_constexpr_evaluation_checker c;
8101 r = cxx_eval_outermost_constant_expr (t, true, true, false, false, decl);
8102 gcc_checking_assert (r == t
8103 || CONVERT_EXPR_P (t)
8104 || TREE_CODE (t) == VIEW_CONVERT_EXPR
8105 || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
8106 || !cp_tree_equal (r, t));
8107 if (!c.evaluation_restricted_p ())
8108 cv_cache->put (t, r);
8109 return r;
8112 /* Dispose of the whole CV_CACHE. */
8114 static void
8115 clear_cv_cache (void)
8117 if (cv_cache != NULL)
8118 cv_cache->empty ();
8121 /* Dispose of the whole CV_CACHE and FOLD_CACHE. */
8123 void
8124 clear_cv_and_fold_caches ()
8126 clear_cv_cache ();
8127 clear_fold_cache ();
8130 /* Internal function handling expressions in templates for
8131 fold_non_dependent_expr and fold_non_dependent_init.
8133 If we're in a template, but T isn't value dependent, simplify
8134 it. We're supposed to treat:
8136 template <typename T> void f(T[1 + 1]);
8137 template <typename T> void f(T[2]);
8139 as two declarations of the same function, for example. */
8141 static tree
8142 fold_non_dependent_expr_template (tree t, tsubst_flags_t complain,
8143 bool manifestly_const_eval,
8144 tree object)
8146 gcc_assert (processing_template_decl);
8148 if (is_nondependent_constant_expression (t))
8150 processing_template_decl_sentinel s;
8151 t = instantiate_non_dependent_expr_internal (t, complain);
8153 if (type_unknown_p (t) || BRACE_ENCLOSED_INITIALIZER_P (t))
8155 if (TREE_OVERFLOW_P (t))
8157 t = build_nop (TREE_TYPE (t), t);
8158 TREE_CONSTANT (t) = false;
8160 return t;
8163 if (cp_unevaluated_operand && !manifestly_const_eval)
8164 return t;
8166 tree r = cxx_eval_outermost_constant_expr (t, true, true,
8167 manifestly_const_eval,
8168 false, object);
8169 /* cp_tree_equal looks through NOPs, so allow them. */
8170 gcc_checking_assert (r == t
8171 || CONVERT_EXPR_P (t)
8172 || TREE_CODE (t) == VIEW_CONVERT_EXPR
8173 || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
8174 || !cp_tree_equal (r, t));
8175 return r;
8177 else if (TREE_OVERFLOW_P (t))
8179 t = build_nop (TREE_TYPE (t), t);
8180 TREE_CONSTANT (t) = false;
8183 return t;
8186 /* Like maybe_constant_value but first fully instantiate the argument.
8188 Note: this is equivalent to instantiate_non_dependent_expr_sfinae
8189 (t, complain) followed by maybe_constant_value but is more efficient,
8190 because it calls instantiation_dependent_expression_p and
8191 potential_constant_expression at most once.
8192 The manifestly_const_eval argument is passed to maybe_constant_value.
8194 Callers should generally pass their active complain, or if they are in a
8195 non-template, diagnosing context, they can use the default of
8196 tf_warning_or_error. Callers that might be within a template context, don't
8197 have a complain parameter, and aren't going to remember the result for long
8198 (e.g. null_ptr_cst_p), can pass tf_none and deal with error_mark_node
8199 appropriately. */
8201 tree
8202 fold_non_dependent_expr (tree t,
8203 tsubst_flags_t complain /* = tf_warning_or_error */,
8204 bool manifestly_const_eval /* = false */,
8205 tree object /* = NULL_TREE */)
8207 if (t == NULL_TREE)
8208 return NULL_TREE;
8210 if (processing_template_decl)
8211 return fold_non_dependent_expr_template (t, complain,
8212 manifestly_const_eval, object);
8214 return maybe_constant_value (t, object, manifestly_const_eval);
8217 /* Like fold_non_dependent_expr, but if EXPR couldn't be folded to a constant,
8218 return the original expression. */
8220 tree
8221 maybe_fold_non_dependent_expr (tree expr,
8222 tsubst_flags_t complain/*=tf_warning_or_error*/)
8224 tree t = fold_non_dependent_expr (expr, complain);
8225 if (t && TREE_CONSTANT (t))
8226 return t;
8228 return expr;
8231 /* Like maybe_constant_init but first fully instantiate the argument. */
8233 tree
8234 fold_non_dependent_init (tree t,
8235 tsubst_flags_t complain /*=tf_warning_or_error*/,
8236 bool manifestly_const_eval /*=false*/,
8237 tree object /* = NULL_TREE */)
8239 if (t == NULL_TREE)
8240 return NULL_TREE;
8242 if (processing_template_decl)
8244 t = fold_non_dependent_expr_template (t, complain,
8245 manifestly_const_eval, object);
8246 /* maybe_constant_init does this stripping, so do it here too. */
8247 if (TREE_CODE (t) == TARGET_EXPR)
8249 tree init = TARGET_EXPR_INITIAL (t);
8250 if (TREE_CODE (init) == CONSTRUCTOR)
8251 t = init;
8253 return t;
8256 return maybe_constant_init (t, object, manifestly_const_eval);
8259 /* Like maybe_constant_value, but returns a CONSTRUCTOR directly, rather
8260 than wrapped in a TARGET_EXPR.
8261 ALLOW_NON_CONSTANT is false if T is required to be a constant expression.
8262 MANIFESTLY_CONST_EVAL is true if T is manifestly const-evaluated as
8263 per P0595 even when ALLOW_NON_CONSTANT is true. */
8265 static tree
8266 maybe_constant_init_1 (tree t, tree decl, bool allow_non_constant,
8267 bool manifestly_const_eval)
8269 if (!t)
8270 return t;
8271 if (TREE_CODE (t) == EXPR_STMT)
8272 t = TREE_OPERAND (t, 0);
8273 if (TREE_CODE (t) == CONVERT_EXPR
8274 && VOID_TYPE_P (TREE_TYPE (t)))
8275 t = TREE_OPERAND (t, 0);
8276 if (TREE_CODE (t) == INIT_EXPR)
8277 t = TREE_OPERAND (t, 1);
8278 if (TREE_CODE (t) == TARGET_EXPR)
8279 t = TARGET_EXPR_INITIAL (t);
8280 if (!is_nondependent_static_init_expression (t))
8281 /* Don't try to evaluate it. */;
8282 else if (CONSTANT_CLASS_P (t) && allow_non_constant)
8283 /* No evaluation needed. */;
8284 else
8285 t = cxx_eval_outermost_constant_expr (t, allow_non_constant,
8286 /*strict*/false,
8287 manifestly_const_eval, false, decl);
8288 if (TREE_CODE (t) == TARGET_EXPR)
8290 tree init = TARGET_EXPR_INITIAL (t);
8291 if (TREE_CODE (init) == CONSTRUCTOR)
8292 t = init;
8294 return t;
8297 /* Wrapper for maybe_constant_init_1 which permits non constants. */
8299 tree
8300 maybe_constant_init (tree t, tree decl, bool manifestly_const_eval)
8302 return maybe_constant_init_1 (t, decl, true, manifestly_const_eval);
8305 /* Wrapper for maybe_constant_init_1 which does not permit non constants. */
8307 tree
8308 cxx_constant_init (tree t, tree decl)
8310 return maybe_constant_init_1 (t, decl, false, true);
8313 #if 0
8314 /* FIXME see ADDR_EXPR section in potential_constant_expression_1. */
8315 /* Return true if the object referred to by REF has automatic or thread
8316 local storage. */
8318 enum { ck_ok, ck_bad, ck_unknown };
8319 static int
8320 check_automatic_or_tls (tree ref)
8322 machine_mode mode;
8323 poly_int64 bitsize, bitpos;
8324 tree offset;
8325 int volatilep = 0, unsignedp = 0;
8326 tree decl = get_inner_reference (ref, &bitsize, &bitpos, &offset,
8327 &mode, &unsignedp, &volatilep, false);
8328 duration_kind dk;
8330 /* If there isn't a decl in the middle, we don't know the linkage here,
8331 and this isn't a constant expression anyway. */
8332 if (!DECL_P (decl))
8333 return ck_unknown;
8334 dk = decl_storage_duration (decl);
8335 return (dk == dk_auto || dk == dk_thread) ? ck_bad : ck_ok;
8337 #endif
8339 /* Data structure for passing data from potential_constant_expression_1
8340 to check_for_return_continue via cp_walk_tree. */
8341 struct check_for_return_continue_data {
8342 hash_set<tree> *pset;
8343 tree continue_stmt;
8344 tree break_stmt;
8347 /* Helper function for potential_constant_expression_1 SWITCH_STMT handling,
8348 called through cp_walk_tree. Return the first RETURN_EXPR found, or note
8349 the first CONTINUE_STMT and/or BREAK_STMT if RETURN_EXPR is not found. */
8350 static tree
8351 check_for_return_continue (tree *tp, int *walk_subtrees, void *data)
8353 tree t = *tp, s, b;
8354 check_for_return_continue_data *d = (check_for_return_continue_data *) data;
8355 switch (TREE_CODE (t))
8357 case RETURN_EXPR:
8358 return t;
8360 case CONTINUE_STMT:
8361 if (d->continue_stmt == NULL_TREE)
8362 d->continue_stmt = t;
8363 break;
8365 case BREAK_STMT:
8366 if (d->break_stmt == NULL_TREE)
8367 d->break_stmt = t;
8368 break;
8370 #define RECUR(x) \
8371 if (tree r = cp_walk_tree (&x, check_for_return_continue, data, \
8372 d->pset)) \
8373 return r
8375 /* For loops, walk subtrees manually, so that continue stmts found
8376 inside of the bodies of the loops are ignored. */
8377 case DO_STMT:
8378 *walk_subtrees = 0;
8379 RECUR (DO_COND (t));
8380 s = d->continue_stmt;
8381 b = d->break_stmt;
8382 RECUR (DO_BODY (t));
8383 d->continue_stmt = s;
8384 d->break_stmt = b;
8385 break;
8387 case WHILE_STMT:
8388 *walk_subtrees = 0;
8389 RECUR (WHILE_COND (t));
8390 s = d->continue_stmt;
8391 b = d->break_stmt;
8392 RECUR (WHILE_BODY (t));
8393 d->continue_stmt = s;
8394 d->break_stmt = b;
8395 break;
8397 case FOR_STMT:
8398 *walk_subtrees = 0;
8399 RECUR (FOR_INIT_STMT (t));
8400 RECUR (FOR_COND (t));
8401 RECUR (FOR_EXPR (t));
8402 s = d->continue_stmt;
8403 b = d->break_stmt;
8404 RECUR (FOR_BODY (t));
8405 d->continue_stmt = s;
8406 d->break_stmt = b;
8407 break;
8409 case RANGE_FOR_STMT:
8410 *walk_subtrees = 0;
8411 RECUR (RANGE_FOR_EXPR (t));
8412 s = d->continue_stmt;
8413 b = d->break_stmt;
8414 RECUR (RANGE_FOR_BODY (t));
8415 d->continue_stmt = s;
8416 d->break_stmt = b;
8417 break;
8419 case SWITCH_STMT:
8420 *walk_subtrees = 0;
8421 RECUR (SWITCH_STMT_COND (t));
8422 b = d->break_stmt;
8423 RECUR (SWITCH_STMT_BODY (t));
8424 d->break_stmt = b;
8425 break;
8426 #undef RECUR
8428 case STATEMENT_LIST:
8429 case CONSTRUCTOR:
8430 break;
8432 default:
8433 if (!EXPR_P (t))
8434 *walk_subtrees = 0;
8435 break;
8438 return NULL_TREE;
8441 /* Return true if T denotes a potentially constant expression. Issue
8442 diagnostic as appropriate under control of FLAGS. If WANT_RVAL is true,
8443 an lvalue-rvalue conversion is implied. If NOW is true, we want to
8444 consider the expression in the current context, independent of constexpr
8445 substitution.
8447 C++0x [expr.const] used to say
8449 6 An expression is a potential constant expression if it is
8450 a constant expression where all occurrences of function
8451 parameters are replaced by arbitrary constant expressions
8452 of the appropriate type.
8454 2 A conditional expression is a constant expression unless it
8455 involves one of the following as a potentially evaluated
8456 subexpression (3.2), but subexpressions of logical AND (5.14),
8457 logical OR (5.15), and conditional (5.16) operations that are
8458 not evaluated are not considered. */
8460 static bool
8461 potential_constant_expression_1 (tree t, bool want_rval, bool strict, bool now,
8462 tsubst_flags_t flags, tree *jump_target)
8464 #define RECUR(T,RV) \
8465 potential_constant_expression_1 ((T), (RV), strict, now, flags, jump_target)
8467 enum { any = false, rval = true };
8468 int i;
8469 tree tmp;
8471 if (t == error_mark_node)
8472 return false;
8473 if (t == NULL_TREE)
8474 return true;
8475 location_t loc = cp_expr_loc_or_input_loc (t);
8477 if (*jump_target)
8478 /* If we are jumping, ignore everything. This is simpler than the
8479 cxx_eval_constant_expression handling because we only need to be
8480 conservatively correct, and we don't necessarily have a constant value
8481 available, so we don't bother with switch tracking. */
8482 return true;
8484 if (TREE_THIS_VOLATILE (t) && want_rval)
8486 if (flags & tf_error)
8487 error_at (loc, "lvalue-to-rvalue conversion of a volatile lvalue "
8488 "%qE with type %qT", t, TREE_TYPE (t));
8489 return false;
8491 if (CONSTANT_CLASS_P (t))
8492 return true;
8493 if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_TYPED)
8494 && TREE_TYPE (t) == error_mark_node)
8495 return false;
8497 switch (TREE_CODE (t))
8499 case FUNCTION_DECL:
8500 case BASELINK:
8501 case TEMPLATE_DECL:
8502 case OVERLOAD:
8503 case TEMPLATE_ID_EXPR:
8504 case LABEL_DECL:
8505 case CASE_LABEL_EXPR:
8506 case PREDICT_EXPR:
8507 case CONST_DECL:
8508 case SIZEOF_EXPR:
8509 case ALIGNOF_EXPR:
8510 case OFFSETOF_EXPR:
8511 case NOEXCEPT_EXPR:
8512 case TEMPLATE_PARM_INDEX:
8513 case TRAIT_EXPR:
8514 case IDENTIFIER_NODE:
8515 case USERDEF_LITERAL:
8516 /* We can see a FIELD_DECL in a pointer-to-member expression. */
8517 case FIELD_DECL:
8518 case RESULT_DECL:
8519 case USING_DECL:
8520 case USING_STMT:
8521 case PLACEHOLDER_EXPR:
8522 case REQUIRES_EXPR:
8523 case STATIC_ASSERT:
8524 case DEBUG_BEGIN_STMT:
8525 return true;
8527 case RETURN_EXPR:
8528 if (!RECUR (TREE_OPERAND (t, 0), any))
8529 return false;
8530 /* FALLTHROUGH */
8532 case BREAK_STMT:
8533 case CONTINUE_STMT:
8534 *jump_target = t;
8535 return true;
8537 case PARM_DECL:
8538 if (now && want_rval)
8540 tree type = TREE_TYPE (t);
8541 if ((processing_template_decl && !COMPLETE_TYPE_P (type))
8542 || dependent_type_p (type)
8543 || is_really_empty_class (type, /*ignore_vptr*/false))
8544 /* An empty class has no data to read. */
8545 return true;
8546 if (flags & tf_error)
8547 error ("%qE is not a constant expression", t);
8548 return false;
8550 return true;
8552 case AGGR_INIT_EXPR:
8553 case CALL_EXPR:
8554 /* -- an invocation of a function other than a constexpr function
8555 or a constexpr constructor. */
8557 tree fun = get_function_named_in_call (t);
8558 const int nargs = call_expr_nargs (t);
8559 i = 0;
8561 if (fun == NULL_TREE)
8563 /* Reset to allow the function to continue past the end
8564 of the block below. Otherwise return early. */
8565 bool bail = true;
8567 if (TREE_CODE (t) == CALL_EXPR
8568 && CALL_EXPR_FN (t) == NULL_TREE)
8569 switch (CALL_EXPR_IFN (t))
8571 /* These should be ignored, they are optimized away from
8572 constexpr functions. */
8573 case IFN_UBSAN_NULL:
8574 case IFN_UBSAN_BOUNDS:
8575 case IFN_UBSAN_VPTR:
8576 case IFN_FALLTHROUGH:
8577 return true;
8579 case IFN_ADD_OVERFLOW:
8580 case IFN_SUB_OVERFLOW:
8581 case IFN_MUL_OVERFLOW:
8582 case IFN_LAUNDER:
8583 case IFN_VEC_CONVERT:
8584 bail = false;
8585 break;
8587 default:
8588 break;
8591 if (bail)
8593 /* fold_call_expr can't do anything with IFN calls. */
8594 if (flags & tf_error)
8595 error_at (loc, "call to internal function %qE", t);
8596 return false;
8600 if (fun && is_overloaded_fn (fun))
8602 if (TREE_CODE (fun) == FUNCTION_DECL)
8604 if (builtin_valid_in_constant_expr_p (fun))
8605 return true;
8606 if (!maybe_constexpr_fn (fun)
8607 /* Allow any built-in function; if the expansion
8608 isn't constant, we'll deal with that then. */
8609 && !fndecl_built_in_p (fun)
8610 /* In C++20, replaceable global allocation functions
8611 are constant expressions. */
8612 && (!cxx_replaceable_global_alloc_fn (fun)
8613 || TREE_CODE (t) != CALL_EXPR
8614 || (!CALL_FROM_NEW_OR_DELETE_P (t)
8615 && (current_function_decl == NULL_TREE
8616 || !is_std_allocator_allocate
8617 (current_function_decl))))
8618 /* Allow placement new in std::construct_at. */
8619 && (!cxx_placement_new_fn (fun)
8620 || TREE_CODE (t) != CALL_EXPR
8621 || current_function_decl == NULL_TREE
8622 || !is_std_construct_at (current_function_decl))
8623 && !cxx_dynamic_cast_fn_p (fun))
8625 if (flags & tf_error)
8627 error_at (loc, "call to non-%<constexpr%> function %qD",
8628 fun);
8629 explain_invalid_constexpr_fn (fun);
8631 return false;
8633 /* A call to a non-static member function takes the address
8634 of the object as the first argument. But in a constant
8635 expression the address will be folded away, so look
8636 through it now. */
8637 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fun)
8638 && !DECL_CONSTRUCTOR_P (fun))
8640 tree x = get_nth_callarg (t, 0);
8641 if (is_this_parameter (x))
8642 return true;
8643 /* Don't require an immediately constant value, as
8644 constexpr substitution might not use the value. */
8645 bool sub_now = false;
8646 if (!potential_constant_expression_1 (x, rval, strict,
8647 sub_now, flags,
8648 jump_target))
8649 return false;
8650 i = 1;
8653 else
8655 if (!RECUR (fun, true))
8656 return false;
8657 fun = get_first_fn (fun);
8659 /* Skip initial arguments to base constructors. */
8660 if (DECL_BASE_CONSTRUCTOR_P (fun))
8661 i = num_artificial_parms_for (fun);
8662 fun = DECL_ORIGIN (fun);
8664 else if (fun)
8666 if (RECUR (fun, rval))
8667 /* Might end up being a constant function pointer. */;
8668 else
8669 return false;
8671 for (; i < nargs; ++i)
8673 tree x = get_nth_callarg (t, i);
8674 /* In a template, reference arguments haven't been converted to
8675 REFERENCE_TYPE and we might not even know if the parameter
8676 is a reference, so accept lvalue constants too. */
8677 bool rv = processing_template_decl ? any : rval;
8678 /* Don't require an immediately constant value, as constexpr
8679 substitution might not use the value of the argument. */
8680 bool sub_now = false;
8681 if (!potential_constant_expression_1 (x, rv, strict,
8682 sub_now, flags, jump_target))
8683 return false;
8685 return true;
8688 case NON_LVALUE_EXPR:
8689 /* -- an lvalue-to-rvalue conversion (4.1) unless it is applied to
8690 -- an lvalue of integral type that refers to a non-volatile
8691 const variable or static data member initialized with
8692 constant expressions, or
8694 -- an lvalue of literal type that refers to non-volatile
8695 object defined with constexpr, or that refers to a
8696 sub-object of such an object; */
8697 return RECUR (TREE_OPERAND (t, 0), rval);
8699 case VAR_DECL:
8700 if (DECL_HAS_VALUE_EXPR_P (t))
8702 if (now && is_normal_capture_proxy (t))
8704 /* -- in a lambda-expression, a reference to this or to a
8705 variable with automatic storage duration defined outside that
8706 lambda-expression, where the reference would be an
8707 odr-use. */
8709 if (want_rval)
8710 /* Since we're doing an lvalue-rvalue conversion, this might
8711 not be an odr-use, so evaluate the variable directly. */
8712 return RECUR (DECL_CAPTURED_VARIABLE (t), rval);
8714 if (flags & tf_error)
8716 tree cap = DECL_CAPTURED_VARIABLE (t);
8717 error ("lambda capture of %qE is not a constant expression",
8718 cap);
8719 if (decl_constant_var_p (cap))
8720 inform (input_location, "because it is used as a glvalue");
8722 return false;
8724 /* Treat __PRETTY_FUNCTION__ inside a template function as
8725 potentially-constant. */
8726 else if (DECL_PRETTY_FUNCTION_P (t)
8727 && DECL_VALUE_EXPR (t) == error_mark_node)
8728 return true;
8729 return RECUR (DECL_VALUE_EXPR (t), rval);
8731 if (want_rval
8732 && !var_in_maybe_constexpr_fn (t)
8733 && !type_dependent_expression_p (t)
8734 && !decl_maybe_constant_var_p (t)
8735 && (strict
8736 || !CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (t))
8737 || (DECL_INITIAL (t)
8738 && !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t)))
8739 && COMPLETE_TYPE_P (TREE_TYPE (t))
8740 && !is_really_empty_class (TREE_TYPE (t), /*ignore_vptr*/false))
8742 if (flags & tf_error)
8743 non_const_var_error (loc, t);
8744 return false;
8746 return true;
8748 case NOP_EXPR:
8749 if (REINTERPRET_CAST_P (t))
8751 if (flags & tf_error)
8752 error_at (loc, "%<reinterpret_cast%> is not a constant expression");
8753 return false;
8755 /* FALLTHRU */
8756 case CONVERT_EXPR:
8757 case VIEW_CONVERT_EXPR:
8758 /* -- a reinterpret_cast. FIXME not implemented, and this rule
8759 may change to something more specific to type-punning (DR 1312). */
8761 tree from = TREE_OPERAND (t, 0);
8762 if (location_wrapper_p (t))
8763 return (RECUR (from, want_rval));
8764 if (INDIRECT_TYPE_P (TREE_TYPE (t)))
8766 STRIP_ANY_LOCATION_WRAPPER (from);
8767 if (TREE_CODE (from) == INTEGER_CST
8768 && !integer_zerop (from))
8770 if (flags & tf_error)
8771 error_at (loc,
8772 "%<reinterpret_cast%> from integer to pointer");
8773 return false;
8776 return (RECUR (from, TREE_CODE (t) != VIEW_CONVERT_EXPR));
8779 case ADDRESSOF_EXPR:
8780 /* This is like ADDR_EXPR, except it won't form pointer-to-member. */
8781 t = TREE_OPERAND (t, 0);
8782 goto handle_addr_expr;
8784 case ADDR_EXPR:
8785 /* -- a unary operator & that is applied to an lvalue that
8786 designates an object with thread or automatic storage
8787 duration; */
8788 t = TREE_OPERAND (t, 0);
8790 if (TREE_CODE (t) == OFFSET_REF && PTRMEM_OK_P (t))
8791 /* A pointer-to-member constant. */
8792 return true;
8794 handle_addr_expr:
8795 #if 0
8796 /* FIXME adjust when issue 1197 is fully resolved. For now don't do
8797 any checking here, as we might dereference the pointer later. If
8798 we remove this code, also remove check_automatic_or_tls. */
8799 i = check_automatic_or_tls (t);
8800 if (i == ck_ok)
8801 return true;
8802 if (i == ck_bad)
8804 if (flags & tf_error)
8805 error ("address-of an object %qE with thread local or "
8806 "automatic storage is not a constant expression", t);
8807 return false;
8809 #endif
8810 return RECUR (t, any);
8812 case COMPONENT_REF:
8813 case ARROW_EXPR:
8814 case OFFSET_REF:
8815 /* -- a class member access unless its postfix-expression is
8816 of literal type or of pointer to literal type. */
8817 /* This test would be redundant, as it follows from the
8818 postfix-expression being a potential constant expression. */
8819 if (type_unknown_p (t))
8820 return true;
8821 if (is_overloaded_fn (t))
8822 /* In a template, a COMPONENT_REF of a function expresses ob.fn(),
8823 which uses ob as an lvalue. */
8824 want_rval = false;
8825 gcc_fallthrough ();
8827 case REALPART_EXPR:
8828 case IMAGPART_EXPR:
8829 case BIT_FIELD_REF:
8830 return RECUR (TREE_OPERAND (t, 0), want_rval);
8832 case EXPR_PACK_EXPANSION:
8833 return RECUR (PACK_EXPANSION_PATTERN (t), want_rval);
8835 case INDIRECT_REF:
8837 tree x = TREE_OPERAND (t, 0);
8838 STRIP_NOPS (x);
8839 if (is_this_parameter (x) && !is_capture_proxy (x))
8841 if (!var_in_maybe_constexpr_fn (x))
8843 if (flags & tf_error)
8844 error_at (loc, "use of %<this%> in a constant expression");
8845 return false;
8847 return true;
8849 return RECUR (x, rval);
8852 case STATEMENT_LIST:
8853 for (tree stmt : tsi_range (t))
8854 if (!RECUR (stmt, any))
8855 return false;
8856 return true;
8858 case MODIFY_EXPR:
8859 if (cxx_dialect < cxx14)
8860 goto fail;
8861 if (!RECUR (TREE_OPERAND (t, 0), any))
8862 return false;
8863 /* Just ignore clobbers. */
8864 if (TREE_CLOBBER_P (TREE_OPERAND (t, 1)))
8865 return true;
8866 if (!RECUR (TREE_OPERAND (t, 1), rval))
8867 return false;
8868 return true;
8870 case MODOP_EXPR:
8871 if (cxx_dialect < cxx14)
8872 goto fail;
8873 if (!RECUR (TREE_OPERAND (t, 0), rval))
8874 return false;
8875 if (!RECUR (TREE_OPERAND (t, 2), rval))
8876 return false;
8877 return true;
8879 case DO_STMT:
8880 if (!RECUR (DO_COND (t), rval))
8881 return false;
8882 if (!RECUR (DO_BODY (t), any))
8883 return false;
8884 if (breaks (jump_target) || continues (jump_target))
8885 *jump_target = NULL_TREE;
8886 return true;
8888 case FOR_STMT:
8889 if (!RECUR (FOR_INIT_STMT (t), any))
8890 return false;
8891 tmp = FOR_COND (t);
8892 if (!RECUR (tmp, rval))
8893 return false;
8894 if (tmp)
8896 if (!processing_template_decl)
8897 tmp = cxx_eval_outermost_constant_expr (tmp, true);
8898 /* If we couldn't evaluate the condition, it might not ever be
8899 true. */
8900 if (!integer_onep (tmp))
8902 /* Before returning true, check if the for body can contain
8903 a return. */
8904 hash_set<tree> pset;
8905 check_for_return_continue_data data = { &pset, NULL_TREE,
8906 NULL_TREE };
8907 if (tree ret_expr
8908 = cp_walk_tree (&FOR_BODY (t), check_for_return_continue,
8909 &data, &pset))
8910 *jump_target = ret_expr;
8911 return true;
8914 if (!RECUR (FOR_EXPR (t), any))
8915 return false;
8916 if (!RECUR (FOR_BODY (t), any))
8917 return false;
8918 if (breaks (jump_target) || continues (jump_target))
8919 *jump_target = NULL_TREE;
8920 return true;
8922 case RANGE_FOR_STMT:
8923 if (!RECUR (RANGE_FOR_INIT_STMT (t), any))
8924 return false;
8925 if (!RECUR (RANGE_FOR_EXPR (t), any))
8926 return false;
8927 if (!RECUR (RANGE_FOR_BODY (t), any))
8928 return false;
8929 if (breaks (jump_target) || continues (jump_target))
8930 *jump_target = NULL_TREE;
8931 return true;
8933 case WHILE_STMT:
8934 tmp = WHILE_COND (t);
8935 if (!RECUR (tmp, rval))
8936 return false;
8937 if (!processing_template_decl)
8938 tmp = cxx_eval_outermost_constant_expr (tmp, true);
8939 /* If we couldn't evaluate the condition, it might not ever be true. */
8940 if (!integer_onep (tmp))
8942 /* Before returning true, check if the while body can contain
8943 a return. */
8944 hash_set<tree> pset;
8945 check_for_return_continue_data data = { &pset, NULL_TREE,
8946 NULL_TREE };
8947 if (tree ret_expr
8948 = cp_walk_tree (&WHILE_BODY (t), check_for_return_continue,
8949 &data, &pset))
8950 *jump_target = ret_expr;
8951 return true;
8953 if (!RECUR (WHILE_BODY (t), any))
8954 return false;
8955 if (breaks (jump_target) || continues (jump_target))
8956 *jump_target = NULL_TREE;
8957 return true;
8959 case SWITCH_STMT:
8960 if (!RECUR (SWITCH_STMT_COND (t), rval))
8961 return false;
8962 /* FIXME we don't check SWITCH_STMT_BODY currently, because even
8963 unreachable labels would be checked and it is enough if there is
8964 a single switch cond value for which it is a valid constant
8965 expression. We need to check if there are any RETURN_EXPRs
8966 or CONTINUE_STMTs inside of the body though, as in that case
8967 we need to set *jump_target. */
8968 else
8970 hash_set<tree> pset;
8971 check_for_return_continue_data data = { &pset, NULL_TREE,
8972 NULL_TREE };
8973 if (tree ret_expr
8974 = cp_walk_tree (&SWITCH_STMT_BODY (t), check_for_return_continue,
8975 &data, &pset))
8976 /* The switch might return. */
8977 *jump_target = ret_expr;
8978 else if (data.continue_stmt)
8979 /* The switch can't return, but might continue. */
8980 *jump_target = data.continue_stmt;
8982 return true;
8984 case STMT_EXPR:
8985 return RECUR (STMT_EXPR_STMT (t), rval);
8987 case LAMBDA_EXPR:
8988 if (cxx_dialect >= cxx17)
8989 /* In C++17 lambdas can be constexpr, don't give up yet. */
8990 return true;
8991 else if (flags & tf_error)
8992 error_at (loc, "lambda-expression is not a constant expression "
8993 "before C++17");
8994 return false;
8996 case DYNAMIC_CAST_EXPR:
8997 case PSEUDO_DTOR_EXPR:
8998 case NEW_EXPR:
8999 case VEC_NEW_EXPR:
9000 case DELETE_EXPR:
9001 case VEC_DELETE_EXPR:
9002 case THROW_EXPR:
9003 case OMP_PARALLEL:
9004 case OMP_TASK:
9005 case OMP_FOR:
9006 case OMP_SIMD:
9007 case OMP_DISTRIBUTE:
9008 case OMP_TASKLOOP:
9009 case OMP_LOOP:
9010 case OMP_TEAMS:
9011 case OMP_TARGET_DATA:
9012 case OMP_TARGET:
9013 case OMP_SECTIONS:
9014 case OMP_ORDERED:
9015 case OMP_CRITICAL:
9016 case OMP_SINGLE:
9017 case OMP_SECTION:
9018 case OMP_MASTER:
9019 case OMP_MASKED:
9020 case OMP_TASKGROUP:
9021 case OMP_TARGET_UPDATE:
9022 case OMP_TARGET_ENTER_DATA:
9023 case OMP_TARGET_EXIT_DATA:
9024 case OMP_ATOMIC:
9025 case OMP_ATOMIC_READ:
9026 case OMP_ATOMIC_CAPTURE_OLD:
9027 case OMP_ATOMIC_CAPTURE_NEW:
9028 case OMP_DEPOBJ:
9029 case OACC_PARALLEL:
9030 case OACC_KERNELS:
9031 case OACC_SERIAL:
9032 case OACC_DATA:
9033 case OACC_HOST_DATA:
9034 case OACC_LOOP:
9035 case OACC_CACHE:
9036 case OACC_DECLARE:
9037 case OACC_ENTER_DATA:
9038 case OACC_EXIT_DATA:
9039 case OACC_UPDATE:
9040 /* GCC internal stuff. */
9041 case VA_ARG_EXPR:
9042 case TRANSACTION_EXPR:
9043 case AT_ENCODE_EXPR:
9044 fail:
9045 if (flags & tf_error)
9046 error_at (loc, "expression %qE is not a constant expression", t);
9047 return false;
9049 case ASM_EXPR:
9050 if (flags & tf_error)
9051 inline_asm_in_constexpr_error (loc);
9052 return false;
9054 case OBJ_TYPE_REF:
9055 if (cxx_dialect >= cxx20)
9056 /* In C++20 virtual calls can be constexpr, don't give up yet. */
9057 return true;
9058 else if (flags & tf_error)
9059 error_at (loc,
9060 "virtual functions cannot be %<constexpr%> before C++20");
9061 return false;
9063 case TYPEID_EXPR:
9064 /* In C++20, a typeid expression whose operand is of polymorphic
9065 class type can be constexpr. */
9067 tree e = TREE_OPERAND (t, 0);
9068 if (cxx_dialect < cxx20
9069 && strict
9070 && !TYPE_P (e)
9071 && !type_dependent_expression_p (e)
9072 && TYPE_POLYMORPHIC_P (TREE_TYPE (e)))
9074 if (flags & tf_error)
9075 error_at (loc, "%<typeid%> is not a constant expression "
9076 "because %qE is of polymorphic type", e);
9077 return false;
9079 return true;
9082 case POINTER_DIFF_EXPR:
9083 case MINUS_EXPR:
9084 want_rval = true;
9085 goto binary;
9087 case LT_EXPR:
9088 case LE_EXPR:
9089 case GT_EXPR:
9090 case GE_EXPR:
9091 case EQ_EXPR:
9092 case NE_EXPR:
9093 case SPACESHIP_EXPR:
9094 want_rval = true;
9095 goto binary;
9097 case PREINCREMENT_EXPR:
9098 case POSTINCREMENT_EXPR:
9099 case PREDECREMENT_EXPR:
9100 case POSTDECREMENT_EXPR:
9101 if (cxx_dialect < cxx14)
9102 goto fail;
9103 goto unary;
9105 case BIT_NOT_EXPR:
9106 /* A destructor. */
9107 if (TYPE_P (TREE_OPERAND (t, 0)))
9108 return true;
9109 /* fall through. */
9111 case CONJ_EXPR:
9112 case SAVE_EXPR:
9113 case FIX_TRUNC_EXPR:
9114 case FLOAT_EXPR:
9115 case NEGATE_EXPR:
9116 case ABS_EXPR:
9117 case ABSU_EXPR:
9118 case TRUTH_NOT_EXPR:
9119 case FIXED_CONVERT_EXPR:
9120 case UNARY_PLUS_EXPR:
9121 case UNARY_LEFT_FOLD_EXPR:
9122 case UNARY_RIGHT_FOLD_EXPR:
9123 unary:
9124 return RECUR (TREE_OPERAND (t, 0), rval);
9126 case CAST_EXPR:
9127 case CONST_CAST_EXPR:
9128 case STATIC_CAST_EXPR:
9129 case REINTERPRET_CAST_EXPR:
9130 case IMPLICIT_CONV_EXPR:
9131 if (cxx_dialect < cxx11
9132 && !dependent_type_p (TREE_TYPE (t))
9133 && !INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t)))
9134 /* In C++98, a conversion to non-integral type can't be part of a
9135 constant expression. */
9137 if (flags & tf_error)
9138 error_at (loc,
9139 "cast to non-integral type %qT in a constant expression",
9140 TREE_TYPE (t));
9141 return false;
9143 /* This might be a conversion from a class to a (potentially) literal
9144 type. Let's consider it potentially constant since the conversion
9145 might be a constexpr user-defined conversion. */
9146 else if (cxx_dialect >= cxx11
9147 && (dependent_type_p (TREE_TYPE (t))
9148 || !COMPLETE_TYPE_P (TREE_TYPE (t))
9149 || literal_type_p (TREE_TYPE (t)))
9150 && TREE_OPERAND (t, 0))
9152 tree type = TREE_TYPE (TREE_OPERAND (t, 0));
9153 /* If this is a dependent type, it could end up being a class
9154 with conversions. */
9155 if (type == NULL_TREE || WILDCARD_TYPE_P (type))
9156 return true;
9157 /* Or a non-dependent class which has conversions. */
9158 else if (CLASS_TYPE_P (type)
9159 && (TYPE_HAS_CONVERSION (type) || dependent_scope_p (type)))
9160 return true;
9163 return (RECUR (TREE_OPERAND (t, 0),
9164 !TYPE_REF_P (TREE_TYPE (t))));
9166 case BIND_EXPR:
9167 return RECUR (BIND_EXPR_BODY (t), want_rval);
9169 case NON_DEPENDENT_EXPR:
9170 /* Treat NON_DEPENDENT_EXPR as non-constant: it's not handled by
9171 constexpr evaluation or tsubst, so fold_non_dependent_expr can't
9172 do anything useful with it. And we shouldn't see it in a context
9173 where a constant expression is strictly required, hence the assert. */
9174 gcc_checking_assert (!(flags & tf_error));
9175 return false;
9177 case CLEANUP_POINT_EXPR:
9178 case MUST_NOT_THROW_EXPR:
9179 case TRY_CATCH_EXPR:
9180 case TRY_BLOCK:
9181 case EH_SPEC_BLOCK:
9182 case EXPR_STMT:
9183 case PAREN_EXPR:
9184 /* For convenience. */
9185 case LOOP_EXPR:
9186 case EXIT_EXPR:
9187 return RECUR (TREE_OPERAND (t, 0), want_rval);
9189 case DECL_EXPR:
9190 tmp = DECL_EXPR_DECL (t);
9191 if (VAR_P (tmp) && !DECL_ARTIFICIAL (tmp))
9193 if (CP_DECL_THREAD_LOCAL_P (tmp) && !DECL_REALLY_EXTERN (tmp))
9195 if (flags & tf_error)
9196 error_at (DECL_SOURCE_LOCATION (tmp), "%qD defined "
9197 "%<thread_local%> in %<constexpr%> context", tmp);
9198 return false;
9200 else if (TREE_STATIC (tmp))
9202 if (flags & tf_error)
9203 error_at (DECL_SOURCE_LOCATION (tmp), "%qD defined "
9204 "%<static%> in %<constexpr%> context", tmp);
9205 return false;
9207 else if (!check_for_uninitialized_const_var
9208 (tmp, /*constexpr_context_p=*/true, flags))
9209 return false;
9211 return RECUR (tmp, want_rval);
9213 case TRY_FINALLY_EXPR:
9214 return (RECUR (TREE_OPERAND (t, 0), want_rval)
9215 && RECUR (TREE_OPERAND (t, 1), any));
9217 case SCOPE_REF:
9218 return RECUR (TREE_OPERAND (t, 1), want_rval);
9220 case TARGET_EXPR:
9221 if (!TARGET_EXPR_DIRECT_INIT_P (t)
9222 && !literal_type_p (TREE_TYPE (t)))
9224 if (flags & tf_error)
9226 auto_diagnostic_group d;
9227 error_at (loc, "temporary of non-literal type %qT in a "
9228 "constant expression", TREE_TYPE (t));
9229 explain_non_literal_class (TREE_TYPE (t));
9231 return false;
9233 /* FALLTHRU */
9234 case INIT_EXPR:
9235 return RECUR (TREE_OPERAND (t, 1), rval);
9237 case CONSTRUCTOR:
9239 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
9240 constructor_elt *ce;
9241 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
9242 if (!RECUR (ce->value, want_rval))
9243 return false;
9244 return true;
9247 case TREE_LIST:
9249 gcc_assert (TREE_PURPOSE (t) == NULL_TREE
9250 || DECL_P (TREE_PURPOSE (t)));
9251 if (!RECUR (TREE_VALUE (t), want_rval))
9252 return false;
9253 if (TREE_CHAIN (t) == NULL_TREE)
9254 return true;
9255 return RECUR (TREE_CHAIN (t), want_rval);
9258 case TRUNC_DIV_EXPR:
9259 case CEIL_DIV_EXPR:
9260 case FLOOR_DIV_EXPR:
9261 case ROUND_DIV_EXPR:
9262 case TRUNC_MOD_EXPR:
9263 case CEIL_MOD_EXPR:
9264 case ROUND_MOD_EXPR:
9266 tree denom = TREE_OPERAND (t, 1);
9267 if (!RECUR (denom, rval))
9268 return false;
9269 /* We can't call cxx_eval_outermost_constant_expr on an expression
9270 that hasn't been through instantiate_non_dependent_expr yet. */
9271 if (!processing_template_decl)
9272 denom = cxx_eval_outermost_constant_expr (denom, true);
9273 if (integer_zerop (denom))
9275 if (flags & tf_error)
9276 error ("division by zero is not a constant expression");
9277 return false;
9279 else
9281 want_rval = true;
9282 return RECUR (TREE_OPERAND (t, 0), want_rval);
9286 case COMPOUND_EXPR:
9288 /* check_return_expr sometimes wraps a TARGET_EXPR in a
9289 COMPOUND_EXPR; don't get confused. */
9290 tree op0 = TREE_OPERAND (t, 0);
9291 tree op1 = TREE_OPERAND (t, 1);
9292 STRIP_NOPS (op1);
9293 if (TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
9294 return RECUR (op0, want_rval);
9295 else
9296 goto binary;
9299 /* If the first operand is the non-short-circuit constant, look at
9300 the second operand; otherwise we only care about the first one for
9301 potentiality. */
9302 case TRUTH_AND_EXPR:
9303 case TRUTH_ANDIF_EXPR:
9304 tmp = boolean_true_node;
9305 goto truth;
9306 case TRUTH_OR_EXPR:
9307 case TRUTH_ORIF_EXPR:
9308 tmp = boolean_false_node;
9309 truth:
9311 tree op0 = TREE_OPERAND (t, 0);
9312 tree op1 = TREE_OPERAND (t, 1);
9313 if (!RECUR (op0, rval))
9314 return false;
9315 if (!(flags & tf_error) && RECUR (op1, rval))
9316 /* When quiet, try to avoid expensive trial evaluation by first
9317 checking potentiality of the second operand. */
9318 return true;
9319 if (!processing_template_decl)
9320 op0 = cxx_eval_outermost_constant_expr (op0, true);
9321 if (tree_int_cst_equal (op0, tmp))
9322 return (flags & tf_error) ? RECUR (op1, rval) : false;
9323 else
9324 return true;
9327 case PLUS_EXPR:
9328 case MULT_EXPR:
9329 case POINTER_PLUS_EXPR:
9330 case RDIV_EXPR:
9331 case EXACT_DIV_EXPR:
9332 case MIN_EXPR:
9333 case MAX_EXPR:
9334 case LSHIFT_EXPR:
9335 case RSHIFT_EXPR:
9336 case LROTATE_EXPR:
9337 case RROTATE_EXPR:
9338 case BIT_IOR_EXPR:
9339 case BIT_XOR_EXPR:
9340 case BIT_AND_EXPR:
9341 case TRUTH_XOR_EXPR:
9342 case UNORDERED_EXPR:
9343 case ORDERED_EXPR:
9344 case UNLT_EXPR:
9345 case UNLE_EXPR:
9346 case UNGT_EXPR:
9347 case UNGE_EXPR:
9348 case UNEQ_EXPR:
9349 case LTGT_EXPR:
9350 case RANGE_EXPR:
9351 case COMPLEX_EXPR:
9352 want_rval = true;
9353 /* Fall through. */
9354 case ARRAY_REF:
9355 case ARRAY_RANGE_REF:
9356 case MEMBER_REF:
9357 case DOTSTAR_EXPR:
9358 case MEM_REF:
9359 case BINARY_LEFT_FOLD_EXPR:
9360 case BINARY_RIGHT_FOLD_EXPR:
9361 binary:
9362 for (i = 0; i < 2; ++i)
9363 if (!RECUR (TREE_OPERAND (t, i), want_rval))
9364 return false;
9365 return true;
9367 case VEC_PERM_EXPR:
9368 for (i = 0; i < 3; ++i)
9369 if (!RECUR (TREE_OPERAND (t, i), true))
9370 return false;
9371 return true;
9373 case COND_EXPR:
9374 if (COND_EXPR_IS_VEC_DELETE (t) && cxx_dialect < cxx20)
9376 if (flags & tf_error)
9377 error_at (loc, "%<delete[]%> is not a constant expression");
9378 return false;
9380 /* Fall through. */
9381 case IF_STMT:
9382 case VEC_COND_EXPR:
9383 /* If the condition is a known constant, we know which of the legs we
9384 care about; otherwise we only require that the condition and
9385 either of the legs be potentially constant. */
9386 tmp = TREE_OPERAND (t, 0);
9387 if (!RECUR (tmp, rval))
9388 return false;
9389 if (!processing_template_decl)
9390 tmp = cxx_eval_outermost_constant_expr (tmp, true);
9391 /* potential_constant_expression* isn't told if it is called for
9392 manifestly_const_eval or not, so for consteval if always
9393 process both branches as if the condition is not a known
9394 constant. */
9395 if (TREE_CODE (t) != IF_STMT || !IF_STMT_CONSTEVAL_P (t))
9397 if (integer_zerop (tmp))
9398 return RECUR (TREE_OPERAND (t, 2), want_rval);
9399 else if (TREE_CODE (tmp) == INTEGER_CST)
9400 return RECUR (TREE_OPERAND (t, 1), want_rval);
9402 tmp = *jump_target;
9403 for (i = 1; i < 3; ++i)
9405 tree this_jump_target = tmp;
9406 if (potential_constant_expression_1 (TREE_OPERAND (t, i),
9407 want_rval, strict, now,
9408 tf_none, &this_jump_target))
9410 if (returns (&this_jump_target))
9411 *jump_target = this_jump_target;
9412 else if (!returns (jump_target))
9414 if (breaks (&this_jump_target)
9415 || continues (&this_jump_target))
9416 *jump_target = this_jump_target;
9417 if (i == 1)
9419 /* If the then branch is potentially constant, but
9420 does not return, check if the else branch
9421 couldn't return, break or continue. */
9422 hash_set<tree> pset;
9423 check_for_return_continue_data data = { &pset, NULL_TREE,
9424 NULL_TREE };
9425 if (tree ret_expr
9426 = cp_walk_tree (&TREE_OPERAND (t, 2),
9427 check_for_return_continue, &data,
9428 &pset))
9429 *jump_target = ret_expr;
9430 else if (*jump_target == NULL_TREE)
9432 if (data.continue_stmt)
9433 *jump_target = data.continue_stmt;
9434 else if (data.break_stmt)
9435 *jump_target = data.break_stmt;
9439 return true;
9442 if (flags & tf_error)
9444 if (TREE_CODE (t) == IF_STMT)
9445 error_at (loc, "neither branch of %<if%> is a constant expression");
9446 else
9447 error_at (loc, "expression %qE is not a constant expression", t);
9449 return false;
9451 case VEC_INIT_EXPR:
9452 if (VEC_INIT_EXPR_IS_CONSTEXPR (t))
9453 return true;
9454 if (flags & tf_error)
9456 error_at (loc, "non-constant array initialization");
9457 diagnose_non_constexpr_vec_init (t);
9459 return false;
9461 case TYPE_DECL:
9462 case TAG_DEFN:
9463 /* We can see these in statement-expressions. */
9464 return true;
9466 case CLEANUP_STMT:
9467 if (!RECUR (CLEANUP_BODY (t), any))
9468 return false;
9469 if (!CLEANUP_EH_ONLY (t) && !RECUR (CLEANUP_EXPR (t), any))
9470 return false;
9471 return true;
9473 case EMPTY_CLASS_EXPR:
9474 return true;
9476 case GOTO_EXPR:
9478 tree *target = &TREE_OPERAND (t, 0);
9479 /* Gotos representing break, continue and cdtor return are OK. */
9480 if (breaks (target) || continues (target) || returns (target))
9482 *jump_target = *target;
9483 return true;
9485 if (flags & tf_error)
9486 error_at (loc, "%<goto%> is not a constant expression");
9487 return false;
9490 case LABEL_EXPR:
9491 t = LABEL_EXPR_LABEL (t);
9492 if (DECL_ARTIFICIAL (t) || cxx_dialect >= cxx23)
9493 return true;
9494 else if (flags & tf_error)
9495 error_at (loc, "label definition in %<constexpr%> function only "
9496 "available with %<-std=c++2b%> or %<-std=gnu++2b%>");
9497 return false;
9499 case ANNOTATE_EXPR:
9500 return RECUR (TREE_OPERAND (t, 0), rval);
9502 case BIT_CAST_EXPR:
9503 return RECUR (TREE_OPERAND (t, 0), rval);
9505 /* Coroutine await, yield and return expressions are not. */
9506 case CO_AWAIT_EXPR:
9507 case CO_YIELD_EXPR:
9508 case CO_RETURN_EXPR:
9509 return false;
9511 case NONTYPE_ARGUMENT_PACK:
9513 tree args = ARGUMENT_PACK_ARGS (t);
9514 int len = TREE_VEC_LENGTH (args);
9515 for (int i = 0; i < len; ++i)
9516 if (!RECUR (TREE_VEC_ELT (args, i), any))
9517 return false;
9518 return true;
9521 default:
9522 if (objc_non_constant_expr_p (t))
9523 return false;
9525 sorry ("unexpected AST of kind %s", get_tree_code_name (TREE_CODE (t)));
9526 gcc_unreachable ();
9527 return false;
9529 #undef RECUR
9532 bool
9533 potential_constant_expression_1 (tree t, bool want_rval, bool strict, bool now,
9534 tsubst_flags_t flags)
9536 if (flags & tf_error)
9538 /* Check potentiality quietly first, as that could be performed more
9539 efficiently in some cases (currently only for TRUTH_*_EXPR). If
9540 that fails, replay the check noisily to give errors. */
9541 flags &= ~tf_error;
9542 if (potential_constant_expression_1 (t, want_rval, strict, now, flags))
9543 return true;
9544 flags |= tf_error;
9547 tree target = NULL_TREE;
9548 return potential_constant_expression_1 (t, want_rval, strict, now,
9549 flags, &target);
9552 /* The main entry point to the above. */
9554 bool
9555 potential_constant_expression (tree t)
9557 return potential_constant_expression_1 (t, false, true, false, tf_none);
9560 /* As above, but require a constant rvalue. */
9562 bool
9563 potential_rvalue_constant_expression (tree t)
9565 return potential_constant_expression_1 (t, true, true, false, tf_none);
9568 /* Like above, but complain about non-constant expressions. */
9570 bool
9571 require_potential_constant_expression (tree t)
9573 return potential_constant_expression_1 (t, false, true, false,
9574 tf_warning_or_error);
9577 /* Cross product of the above. */
9579 bool
9580 require_potential_rvalue_constant_expression (tree t)
9582 return potential_constant_expression_1 (t, true, true, false,
9583 tf_warning_or_error);
9586 /* Like above, but don't consider PARM_DECL a potential_constant_expression. */
9588 bool
9589 require_rvalue_constant_expression (tree t)
9591 return potential_constant_expression_1 (t, true, true, true,
9592 tf_warning_or_error);
9595 /* Like potential_constant_expression, but don't consider possible constexpr
9596 substitution of the current function. That is, PARM_DECL qualifies under
9597 potential_constant_expression, but not here.
9599 This is basically what you can check when any actual constant values might
9600 be value-dependent. */
9602 bool
9603 is_constant_expression (tree t)
9605 return potential_constant_expression_1 (t, false, true, true, tf_none);
9608 /* As above, but expect an rvalue. */
9610 bool
9611 is_rvalue_constant_expression (tree t)
9613 return potential_constant_expression_1 (t, true, true, true, tf_none);
9616 /* Like above, but complain about non-constant expressions. */
9618 bool
9619 require_constant_expression (tree t)
9621 return potential_constant_expression_1 (t, false, true, true,
9622 tf_warning_or_error);
9625 /* Like is_constant_expression, but allow const variables that are not allowed
9626 under constexpr rules. */
9628 bool
9629 is_static_init_expression (tree t)
9631 return potential_constant_expression_1 (t, false, false, true, tf_none);
9634 /* Returns true if T is a potential constant expression that is not
9635 instantiation-dependent, and therefore a candidate for constant folding even
9636 in a template. */
9638 bool
9639 is_nondependent_constant_expression (tree t)
9641 return (!type_unknown_p (t)
9642 && is_constant_expression (t)
9643 && !instantiation_dependent_expression_p (t));
9646 /* Returns true if T is a potential static initializer expression that is not
9647 instantiation-dependent. */
9649 bool
9650 is_nondependent_static_init_expression (tree t)
9652 return (!type_unknown_p (t)
9653 && is_static_init_expression (t)
9654 && !instantiation_dependent_expression_p (t));
9657 /* True iff FN is an implicitly constexpr function. */
9659 bool
9660 decl_implicit_constexpr_p (tree fn)
9662 if (!(flag_implicit_constexpr
9663 && TREE_CODE (fn) == FUNCTION_DECL
9664 && DECL_DECLARED_CONSTEXPR_P (fn)))
9665 return false;
9667 if (DECL_CLONED_FUNCTION_P (fn))
9668 fn = DECL_CLONED_FUNCTION (fn);
9670 return (DECL_LANG_SPECIFIC (fn)
9671 && DECL_LANG_SPECIFIC (fn)->u.fn.implicit_constexpr);
9674 /* Finalize constexpr processing after parsing. */
9676 void
9677 fini_constexpr (void)
9679 /* The contexpr call and fundef copies tables are no longer needed. */
9680 constexpr_call_table = NULL;
9681 fundef_copies_table = NULL;
9684 #include "gt-cp-constexpr.h"