[C++ PATCH] tiny code cleanup
[official-gcc.git] / gcc / cp / constexpr.c
blob23f5fcf3c81b9cc0ab103231070f3b7ff246481f
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-2017 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 "gimple-fold.h"
35 #include "timevar.h"
37 static bool verify_constant (tree, bool, bool *, bool *);
38 #define VERIFY_CONSTANT(X) \
39 do { \
40 if (verify_constant ((X), ctx->quiet, non_constant_p, overflow_p)) \
41 return t; \
42 } while (0)
44 /* Returns true iff FUN is an instantiation of a constexpr function
45 template or a defaulted constexpr function. */
47 bool
48 is_instantiation_of_constexpr (tree fun)
50 return ((DECL_TEMPLOID_INSTANTIATION (fun)
51 && DECL_DECLARED_CONSTEXPR_P (DECL_TI_TEMPLATE (fun)))
52 || (DECL_DEFAULTED_FN (fun)
53 && DECL_DECLARED_CONSTEXPR_P (fun)));
56 /* Return true if T is a literal type. */
58 bool
59 literal_type_p (tree t)
61 if (SCALAR_TYPE_P (t)
62 || VECTOR_TYPE_P (t)
63 || TREE_CODE (t) == REFERENCE_TYPE
64 || (VOID_TYPE_P (t) && cxx_dialect >= cxx14))
65 return true;
66 if (CLASS_TYPE_P (t))
68 t = complete_type (t);
69 gcc_assert (COMPLETE_TYPE_P (t) || errorcount);
70 return CLASSTYPE_LITERAL_P (t);
72 if (TREE_CODE (t) == ARRAY_TYPE)
73 return literal_type_p (strip_array_types (t));
74 return false;
77 /* If DECL is a variable declared `constexpr', require its type
78 be literal. Return the DECL if OK, otherwise NULL. */
80 tree
81 ensure_literal_type_for_constexpr_object (tree decl)
83 tree type = TREE_TYPE (decl);
84 if (VAR_P (decl)
85 && (DECL_DECLARED_CONSTEXPR_P (decl)
86 || var_in_constexpr_fn (decl))
87 && !processing_template_decl)
89 tree stype = strip_array_types (type);
90 if (CLASS_TYPE_P (stype) && !COMPLETE_TYPE_P (complete_type (stype)))
91 /* Don't complain here, we'll complain about incompleteness
92 when we try to initialize the variable. */;
93 else if (!literal_type_p (type))
95 if (DECL_DECLARED_CONSTEXPR_P (decl))
97 error ("the type %qT of %<constexpr%> variable %qD "
98 "is not literal", type, decl);
99 explain_non_literal_class (type);
101 else
103 if (!is_instantiation_of_constexpr (current_function_decl))
105 error ("variable %qD of non-literal type %qT in %<constexpr%> "
106 "function", decl, type);
107 explain_non_literal_class (type);
109 cp_function_chain->invalid_constexpr = true;
111 return NULL;
114 return decl;
117 /* Representation of entries in the constexpr function definition table. */
119 struct GTY((for_user)) constexpr_fundef {
120 tree decl;
121 tree body;
124 struct constexpr_fundef_hasher : ggc_ptr_hash<constexpr_fundef>
126 static hashval_t hash (constexpr_fundef *);
127 static bool equal (constexpr_fundef *, constexpr_fundef *);
130 /* This table holds all constexpr function definitions seen in
131 the current translation unit. */
133 static GTY (()) hash_table<constexpr_fundef_hasher> *constexpr_fundef_table;
135 /* Utility function used for managing the constexpr function table.
136 Return true if the entries pointed to by P and Q are for the
137 same constexpr function. */
139 inline bool
140 constexpr_fundef_hasher::equal (constexpr_fundef *lhs, constexpr_fundef *rhs)
142 return lhs->decl == rhs->decl;
145 /* Utility function used for managing the constexpr function table.
146 Return a hash value for the entry pointed to by Q. */
148 inline hashval_t
149 constexpr_fundef_hasher::hash (constexpr_fundef *fundef)
151 return DECL_UID (fundef->decl);
154 /* Return a previously saved definition of function FUN. */
156 static constexpr_fundef *
157 retrieve_constexpr_fundef (tree fun)
159 constexpr_fundef fundef = { NULL, NULL };
160 if (constexpr_fundef_table == NULL)
161 return NULL;
163 fundef.decl = fun;
164 return constexpr_fundef_table->find (&fundef);
167 /* Check whether the parameter and return types of FUN are valid for a
168 constexpr function, and complain if COMPLAIN. */
170 bool
171 is_valid_constexpr_fn (tree fun, bool complain)
173 bool ret = true;
175 if (DECL_INHERITED_CTOR (fun)
176 && TREE_CODE (fun) == TEMPLATE_DECL)
178 ret = false;
179 if (complain)
180 error ("inherited constructor %qD is not %<constexpr%>",
181 DECL_INHERITED_CTOR (fun));
183 else
185 for (tree parm = FUNCTION_FIRST_USER_PARM (fun);
186 parm != NULL_TREE; parm = TREE_CHAIN (parm))
187 if (!literal_type_p (TREE_TYPE (parm)))
189 ret = false;
190 if (complain)
192 error ("invalid type for parameter %d of %<constexpr%> "
193 "function %q+#D", DECL_PARM_INDEX (parm), fun);
194 explain_non_literal_class (TREE_TYPE (parm));
199 if (LAMBDA_TYPE_P (CP_DECL_CONTEXT (fun)) && cxx_dialect < cxx17)
201 ret = false;
202 if (complain)
203 inform (DECL_SOURCE_LOCATION (fun),
204 "lambdas are implicitly %<constexpr%> only in C++17 and later");
206 else if (!DECL_CONSTRUCTOR_P (fun))
208 tree rettype = TREE_TYPE (TREE_TYPE (fun));
209 if (!literal_type_p (rettype))
211 ret = false;
212 if (complain)
214 error ("invalid return type %qT of %<constexpr%> function %q+D",
215 rettype, fun);
216 explain_non_literal_class (rettype);
220 /* C++14 DR 1684 removed this restriction. */
221 if (cxx_dialect < cxx14
222 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fun)
223 && !CLASSTYPE_LITERAL_P (DECL_CONTEXT (fun)))
225 ret = false;
226 if (complain
227 && pedwarn (DECL_SOURCE_LOCATION (fun), OPT_Wpedantic,
228 "enclosing class of %<constexpr%> non-static member "
229 "function %q+#D is not a literal type", fun))
230 explain_non_literal_class (DECL_CONTEXT (fun));
233 else if (CLASSTYPE_VBASECLASSES (DECL_CONTEXT (fun)))
235 ret = false;
236 if (complain)
237 error ("%q#T has virtual base classes", DECL_CONTEXT (fun));
240 return ret;
243 /* Subroutine of build_data_member_initialization. MEMBER is a COMPONENT_REF
244 for a member of an anonymous aggregate, INIT is the initializer for that
245 member, and VEC_OUTER is the vector of constructor elements for the class
246 whose constructor we are processing. Add the initializer to the vector
247 and return true to indicate success. */
249 static bool
250 build_anon_member_initialization (tree member, tree init,
251 vec<constructor_elt, va_gc> **vec_outer)
253 /* MEMBER presents the relevant fields from the inside out, but we need
254 to build up the initializer from the outside in so that we can reuse
255 previously built CONSTRUCTORs if this is, say, the second field in an
256 anonymous struct. So we use a vec as a stack. */
257 auto_vec<tree, 2> fields;
260 fields.safe_push (TREE_OPERAND (member, 1));
261 member = TREE_OPERAND (member, 0);
263 while (ANON_AGGR_TYPE_P (TREE_TYPE (member))
264 && TREE_CODE (member) == COMPONENT_REF);
266 /* VEC has the constructor elements vector for the context of FIELD.
267 If FIELD is an anonymous aggregate, we will push inside it. */
268 vec<constructor_elt, va_gc> **vec = vec_outer;
269 tree field;
270 while (field = fields.pop(),
271 ANON_AGGR_TYPE_P (TREE_TYPE (field)))
273 tree ctor;
274 /* If there is already an outer constructor entry for the anonymous
275 aggregate FIELD, use it; otherwise, insert one. */
276 if (vec_safe_is_empty (*vec)
277 || (*vec)->last().index != field)
279 ctor = build_constructor (TREE_TYPE (field), NULL);
280 CONSTRUCTOR_APPEND_ELT (*vec, field, ctor);
282 else
283 ctor = (*vec)->last().value;
284 vec = &CONSTRUCTOR_ELTS (ctor);
287 /* Now we're at the innermost field, the one that isn't an anonymous
288 aggregate. Add its initializer to the CONSTRUCTOR and we're done. */
289 gcc_assert (fields.is_empty());
290 CONSTRUCTOR_APPEND_ELT (*vec, field, init);
292 return true;
295 /* Subroutine of build_constexpr_constructor_member_initializers.
296 The expression tree T represents a data member initialization
297 in a (constexpr) constructor definition. Build a pairing of
298 the data member with its initializer, and prepend that pair
299 to the existing initialization pair INITS. */
301 static bool
302 build_data_member_initialization (tree t, vec<constructor_elt, va_gc> **vec)
304 tree member, init;
305 if (TREE_CODE (t) == CLEANUP_POINT_EXPR)
306 t = TREE_OPERAND (t, 0);
307 if (TREE_CODE (t) == EXPR_STMT)
308 t = TREE_OPERAND (t, 0);
309 if (t == error_mark_node)
310 return false;
311 if (TREE_CODE (t) == STATEMENT_LIST)
313 tree_stmt_iterator i;
314 for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
316 if (! build_data_member_initialization (tsi_stmt (i), vec))
317 return false;
319 return true;
321 if (TREE_CODE (t) == CLEANUP_STMT)
323 /* We can't see a CLEANUP_STMT in a constructor for a literal class,
324 but we can in a constexpr constructor for a non-literal class. Just
325 ignore it; either all the initialization will be constant, in which
326 case the cleanup can't run, or it can't be constexpr.
327 Still recurse into CLEANUP_BODY. */
328 return build_data_member_initialization (CLEANUP_BODY (t), vec);
330 if (TREE_CODE (t) == CONVERT_EXPR)
331 t = TREE_OPERAND (t, 0);
332 if (TREE_CODE (t) == INIT_EXPR
333 /* vptr initialization shows up as a MODIFY_EXPR. In C++14 we only
334 use what this function builds for cx_check_missing_mem_inits, and
335 assignment in the ctor body doesn't count. */
336 || (cxx_dialect < cxx14 && TREE_CODE (t) == MODIFY_EXPR))
338 member = TREE_OPERAND (t, 0);
339 init = break_out_target_exprs (TREE_OPERAND (t, 1));
341 else if (TREE_CODE (t) == CALL_EXPR)
343 tree fn = get_callee_fndecl (t);
344 if (!fn || !DECL_CONSTRUCTOR_P (fn))
345 /* We're only interested in calls to subobject constructors. */
346 return true;
347 member = CALL_EXPR_ARG (t, 0);
348 /* We don't use build_cplus_new here because it complains about
349 abstract bases. Leaving the call unwrapped means that it has the
350 wrong type, but cxx_eval_constant_expression doesn't care. */
351 init = break_out_target_exprs (t);
353 else if (TREE_CODE (t) == BIND_EXPR)
354 return build_data_member_initialization (BIND_EXPR_BODY (t), vec);
355 else
356 /* Don't add anything else to the CONSTRUCTOR. */
357 return true;
358 if (INDIRECT_REF_P (member))
359 member = TREE_OPERAND (member, 0);
360 if (TREE_CODE (member) == NOP_EXPR)
362 tree op = member;
363 STRIP_NOPS (op);
364 if (TREE_CODE (op) == ADDR_EXPR)
366 gcc_assert (same_type_ignoring_top_level_qualifiers_p
367 (TREE_TYPE (TREE_TYPE (op)),
368 TREE_TYPE (TREE_TYPE (member))));
369 /* Initializing a cv-qualified member; we need to look through
370 the const_cast. */
371 member = op;
373 else if (op == current_class_ptr
374 && (same_type_ignoring_top_level_qualifiers_p
375 (TREE_TYPE (TREE_TYPE (member)),
376 current_class_type)))
377 /* Delegating constructor. */
378 member = op;
379 else
381 /* This is an initializer for an empty base; keep it for now so
382 we can check it in cxx_eval_bare_aggregate. */
383 gcc_assert (is_empty_class (TREE_TYPE (TREE_TYPE (member))));
386 if (TREE_CODE (member) == ADDR_EXPR)
387 member = TREE_OPERAND (member, 0);
388 if (TREE_CODE (member) == COMPONENT_REF)
390 tree aggr = TREE_OPERAND (member, 0);
391 if (TREE_CODE (aggr) == VAR_DECL)
392 /* Initializing a local variable, don't add anything. */
393 return true;
394 if (TREE_CODE (aggr) != COMPONENT_REF)
395 /* Normal member initialization. */
396 member = TREE_OPERAND (member, 1);
397 else if (ANON_AGGR_TYPE_P (TREE_TYPE (aggr)))
398 /* Initializing a member of an anonymous union. */
399 return build_anon_member_initialization (member, init, vec);
400 else
401 /* We're initializing a vtable pointer in a base. Leave it as
402 COMPONENT_REF so we remember the path to get to the vfield. */
403 gcc_assert (TREE_TYPE (member) == vtbl_ptr_type_node);
406 /* Value-initialization can produce multiple initializers for the
407 same field; use the last one. */
408 if (!vec_safe_is_empty (*vec) && (*vec)->last().index == member)
409 (*vec)->last().value = init;
410 else
411 CONSTRUCTOR_APPEND_ELT (*vec, member, init);
412 return true;
415 /* Subroutine of check_constexpr_ctor_body_1 and constexpr_fn_retval.
416 In C++11 mode checks that the TYPE_DECLs in the BIND_EXPR_VARS of a
417 BIND_EXPR conform to 7.1.5/3/4 on typedef and alias declarations. */
419 static bool
420 check_constexpr_bind_expr_vars (tree t)
422 gcc_assert (TREE_CODE (t) == BIND_EXPR);
424 for (tree var = BIND_EXPR_VARS (t); var; var = DECL_CHAIN (var))
425 if (TREE_CODE (var) == TYPE_DECL
426 && DECL_IMPLICIT_TYPEDEF_P (var)
427 && !LAMBDA_TYPE_P (TREE_TYPE (var)))
428 return false;
429 return true;
432 /* Subroutine of check_constexpr_ctor_body. */
434 static bool
435 check_constexpr_ctor_body_1 (tree last, tree list)
437 switch (TREE_CODE (list))
439 case DECL_EXPR:
440 if (TREE_CODE (DECL_EXPR_DECL (list)) == USING_DECL
441 || TREE_CODE (DECL_EXPR_DECL (list)) == TYPE_DECL)
442 return true;
443 return false;
445 case CLEANUP_POINT_EXPR:
446 return check_constexpr_ctor_body (last, TREE_OPERAND (list, 0),
447 /*complain=*/false);
449 case BIND_EXPR:
450 if (!check_constexpr_bind_expr_vars (list)
451 || !check_constexpr_ctor_body (last, BIND_EXPR_BODY (list),
452 /*complain=*/false))
453 return false;
454 return true;
456 case USING_STMT:
457 case STATIC_ASSERT:
458 case DEBUG_BEGIN_STMT:
459 return true;
461 default:
462 return false;
466 /* Make sure that there are no statements after LAST in the constructor
467 body represented by LIST. */
469 bool
470 check_constexpr_ctor_body (tree last, tree list, bool complain)
472 /* C++14 doesn't require a constexpr ctor to have an empty body. */
473 if (cxx_dialect >= cxx14)
474 return true;
476 bool ok = true;
477 if (TREE_CODE (list) == STATEMENT_LIST)
479 tree_stmt_iterator i = tsi_last (list);
480 for (; !tsi_end_p (i); tsi_prev (&i))
482 tree t = tsi_stmt (i);
483 if (t == last)
484 break;
485 if (!check_constexpr_ctor_body_1 (last, t))
487 ok = false;
488 break;
492 else if (list != last
493 && !check_constexpr_ctor_body_1 (last, list))
494 ok = false;
495 if (!ok)
497 if (complain)
498 error ("%<constexpr%> constructor does not have empty body");
499 DECL_DECLARED_CONSTEXPR_P (current_function_decl) = false;
501 return ok;
504 /* V is a vector of constructor elements built up for the base and member
505 initializers of a constructor for TYPE. They need to be in increasing
506 offset order, which they might not be yet if TYPE has a primary base
507 which is not first in the base-clause or a vptr and at least one base
508 all of which are non-primary. */
510 static vec<constructor_elt, va_gc> *
511 sort_constexpr_mem_initializers (tree type, vec<constructor_elt, va_gc> *v)
513 tree pri = CLASSTYPE_PRIMARY_BINFO (type);
514 tree field_type;
515 unsigned i;
516 constructor_elt *ce;
518 if (pri)
519 field_type = BINFO_TYPE (pri);
520 else if (TYPE_CONTAINS_VPTR_P (type))
521 field_type = vtbl_ptr_type_node;
522 else
523 return v;
525 /* Find the element for the primary base or vptr and move it to the
526 beginning of the vec. */
527 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
528 if (TREE_TYPE (ce->index) == field_type)
529 break;
531 if (i > 0 && i < vec_safe_length (v))
533 vec<constructor_elt, va_gc> &vref = *v;
534 constructor_elt elt = vref[i];
535 for (; i > 0; --i)
536 vref[i] = vref[i-1];
537 vref[0] = elt;
540 return v;
543 /* Build compile-time evalable representations of member-initializer list
544 for a constexpr constructor. */
546 static tree
547 build_constexpr_constructor_member_initializers (tree type, tree body)
549 vec<constructor_elt, va_gc> *vec = NULL;
550 bool ok = true;
551 while (true)
552 switch (TREE_CODE (body))
554 case MUST_NOT_THROW_EXPR:
555 case EH_SPEC_BLOCK:
556 body = TREE_OPERAND (body, 0);
557 break;
559 case STATEMENT_LIST:
560 for (tree_stmt_iterator i = tsi_start (body);
561 !tsi_end_p (i); tsi_next (&i))
563 body = tsi_stmt (i);
564 if (TREE_CODE (body) == BIND_EXPR)
565 break;
567 break;
569 case BIND_EXPR:
570 body = BIND_EXPR_BODY (body);
571 goto found;
573 default:
574 gcc_unreachable ();
576 found:
577 if (TREE_CODE (body) == CLEANUP_POINT_EXPR)
579 body = TREE_OPERAND (body, 0);
580 if (TREE_CODE (body) == EXPR_STMT)
581 body = TREE_OPERAND (body, 0);
582 if (TREE_CODE (body) == INIT_EXPR
583 && (same_type_ignoring_top_level_qualifiers_p
584 (TREE_TYPE (TREE_OPERAND (body, 0)),
585 current_class_type)))
587 /* Trivial copy. */
588 return TREE_OPERAND (body, 1);
590 ok = build_data_member_initialization (body, &vec);
592 else if (TREE_CODE (body) == STATEMENT_LIST)
594 tree_stmt_iterator i;
595 for (i = tsi_start (body); !tsi_end_p (i); tsi_next (&i))
597 ok = build_data_member_initialization (tsi_stmt (i), &vec);
598 if (!ok)
599 break;
602 else if (TREE_CODE (body) == TRY_BLOCK)
604 error ("body of %<constexpr%> constructor cannot be "
605 "a function-try-block");
606 return error_mark_node;
608 else if (EXPR_P (body))
609 ok = build_data_member_initialization (body, &vec);
610 else
611 gcc_assert (errorcount > 0);
612 if (ok)
614 if (vec_safe_length (vec) > 0)
616 /* In a delegating constructor, return the target. */
617 constructor_elt *ce = &(*vec)[0];
618 if (ce->index == current_class_ptr)
620 body = ce->value;
621 vec_free (vec);
622 return body;
625 vec = sort_constexpr_mem_initializers (type, vec);
626 return build_constructor (type, vec);
628 else
629 return error_mark_node;
632 /* We have an expression tree T that represents a call, either CALL_EXPR
633 or AGGR_INIT_EXPR. If the call is lexically to a named function,
634 retrun the _DECL for that function. */
636 static tree
637 get_function_named_in_call (tree t)
639 tree fun = cp_get_callee (t);
640 if (fun && TREE_CODE (fun) == ADDR_EXPR
641 && TREE_CODE (TREE_OPERAND (fun, 0)) == FUNCTION_DECL)
642 fun = TREE_OPERAND (fun, 0);
643 return fun;
646 /* Subroutine of register_constexpr_fundef. BODY is the body of a function
647 declared to be constexpr, or a sub-statement thereof. Returns the
648 return value if suitable, error_mark_node for a statement not allowed in
649 a constexpr function, or NULL_TREE if no return value was found. */
651 static tree
652 constexpr_fn_retval (tree body)
654 switch (TREE_CODE (body))
656 case STATEMENT_LIST:
658 tree_stmt_iterator i;
659 tree expr = NULL_TREE;
660 for (i = tsi_start (body); !tsi_end_p (i); tsi_next (&i))
662 tree s = constexpr_fn_retval (tsi_stmt (i));
663 if (s == error_mark_node)
664 return error_mark_node;
665 else if (s == NULL_TREE)
666 /* Keep iterating. */;
667 else if (expr)
668 /* Multiple return statements. */
669 return error_mark_node;
670 else
671 expr = s;
673 return expr;
676 case RETURN_EXPR:
677 return break_out_target_exprs (TREE_OPERAND (body, 0));
679 case DECL_EXPR:
681 tree decl = DECL_EXPR_DECL (body);
682 if (TREE_CODE (decl) == USING_DECL
683 /* Accept __func__, __FUNCTION__, and __PRETTY_FUNCTION__. */
684 || DECL_ARTIFICIAL (decl))
685 return NULL_TREE;
686 return error_mark_node;
689 case CLEANUP_POINT_EXPR:
690 return constexpr_fn_retval (TREE_OPERAND (body, 0));
692 case BIND_EXPR:
693 if (!check_constexpr_bind_expr_vars (body))
694 return error_mark_node;
695 return constexpr_fn_retval (BIND_EXPR_BODY (body));
697 case USING_STMT:
698 case DEBUG_BEGIN_STMT:
699 return NULL_TREE;
701 case CALL_EXPR:
703 tree fun = get_function_named_in_call (body);
704 if (fun != NULL_TREE
705 && DECL_FUNCTION_CODE (fun) == BUILT_IN_UNREACHABLE)
706 return NULL_TREE;
708 /* Fallthru. */
710 default:
711 return error_mark_node;
715 /* Subroutine of register_constexpr_fundef. BODY is the DECL_SAVED_TREE of
716 FUN; do the necessary transformations to turn it into a single expression
717 that we can store in the hash table. */
719 static tree
720 massage_constexpr_body (tree fun, tree body)
722 if (DECL_CONSTRUCTOR_P (fun))
723 body = build_constexpr_constructor_member_initializers
724 (DECL_CONTEXT (fun), body);
725 else if (cxx_dialect < cxx14)
727 if (TREE_CODE (body) == EH_SPEC_BLOCK)
728 body = EH_SPEC_STMTS (body);
729 if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
730 body = TREE_OPERAND (body, 0);
731 body = constexpr_fn_retval (body);
733 return body;
736 /* CTYPE is a type constructed from BODY. Return true if some
737 bases/fields are uninitialized, and complain if COMPLAIN. */
739 static bool
740 cx_check_missing_mem_inits (tree ctype, tree body, bool complain)
742 unsigned nelts = 0;
744 if (body)
746 if (TREE_CODE (body) != CONSTRUCTOR)
747 return false;
748 nelts = CONSTRUCTOR_NELTS (body);
750 tree field = TYPE_FIELDS (ctype);
752 if (TREE_CODE (ctype) == UNION_TYPE)
754 if (nelts == 0 && next_initializable_field (field))
756 if (complain)
757 error ("%<constexpr%> constructor for union %qT must "
758 "initialize exactly one non-static data member", ctype);
759 return true;
761 return false;
764 /* Iterate over the CONSTRUCTOR, checking any missing fields don't
765 need an explicit initialization. */
766 bool bad = false;
767 for (unsigned i = 0; i <= nelts; ++i)
769 tree index = NULL_TREE;
770 if (i < nelts)
772 index = CONSTRUCTOR_ELT (body, i)->index;
773 /* Skip base and vtable inits. */
774 if (TREE_CODE (index) != FIELD_DECL
775 || DECL_ARTIFICIAL (index))
776 continue;
779 for (; field != index; field = DECL_CHAIN (field))
781 tree ftype;
782 if (TREE_CODE (field) != FIELD_DECL)
783 continue;
784 if (DECL_C_BIT_FIELD (field) && !DECL_NAME (field))
785 continue;
786 if (DECL_ARTIFICIAL (field))
787 continue;
788 if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
790 /* Recurse to check the anonummous aggregate member. */
791 bad |= cx_check_missing_mem_inits
792 (TREE_TYPE (field), NULL_TREE, complain);
793 if (bad && !complain)
794 return true;
795 continue;
797 ftype = strip_array_types (TREE_TYPE (field));
798 if (type_has_constexpr_default_constructor (ftype))
800 /* It's OK to skip a member with a trivial constexpr ctor.
801 A constexpr ctor that isn't trivial should have been
802 added in by now. */
803 gcc_checking_assert (!TYPE_HAS_COMPLEX_DFLT (ftype)
804 || errorcount != 0);
805 continue;
807 if (!complain)
808 return true;
809 error ("member %qD must be initialized by mem-initializer "
810 "in %<constexpr%> constructor", field);
811 inform (DECL_SOURCE_LOCATION (field), "declared here");
812 bad = true;
814 if (field == NULL_TREE)
815 break;
817 if (ANON_AGGR_TYPE_P (TREE_TYPE (index)))
819 /* Check the anonymous aggregate initializer is valid. */
820 bad |= cx_check_missing_mem_inits
821 (TREE_TYPE (index), CONSTRUCTOR_ELT (body, i)->value, complain);
822 if (bad && !complain)
823 return true;
825 field = DECL_CHAIN (field);
828 return bad;
831 /* We are processing the definition of the constexpr function FUN.
832 Check that its BODY fulfills the propriate requirements and
833 enter it in the constexpr function definition table.
834 For constructor BODY is actually the TREE_LIST of the
835 member-initializer list. */
837 tree
838 register_constexpr_fundef (tree fun, tree body)
840 constexpr_fundef entry;
841 constexpr_fundef **slot;
843 if (!is_valid_constexpr_fn (fun, !DECL_GENERATED_P (fun)))
844 return NULL;
846 tree massaged = massage_constexpr_body (fun, body);
847 if (massaged == NULL_TREE || massaged == error_mark_node)
849 if (!DECL_CONSTRUCTOR_P (fun))
850 error ("body of %<constexpr%> function %qD not a return-statement",
851 fun);
852 return NULL;
855 if (!potential_rvalue_constant_expression (massaged))
857 if (!DECL_GENERATED_P (fun))
858 require_potential_rvalue_constant_expression (massaged);
859 return NULL;
862 if (DECL_CONSTRUCTOR_P (fun)
863 && cx_check_missing_mem_inits (DECL_CONTEXT (fun),
864 massaged, !DECL_GENERATED_P (fun)))
865 return NULL;
867 /* Create the constexpr function table if necessary. */
868 if (constexpr_fundef_table == NULL)
869 constexpr_fundef_table
870 = hash_table<constexpr_fundef_hasher>::create_ggc (101);
872 entry.decl = fun;
873 entry.body = body;
874 slot = constexpr_fundef_table->find_slot (&entry, INSERT);
876 gcc_assert (*slot == NULL);
877 *slot = ggc_alloc<constexpr_fundef> ();
878 **slot = entry;
880 return fun;
883 /* FUN is a non-constexpr function called in a context that requires a
884 constant expression. If it comes from a constexpr template, explain why
885 the instantiation isn't constexpr. */
887 void
888 explain_invalid_constexpr_fn (tree fun)
890 static hash_set<tree> *diagnosed;
891 tree body;
892 location_t save_loc;
893 /* Only diagnose defaulted functions, lambdas, or instantiations. */
894 if (!DECL_DEFAULTED_FN (fun)
895 && !LAMBDA_TYPE_P (CP_DECL_CONTEXT (fun))
896 && !is_instantiation_of_constexpr (fun))
897 return;
898 if (diagnosed == NULL)
899 diagnosed = new hash_set<tree>;
900 if (diagnosed->add (fun))
901 /* Already explained. */
902 return;
904 save_loc = input_location;
905 if (!lambda_static_thunk_p (fun))
907 /* Diagnostics should completely ignore the static thunk, so leave
908 input_location set to our caller's location. */
909 input_location = DECL_SOURCE_LOCATION (fun);
910 inform (input_location,
911 "%qD is not usable as a %<constexpr%> function because:", fun);
913 /* First check the declaration. */
914 if (is_valid_constexpr_fn (fun, true))
916 /* Then if it's OK, the body. */
917 if (!DECL_DECLARED_CONSTEXPR_P (fun)
918 && !LAMBDA_TYPE_P (CP_DECL_CONTEXT (fun)))
919 explain_implicit_non_constexpr (fun);
920 else
922 body = massage_constexpr_body (fun, DECL_SAVED_TREE (fun));
923 require_potential_rvalue_constant_expression (body);
924 if (DECL_CONSTRUCTOR_P (fun))
925 cx_check_missing_mem_inits (DECL_CONTEXT (fun), body, true);
928 input_location = save_loc;
931 /* Objects of this type represent calls to constexpr functions
932 along with the bindings of parameters to their arguments, for
933 the purpose of compile time evaluation. */
935 struct GTY((for_user)) constexpr_call {
936 /* Description of the constexpr function definition. */
937 constexpr_fundef *fundef;
938 /* Parameter bindings environment. A TREE_LIST where each TREE_PURPOSE
939 is a parameter _DECL and the TREE_VALUE is the value of the parameter.
940 Note: This arrangement is made to accommodate the use of
941 iterative_hash_template_arg (see pt.c). If you change this
942 representation, also change the hash calculation in
943 cxx_eval_call_expression. */
944 tree bindings;
945 /* Result of the call.
946 NULL means the call is being evaluated.
947 error_mark_node means that the evaluation was erroneous;
948 otherwise, the actuall value of the call. */
949 tree result;
950 /* The hash of this call; we remember it here to avoid having to
951 recalculate it when expanding the hash table. */
952 hashval_t hash;
955 struct constexpr_call_hasher : ggc_ptr_hash<constexpr_call>
957 static hashval_t hash (constexpr_call *);
958 static bool equal (constexpr_call *, constexpr_call *);
961 enum constexpr_switch_state {
962 /* Used when processing a switch for the first time by cxx_eval_switch_expr
963 and default: label for that switch has not been seen yet. */
964 css_default_not_seen,
965 /* Used when processing a switch for the first time by cxx_eval_switch_expr
966 and default: label for that switch has been seen already. */
967 css_default_seen,
968 /* Used when processing a switch for the second time by
969 cxx_eval_switch_expr, where default: label should match. */
970 css_default_processing
973 /* The constexpr expansion context. CALL is the current function
974 expansion, CTOR is the current aggregate initializer, OBJECT is the
975 object being initialized by CTOR, either a VAR_DECL or a _REF. VALUES
976 is a map of values of variables initialized within the expression. */
978 struct constexpr_ctx {
979 /* The innermost call we're evaluating. */
980 constexpr_call *call;
981 /* Values for any temporaries or local variables within the
982 constant-expression. */
983 hash_map<tree,tree> *values;
984 /* SAVE_EXPRs that we've seen within the current LOOP_EXPR. NULL if we
985 aren't inside a loop. */
986 hash_set<tree> *save_exprs;
987 /* The CONSTRUCTOR we're currently building up for an aggregate
988 initializer. */
989 tree ctor;
990 /* The object we're building the CONSTRUCTOR for. */
991 tree object;
992 /* If inside SWITCH_EXPR. */
993 constexpr_switch_state *css_state;
994 /* Whether we should error on a non-constant expression or fail quietly. */
995 bool quiet;
996 /* Whether we are strictly conforming to constant expression rules or
997 trying harder to get a constant value. */
998 bool strict;
1001 /* A table of all constexpr calls that have been evaluated by the
1002 compiler in this translation unit. */
1004 static GTY (()) hash_table<constexpr_call_hasher> *constexpr_call_table;
1006 static tree cxx_eval_constant_expression (const constexpr_ctx *, tree,
1007 bool, bool *, bool *, tree * = NULL);
1009 /* Compute a hash value for a constexpr call representation. */
1011 inline hashval_t
1012 constexpr_call_hasher::hash (constexpr_call *info)
1014 return info->hash;
1017 /* Return true if the objects pointed to by P and Q represent calls
1018 to the same constexpr function with the same arguments.
1019 Otherwise, return false. */
1021 bool
1022 constexpr_call_hasher::equal (constexpr_call *lhs, constexpr_call *rhs)
1024 tree lhs_bindings;
1025 tree rhs_bindings;
1026 if (lhs == rhs)
1027 return 1;
1028 if (!constexpr_fundef_hasher::equal (lhs->fundef, rhs->fundef))
1029 return 0;
1030 lhs_bindings = lhs->bindings;
1031 rhs_bindings = rhs->bindings;
1032 while (lhs_bindings != NULL && rhs_bindings != NULL)
1034 tree lhs_arg = TREE_VALUE (lhs_bindings);
1035 tree rhs_arg = TREE_VALUE (rhs_bindings);
1036 gcc_assert (TREE_TYPE (lhs_arg) == TREE_TYPE (rhs_arg));
1037 if (!cp_tree_equal (lhs_arg, rhs_arg))
1038 return 0;
1039 lhs_bindings = TREE_CHAIN (lhs_bindings);
1040 rhs_bindings = TREE_CHAIN (rhs_bindings);
1042 return lhs_bindings == rhs_bindings;
1045 /* Initialize the constexpr call table, if needed. */
1047 static void
1048 maybe_initialize_constexpr_call_table (void)
1050 if (constexpr_call_table == NULL)
1051 constexpr_call_table = hash_table<constexpr_call_hasher>::create_ggc (101);
1054 /* During constexpr CALL_EXPR evaluation, to avoid issues with sharing when
1055 a function happens to get called recursively, we unshare the callee
1056 function's body and evaluate this unshared copy instead of evaluating the
1057 original body.
1059 FUNDEF_COPIES_TABLE is a per-function freelist of these unshared function
1060 copies. The underlying data structure of FUNDEF_COPIES_TABLE is a hash_map
1061 that's keyed off of the original FUNCTION_DECL and whose value is a
1062 TREE_LIST of this function's unused copies awaiting reuse.
1064 This is not GC-deletable to avoid GC affecting UID generation. */
1066 static GTY(()) hash_map<tree, tree> *fundef_copies_table;
1068 /* Initialize FUNDEF_COPIES_TABLE if it's not initialized. */
1070 static void
1071 maybe_initialize_fundef_copies_table ()
1073 if (fundef_copies_table == NULL)
1074 fundef_copies_table = hash_map<tree,tree>::create_ggc (101);
1077 /* Reuse a copy or create a new unshared copy of the function FUN.
1078 Return this copy. We use a TREE_LIST whose PURPOSE is body, VALUE
1079 is parms, TYPE is result. */
1081 static tree
1082 get_fundef_copy (tree fun)
1084 maybe_initialize_fundef_copies_table ();
1086 tree copy;
1087 bool existed;
1088 tree *slot = &fundef_copies_table->get_or_insert (fun, &existed);
1090 if (!existed)
1092 /* There is no cached function available, or in use. We can use
1093 the function directly. That the slot is now created records
1094 that this function is now in use. */
1095 copy = build_tree_list (DECL_SAVED_TREE (fun), DECL_ARGUMENTS (fun));
1096 TREE_TYPE (copy) = DECL_RESULT (fun);
1098 else if (*slot == NULL_TREE)
1100 /* We've already used the function itself, so make a copy. */
1101 copy = build_tree_list (NULL, NULL);
1102 TREE_PURPOSE (copy) = copy_fn (fun, TREE_VALUE (copy), TREE_TYPE (copy));
1104 else
1106 /* We have a cached function available. */
1107 copy = *slot;
1108 *slot = TREE_CHAIN (copy);
1111 return copy;
1114 /* Save the copy COPY of function FUN for later reuse by
1115 get_fundef_copy(). By construction, there will always be an entry
1116 to find. */
1118 static void
1119 save_fundef_copy (tree fun, tree copy)
1121 tree *slot = fundef_copies_table->get (fun);
1122 TREE_CHAIN (copy) = *slot;
1123 *slot = copy;
1126 /* We have an expression tree T that represents a call, either CALL_EXPR
1127 or AGGR_INIT_EXPR. Return the Nth argument. */
1129 static inline tree
1130 get_nth_callarg (tree t, int n)
1132 switch (TREE_CODE (t))
1134 case CALL_EXPR:
1135 return CALL_EXPR_ARG (t, n);
1137 case AGGR_INIT_EXPR:
1138 return AGGR_INIT_EXPR_ARG (t, n);
1140 default:
1141 gcc_unreachable ();
1142 return NULL;
1146 /* Attempt to evaluate T which represents a call to a builtin function.
1147 We assume here that all builtin functions evaluate to scalar types
1148 represented by _CST nodes. */
1150 static tree
1151 cxx_eval_builtin_function_call (const constexpr_ctx *ctx, tree t, tree fun,
1152 bool lval,
1153 bool *non_constant_p, bool *overflow_p)
1155 const int nargs = call_expr_nargs (t);
1156 tree *args = (tree *) alloca (nargs * sizeof (tree));
1157 tree new_call;
1158 int i;
1160 /* Don't fold __builtin_constant_p within a constexpr function. */
1161 bool bi_const_p = (DECL_FUNCTION_CODE (fun) == BUILT_IN_CONSTANT_P);
1163 if (bi_const_p
1164 && current_function_decl
1165 && DECL_DECLARED_CONSTEXPR_P (current_function_decl))
1167 *non_constant_p = true;
1168 return t;
1171 /* Be permissive for arguments to built-ins; __builtin_constant_p should
1172 return constant false for a non-constant argument. */
1173 constexpr_ctx new_ctx = *ctx;
1174 new_ctx.quiet = true;
1175 bool dummy1 = false, dummy2 = false;
1176 for (i = 0; i < nargs; ++i)
1178 args[i] = cxx_eval_constant_expression (&new_ctx, CALL_EXPR_ARG (t, i),
1179 false, &dummy1, &dummy2);
1180 if (bi_const_p)
1181 /* For __built_in_constant_p, fold all expressions with constant values
1182 even if they aren't C++ constant-expressions. */
1183 args[i] = cp_fully_fold (args[i]);
1186 bool save_ffbcp = force_folding_builtin_constant_p;
1187 force_folding_builtin_constant_p = true;
1188 new_call = fold_builtin_call_array (EXPR_LOCATION (t), TREE_TYPE (t),
1189 CALL_EXPR_FN (t), nargs, args);
1190 force_folding_builtin_constant_p = save_ffbcp;
1191 if (new_call == NULL)
1193 if (!*non_constant_p && !ctx->quiet)
1195 /* Do not allow__builtin_unreachable in constexpr function.
1196 The __builtin_unreachable call with BUILTINS_LOCATION
1197 comes from cp_maybe_instrument_return. */
1198 if (DECL_FUNCTION_CODE (fun) == BUILT_IN_UNREACHABLE
1199 && EXPR_LOCATION (t) == BUILTINS_LOCATION)
1200 error ("%<constexpr%> call flows off the end of the function");
1201 else
1203 new_call = build_call_array_loc (EXPR_LOCATION (t), TREE_TYPE (t),
1204 CALL_EXPR_FN (t), nargs, args);
1205 error ("%q+E is not a constant expression", new_call);
1208 *non_constant_p = true;
1209 return t;
1212 if (!is_constant_expression (new_call))
1214 if (!*non_constant_p && !ctx->quiet)
1215 error ("%q+E is not a constant expression", new_call);
1216 *non_constant_p = true;
1217 return t;
1220 return cxx_eval_constant_expression (&new_ctx, new_call, lval,
1221 non_constant_p, overflow_p);
1224 /* TEMP is the constant value of a temporary object of type TYPE. Adjust
1225 the type of the value to match. */
1227 static tree
1228 adjust_temp_type (tree type, tree temp)
1230 if (TREE_TYPE (temp) == type)
1231 return temp;
1232 /* Avoid wrapping an aggregate value in a NOP_EXPR. */
1233 if (TREE_CODE (temp) == CONSTRUCTOR)
1234 return build_constructor (type, CONSTRUCTOR_ELTS (temp));
1235 gcc_assert (scalarish_type_p (type));
1236 return cp_fold_convert (type, temp);
1239 /* Callback for walk_tree used by unshare_constructor. */
1241 static tree
1242 find_constructor (tree *tp, int *walk_subtrees, void *)
1244 if (TYPE_P (*tp))
1245 *walk_subtrees = 0;
1246 if (TREE_CODE (*tp) == CONSTRUCTOR)
1247 return *tp;
1248 return NULL_TREE;
1251 /* If T is a CONSTRUCTOR or an expression that has a CONSTRUCTOR node as a
1252 subexpression, return an unshared copy of T. Otherwise return T. */
1254 static tree
1255 unshare_constructor (tree t)
1257 tree ctor = walk_tree (&t, find_constructor, NULL, NULL);
1258 if (ctor != NULL_TREE)
1259 return unshare_expr (t);
1260 return t;
1263 /* Subroutine of cxx_eval_call_expression.
1264 We are processing a call expression (either CALL_EXPR or
1265 AGGR_INIT_EXPR) in the context of CTX. Evaluate
1266 all arguments and bind their values to correspondings
1267 parameters, making up the NEW_CALL context. */
1269 static void
1270 cxx_bind_parameters_in_call (const constexpr_ctx *ctx, tree t,
1271 constexpr_call *new_call,
1272 bool *non_constant_p, bool *overflow_p,
1273 bool *non_constant_args)
1275 const int nargs = call_expr_nargs (t);
1276 tree fun = new_call->fundef->decl;
1277 tree parms = DECL_ARGUMENTS (fun);
1278 int i;
1279 tree *p = &new_call->bindings;
1280 for (i = 0; i < nargs; ++i)
1282 tree x, arg;
1283 tree type = parms ? TREE_TYPE (parms) : void_type_node;
1284 x = get_nth_callarg (t, i);
1285 /* For member function, the first argument is a pointer to the implied
1286 object. For a constructor, it might still be a dummy object, in
1287 which case we get the real argument from ctx. */
1288 if (i == 0 && DECL_CONSTRUCTOR_P (fun)
1289 && is_dummy_object (x))
1291 x = ctx->object;
1292 x = build_address (x);
1294 arg = cxx_eval_constant_expression (ctx, x, /*lval=*/false,
1295 non_constant_p, overflow_p);
1296 /* Don't VERIFY_CONSTANT here. */
1297 if (*non_constant_p && ctx->quiet)
1298 return;
1299 /* Just discard ellipsis args after checking their constantitude. */
1300 if (!parms)
1301 continue;
1303 if (!*non_constant_p)
1305 /* Make sure the binding has the same type as the parm. But
1306 only for constant args. */
1307 if (TREE_CODE (type) != REFERENCE_TYPE)
1308 arg = adjust_temp_type (type, arg);
1309 if (!TREE_CONSTANT (arg))
1310 *non_constant_args = true;
1311 *p = build_tree_list (parms, arg);
1312 p = &TREE_CHAIN (*p);
1314 parms = TREE_CHAIN (parms);
1318 /* Variables and functions to manage constexpr call expansion context.
1319 These do not need to be marked for PCH or GC. */
1321 /* FIXME remember and print actual constant arguments. */
1322 static vec<tree> call_stack;
1323 static int call_stack_tick;
1324 static int last_cx_error_tick;
1326 static bool
1327 push_cx_call_context (tree call)
1329 ++call_stack_tick;
1330 if (!EXPR_HAS_LOCATION (call))
1331 SET_EXPR_LOCATION (call, input_location);
1332 call_stack.safe_push (call);
1333 if (call_stack.length () > (unsigned) max_constexpr_depth)
1334 return false;
1335 return true;
1338 static void
1339 pop_cx_call_context (void)
1341 ++call_stack_tick;
1342 call_stack.pop ();
1345 vec<tree>
1346 cx_error_context (void)
1348 vec<tree> r = vNULL;
1349 if (call_stack_tick != last_cx_error_tick
1350 && !call_stack.is_empty ())
1351 r = call_stack;
1352 last_cx_error_tick = call_stack_tick;
1353 return r;
1356 /* Evaluate a call T to a GCC internal function when possible and return
1357 the evaluated result or, under the control of CTX, give an error, set
1358 NON_CONSTANT_P, and return the unevaluated call T otherwise. */
1360 static tree
1361 cxx_eval_internal_function (const constexpr_ctx *ctx, tree t,
1362 bool lval,
1363 bool *non_constant_p, bool *overflow_p)
1365 enum tree_code opcode = ERROR_MARK;
1367 switch (CALL_EXPR_IFN (t))
1369 case IFN_UBSAN_NULL:
1370 case IFN_UBSAN_BOUNDS:
1371 case IFN_UBSAN_VPTR:
1372 case IFN_FALLTHROUGH:
1373 return void_node;
1375 case IFN_ADD_OVERFLOW:
1376 opcode = PLUS_EXPR;
1377 break;
1378 case IFN_SUB_OVERFLOW:
1379 opcode = MINUS_EXPR;
1380 break;
1381 case IFN_MUL_OVERFLOW:
1382 opcode = MULT_EXPR;
1383 break;
1385 case IFN_LAUNDER:
1386 return cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0),
1387 false, non_constant_p, overflow_p);
1389 default:
1390 if (!ctx->quiet)
1391 error_at (EXPR_LOC_OR_LOC (t, input_location),
1392 "call to internal function %qE", t);
1393 *non_constant_p = true;
1394 return t;
1397 /* Evaluate constant arguments using OPCODE and return a complex
1398 number containing the result and the overflow bit. */
1399 tree arg0 = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0), lval,
1400 non_constant_p, overflow_p);
1401 tree arg1 = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 1), lval,
1402 non_constant_p, overflow_p);
1404 if (TREE_CODE (arg0) == INTEGER_CST && TREE_CODE (arg1) == INTEGER_CST)
1406 location_t loc = EXPR_LOC_OR_LOC (t, input_location);
1407 tree type = TREE_TYPE (TREE_TYPE (t));
1408 tree result = fold_binary_loc (loc, opcode, type,
1409 fold_convert_loc (loc, type, arg0),
1410 fold_convert_loc (loc, type, arg1));
1411 tree ovf
1412 = build_int_cst (type, arith_overflowed_p (opcode, type, arg0, arg1));
1413 /* Reset TREE_OVERFLOW to avoid warnings for the overflow. */
1414 if (TREE_OVERFLOW (result))
1415 TREE_OVERFLOW (result) = 0;
1417 return build_complex (TREE_TYPE (t), result, ovf);
1420 *non_constant_p = true;
1421 return t;
1424 /* Clean CONSTRUCTOR_NO_IMPLICIT_ZERO from CTOR and its sub-aggregates. */
1426 static void
1427 clear_no_implicit_zero (tree ctor)
1429 if (CONSTRUCTOR_NO_IMPLICIT_ZERO (ctor))
1431 CONSTRUCTOR_NO_IMPLICIT_ZERO (ctor) = false;
1432 tree elt; unsigned HOST_WIDE_INT idx;
1433 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (ctor), idx, elt)
1434 if (TREE_CODE (elt) == CONSTRUCTOR)
1435 clear_no_implicit_zero (elt);
1439 /* Subroutine of cxx_eval_constant_expression.
1440 Evaluate the call expression tree T in the context of OLD_CALL expression
1441 evaluation. */
1443 static tree
1444 cxx_eval_call_expression (const constexpr_ctx *ctx, tree t,
1445 bool lval,
1446 bool *non_constant_p, bool *overflow_p)
1448 location_t loc = EXPR_LOC_OR_LOC (t, input_location);
1449 tree fun = get_function_named_in_call (t);
1450 constexpr_call new_call = { NULL, NULL, NULL, 0 };
1451 bool depth_ok;
1453 if (fun == NULL_TREE)
1454 return cxx_eval_internal_function (ctx, t, lval,
1455 non_constant_p, overflow_p);
1457 if (TREE_CODE (fun) != FUNCTION_DECL)
1459 /* Might be a constexpr function pointer. */
1460 fun = cxx_eval_constant_expression (ctx, fun,
1461 /*lval*/false, non_constant_p,
1462 overflow_p);
1463 STRIP_NOPS (fun);
1464 if (TREE_CODE (fun) == ADDR_EXPR)
1465 fun = TREE_OPERAND (fun, 0);
1467 if (TREE_CODE (fun) != FUNCTION_DECL)
1469 if (!ctx->quiet && !*non_constant_p)
1470 error_at (loc, "expression %qE does not designate a %<constexpr%> "
1471 "function", fun);
1472 *non_constant_p = true;
1473 return t;
1475 if (DECL_CLONED_FUNCTION_P (fun))
1476 fun = DECL_CLONED_FUNCTION (fun);
1478 if (is_ubsan_builtin_p (fun))
1479 return void_node;
1481 if (is_builtin_fn (fun))
1482 return cxx_eval_builtin_function_call (ctx, t, fun,
1483 lval, non_constant_p, overflow_p);
1484 if (!DECL_DECLARED_CONSTEXPR_P (fun))
1486 if (!ctx->quiet)
1488 if (!lambda_static_thunk_p (fun))
1489 error_at (loc, "call to non-%<constexpr%> function %qD", fun);
1490 explain_invalid_constexpr_fn (fun);
1492 *non_constant_p = true;
1493 return t;
1496 constexpr_ctx new_ctx = *ctx;
1497 if (DECL_CONSTRUCTOR_P (fun) && !ctx->object
1498 && TREE_CODE (t) == AGGR_INIT_EXPR)
1500 /* We want to have an initialization target for an AGGR_INIT_EXPR.
1501 If we don't already have one in CTX, use the AGGR_INIT_EXPR_SLOT. */
1502 new_ctx.object = AGGR_INIT_EXPR_SLOT (t);
1503 tree ctor = new_ctx.ctor = build_constructor (DECL_CONTEXT (fun), NULL);
1504 CONSTRUCTOR_NO_IMPLICIT_ZERO (ctor) = true;
1505 ctx->values->put (new_ctx.object, ctor);
1506 ctx = &new_ctx;
1509 /* Shortcut trivial constructor/op=. */
1510 if (trivial_fn_p (fun))
1512 tree init = NULL_TREE;
1513 if (call_expr_nargs (t) == 2)
1514 init = convert_from_reference (get_nth_callarg (t, 1));
1515 else if (TREE_CODE (t) == AGGR_INIT_EXPR
1516 && AGGR_INIT_ZERO_FIRST (t))
1517 init = build_zero_init (DECL_CONTEXT (fun), NULL_TREE, false);
1518 if (init)
1520 tree op = get_nth_callarg (t, 0);
1521 if (is_dummy_object (op))
1522 op = ctx->object;
1523 else
1524 op = build1 (INDIRECT_REF, TREE_TYPE (TREE_TYPE (op)), op);
1525 tree set = build2 (MODIFY_EXPR, TREE_TYPE (op), op, init);
1526 new_ctx.call = &new_call;
1527 return cxx_eval_constant_expression (&new_ctx, set, lval,
1528 non_constant_p, overflow_p);
1532 /* We can't defer instantiating the function any longer. */
1533 if (!DECL_INITIAL (fun)
1534 && DECL_TEMPLOID_INSTANTIATION (fun))
1536 location_t save_loc = input_location;
1537 input_location = loc;
1538 ++function_depth;
1539 instantiate_decl (fun, /*defer_ok*/false, /*expl_inst*/false);
1540 --function_depth;
1541 input_location = save_loc;
1544 /* If in direct recursive call, optimize definition search. */
1545 if (ctx && ctx->call && ctx->call->fundef && ctx->call->fundef->decl == fun)
1546 new_call.fundef = ctx->call->fundef;
1547 else
1549 new_call.fundef = retrieve_constexpr_fundef (fun);
1550 if (new_call.fundef == NULL || new_call.fundef->body == NULL
1551 || fun == current_function_decl)
1553 if (!ctx->quiet)
1555 /* We need to check for current_function_decl here in case we're
1556 being called during cp_fold_function, because at that point
1557 DECL_INITIAL is set properly and we have a fundef but we
1558 haven't lowered invisirefs yet (c++/70344). */
1559 if (DECL_INITIAL (fun) == error_mark_node
1560 || fun == current_function_decl)
1561 error_at (loc, "%qD called in a constant expression before its "
1562 "definition is complete", fun);
1563 else if (DECL_INITIAL (fun))
1565 /* The definition of fun was somehow unsuitable. But pretend
1566 that lambda static thunks don't exist. */
1567 if (!lambda_static_thunk_p (fun))
1568 error_at (loc, "%qD called in a constant expression", fun);
1569 explain_invalid_constexpr_fn (fun);
1571 else
1572 error_at (loc, "%qD used before its definition", fun);
1574 *non_constant_p = true;
1575 return t;
1579 bool non_constant_args = false;
1580 cxx_bind_parameters_in_call (ctx, t, &new_call,
1581 non_constant_p, overflow_p, &non_constant_args);
1582 if (*non_constant_p)
1583 return t;
1585 depth_ok = push_cx_call_context (t);
1587 tree result = NULL_TREE;
1589 constexpr_call *entry = NULL;
1590 if (depth_ok && !non_constant_args && ctx->strict)
1592 new_call.hash = iterative_hash_template_arg
1593 (new_call.bindings, constexpr_fundef_hasher::hash (new_call.fundef));
1595 /* If we have seen this call before, we are done. */
1596 maybe_initialize_constexpr_call_table ();
1597 constexpr_call **slot
1598 = constexpr_call_table->find_slot (&new_call, INSERT);
1599 entry = *slot;
1600 if (entry == NULL)
1602 /* We need to keep a pointer to the entry, not just the slot, as the
1603 slot can move in the call to cxx_eval_builtin_function_call. */
1604 *slot = entry = ggc_alloc<constexpr_call> ();
1605 *entry = new_call;
1607 /* Calls that are in progress have their result set to NULL,
1608 so that we can detect circular dependencies. */
1609 else if (entry->result == NULL)
1611 if (!ctx->quiet)
1612 error ("call has circular dependency");
1613 *non_constant_p = true;
1614 entry->result = result = error_mark_node;
1616 else
1617 result = entry->result;
1620 if (!depth_ok)
1622 if (!ctx->quiet)
1623 error ("%<constexpr%> evaluation depth exceeds maximum of %d (use "
1624 "-fconstexpr-depth= to increase the maximum)",
1625 max_constexpr_depth);
1626 *non_constant_p = true;
1627 result = error_mark_node;
1629 else
1631 if (result && result != error_mark_node)
1632 /* OK */;
1633 else if (!DECL_SAVED_TREE (fun))
1635 /* When at_eof >= 2, cgraph has started throwing away
1636 DECL_SAVED_TREE, so fail quietly. FIXME we get here because of
1637 late code generation for VEC_INIT_EXPR, which needs to be
1638 completely reconsidered. */
1639 gcc_assert (at_eof >= 2 && ctx->quiet);
1640 *non_constant_p = true;
1642 else
1644 tree body, parms, res;
1646 /* Reuse or create a new unshared copy of this function's body. */
1647 tree copy = get_fundef_copy (fun);
1648 body = TREE_PURPOSE (copy);
1649 parms = TREE_VALUE (copy);
1650 res = TREE_TYPE (copy);
1652 /* Associate the bindings with the remapped parms. */
1653 tree bound = new_call.bindings;
1654 tree remapped = parms;
1655 while (bound)
1657 tree oparm = TREE_PURPOSE (bound);
1658 tree arg = TREE_VALUE (bound);
1659 gcc_assert (DECL_NAME (remapped) == DECL_NAME (oparm));
1660 /* Don't share a CONSTRUCTOR that might be changed. */
1661 arg = unshare_constructor (arg);
1662 ctx->values->put (remapped, arg);
1663 bound = TREE_CHAIN (bound);
1664 remapped = DECL_CHAIN (remapped);
1666 /* Add the RESULT_DECL to the values map, too. */
1667 tree slot = NULL_TREE;
1668 if (DECL_BY_REFERENCE (res))
1670 slot = AGGR_INIT_EXPR_SLOT (t);
1671 tree addr = build_address (slot);
1672 addr = build_nop (TREE_TYPE (res), addr);
1673 ctx->values->put (res, addr);
1674 ctx->values->put (slot, NULL_TREE);
1676 else
1677 ctx->values->put (res, NULL_TREE);
1679 /* Track the callee's evaluated SAVE_EXPRs so that we can forget
1680 their values after the call. */
1681 constexpr_ctx ctx_with_save_exprs = *ctx;
1682 hash_set<tree> save_exprs;
1683 ctx_with_save_exprs.save_exprs = &save_exprs;
1684 ctx_with_save_exprs.call = &new_call;
1686 tree jump_target = NULL_TREE;
1687 cxx_eval_constant_expression (&ctx_with_save_exprs, body,
1688 lval, non_constant_p, overflow_p,
1689 &jump_target);
1691 if (DECL_CONSTRUCTOR_P (fun))
1692 /* This can be null for a subobject constructor call, in
1693 which case what we care about is the initialization
1694 side-effects rather than the value. We could get at the
1695 value by evaluating *this, but we don't bother; there's
1696 no need to put such a call in the hash table. */
1697 result = lval ? ctx->object : ctx->ctor;
1698 else if (VOID_TYPE_P (TREE_TYPE (res)))
1699 result = void_node;
1700 else
1702 result = *ctx->values->get (slot ? slot : res);
1703 if (result == NULL_TREE && !*non_constant_p)
1705 if (!ctx->quiet)
1706 error ("%<constexpr%> call flows off the end "
1707 "of the function");
1708 *non_constant_p = true;
1712 /* Forget the saved values of the callee's SAVE_EXPRs. */
1713 for (hash_set<tree>::iterator iter = save_exprs.begin();
1714 iter != save_exprs.end(); ++iter)
1715 ctx_with_save_exprs.values->remove (*iter);
1717 /* Remove the parms/result from the values map. Is it worth
1718 bothering to do this when the map itself is only live for
1719 one constexpr evaluation? If so, maybe also clear out
1720 other vars from call, maybe in BIND_EXPR handling? */
1721 ctx->values->remove (res);
1722 if (slot)
1723 ctx->values->remove (slot);
1724 for (tree parm = parms; parm; parm = TREE_CHAIN (parm))
1725 ctx->values->remove (parm);
1727 /* Make the unshared function copy we used available for re-use. */
1728 save_fundef_copy (fun, copy);
1731 if (result == error_mark_node)
1732 *non_constant_p = true;
1733 if (*non_constant_p || *overflow_p)
1734 result = error_mark_node;
1735 else if (!result)
1736 result = void_node;
1737 if (entry)
1738 entry->result = result;
1741 /* The result of a constexpr function must be completely initialized. */
1742 if (TREE_CODE (result) == CONSTRUCTOR)
1743 clear_no_implicit_zero (result);
1745 pop_cx_call_context ();
1746 return unshare_constructor (result);
1749 /* FIXME speed this up, it's taking 16% of compile time on sieve testcase. */
1751 bool
1752 reduced_constant_expression_p (tree t)
1754 switch (TREE_CODE (t))
1756 case PTRMEM_CST:
1757 /* Even if we can't lower this yet, it's constant. */
1758 return true;
1760 case CONSTRUCTOR:
1761 /* And we need to handle PTRMEM_CST wrapped in a CONSTRUCTOR. */
1762 tree idx, val, field; unsigned HOST_WIDE_INT i;
1763 if (CONSTRUCTOR_NO_IMPLICIT_ZERO (t))
1764 field = next_initializable_field (TYPE_FIELDS (TREE_TYPE (t)));
1765 else
1766 field = NULL_TREE;
1767 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (t), i, idx, val)
1769 if (!val)
1770 /* We're in the middle of initializing this element. */
1771 return false;
1772 if (!reduced_constant_expression_p (val))
1773 return false;
1774 if (field)
1776 if (idx != field)
1777 return false;
1778 field = next_initializable_field (DECL_CHAIN (field));
1781 if (field)
1782 return false;
1783 else if (CONSTRUCTOR_NO_IMPLICIT_ZERO (t))
1784 /* All the fields are initialized. */
1785 CONSTRUCTOR_NO_IMPLICIT_ZERO (t) = false;
1786 return true;
1788 default:
1789 /* FIXME are we calling this too much? */
1790 return initializer_constant_valid_p (t, TREE_TYPE (t)) != NULL_TREE;
1794 /* Some expressions may have constant operands but are not constant
1795 themselves, such as 1/0. Call this function (or rather, the macro
1796 following it) to check for that condition.
1798 We only call this in places that require an arithmetic constant, not in
1799 places where we might have a non-constant expression that can be a
1800 component of a constant expression, such as the address of a constexpr
1801 variable that might be dereferenced later. */
1803 static bool
1804 verify_constant (tree t, bool allow_non_constant, bool *non_constant_p,
1805 bool *overflow_p)
1807 if (!*non_constant_p && !reduced_constant_expression_p (t))
1809 if (!allow_non_constant)
1810 error ("%q+E is not a constant expression", t);
1811 *non_constant_p = true;
1813 if (TREE_OVERFLOW_P (t))
1815 if (!allow_non_constant)
1817 permerror (input_location, "overflow in constant expression");
1818 /* If we're being permissive (and are in an enforcing
1819 context), ignore the overflow. */
1820 if (flag_permissive)
1821 return *non_constant_p;
1823 *overflow_p = true;
1825 return *non_constant_p;
1828 /* Check whether the shift operation with code CODE and type TYPE on LHS
1829 and RHS is undefined. If it is, give an error with an explanation,
1830 and return true; return false otherwise. */
1832 static bool
1833 cxx_eval_check_shift_p (location_t loc, const constexpr_ctx *ctx,
1834 enum tree_code code, tree type, tree lhs, tree rhs)
1836 if ((code != LSHIFT_EXPR && code != RSHIFT_EXPR)
1837 || TREE_CODE (lhs) != INTEGER_CST
1838 || TREE_CODE (rhs) != INTEGER_CST)
1839 return false;
1841 tree lhstype = TREE_TYPE (lhs);
1842 unsigned HOST_WIDE_INT uprec = TYPE_PRECISION (TREE_TYPE (lhs));
1844 /* [expr.shift] The behavior is undefined if the right operand
1845 is negative, or greater than or equal to the length in bits
1846 of the promoted left operand. */
1847 if (tree_int_cst_sgn (rhs) == -1)
1849 if (!ctx->quiet)
1850 permerror (loc, "right operand of shift expression %q+E is negative",
1851 build2_loc (loc, code, type, lhs, rhs));
1852 return (!flag_permissive || ctx->quiet);
1854 if (compare_tree_int (rhs, uprec) >= 0)
1856 if (!ctx->quiet)
1857 permerror (loc, "right operand of shift expression %q+E is >= than "
1858 "the precision of the left operand",
1859 build2_loc (loc, code, type, lhs, rhs));
1860 return (!flag_permissive || ctx->quiet);
1863 /* The value of E1 << E2 is E1 left-shifted E2 bit positions; [...]
1864 if E1 has a signed type and non-negative value, and E1x2^E2 is
1865 representable in the corresponding unsigned type of the result type,
1866 then that value, converted to the result type, is the resulting value;
1867 otherwise, the behavior is undefined. */
1868 if (code == LSHIFT_EXPR && !TYPE_UNSIGNED (lhstype)
1869 && (cxx_dialect >= cxx11))
1871 if (tree_int_cst_sgn (lhs) == -1)
1873 if (!ctx->quiet)
1874 permerror (loc,
1875 "left operand of shift expression %q+E is negative",
1876 build2_loc (loc, code, type, lhs, rhs));
1877 return (!flag_permissive || ctx->quiet);
1879 /* For signed x << y the following:
1880 (unsigned) x >> ((prec (lhs) - 1) - y)
1881 if > 1, is undefined. The right-hand side of this formula
1882 is the highest bit of the LHS that can be set (starting from 0),
1883 so that the shift doesn't overflow. We then right-shift the LHS
1884 to see whether any other bit is set making the original shift
1885 undefined -- the result is not representable in the corresponding
1886 unsigned type. */
1887 tree t = build_int_cst (unsigned_type_node, uprec - 1);
1888 t = fold_build2 (MINUS_EXPR, unsigned_type_node, t, rhs);
1889 tree ulhs = fold_convert (unsigned_type_for (lhstype), lhs);
1890 t = fold_build2 (RSHIFT_EXPR, TREE_TYPE (ulhs), ulhs, t);
1891 if (tree_int_cst_lt (integer_one_node, t))
1893 if (!ctx->quiet)
1894 permerror (loc, "shift expression %q+E overflows",
1895 build2_loc (loc, code, type, lhs, rhs));
1896 return (!flag_permissive || ctx->quiet);
1899 return false;
1902 /* Subroutine of cxx_eval_constant_expression.
1903 Attempt to reduce the unary expression tree T to a compile time value.
1904 If successful, return the value. Otherwise issue a diagnostic
1905 and return error_mark_node. */
1907 static tree
1908 cxx_eval_unary_expression (const constexpr_ctx *ctx, tree t,
1909 bool /*lval*/,
1910 bool *non_constant_p, bool *overflow_p)
1912 tree r;
1913 tree orig_arg = TREE_OPERAND (t, 0);
1914 tree arg = cxx_eval_constant_expression (ctx, orig_arg, /*lval*/false,
1915 non_constant_p, overflow_p);
1916 VERIFY_CONSTANT (arg);
1917 location_t loc = EXPR_LOCATION (t);
1918 enum tree_code code = TREE_CODE (t);
1919 tree type = TREE_TYPE (t);
1920 r = fold_unary_loc (loc, code, type, arg);
1921 if (r == NULL_TREE)
1923 if (arg == orig_arg)
1924 r = t;
1925 else
1926 r = build1_loc (loc, code, type, arg);
1928 VERIFY_CONSTANT (r);
1929 return r;
1932 /* Helper function for cxx_eval_binary_expression. Try to optimize
1933 original POINTER_PLUS_EXPR T, LHS p+ RHS, return NULL_TREE if the
1934 generic folding should be used. */
1936 static tree
1937 cxx_fold_pointer_plus_expression (const constexpr_ctx *ctx, tree t,
1938 tree lhs, tree rhs, bool *non_constant_p,
1939 bool *overflow_p)
1941 STRIP_NOPS (lhs);
1942 if (TREE_CODE (lhs) != ADDR_EXPR)
1943 return NULL_TREE;
1945 lhs = TREE_OPERAND (lhs, 0);
1947 /* &A[i] p+ j => &A[i + j] */
1948 if (TREE_CODE (lhs) == ARRAY_REF
1949 && TREE_CODE (TREE_OPERAND (lhs, 1)) == INTEGER_CST
1950 && TREE_CODE (rhs) == INTEGER_CST
1951 && TYPE_SIZE_UNIT (TREE_TYPE (lhs))
1952 && TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (lhs))) == INTEGER_CST)
1954 tree orig_type = TREE_TYPE (t);
1955 location_t loc = EXPR_LOCATION (t);
1956 tree type = TREE_TYPE (lhs);
1958 t = fold_convert_loc (loc, ssizetype, TREE_OPERAND (lhs, 1));
1959 tree nelts = array_type_nelts_top (TREE_TYPE (TREE_OPERAND (lhs, 0)));
1960 nelts = cxx_eval_constant_expression (ctx, nelts, false, non_constant_p,
1961 overflow_p);
1962 if (*non_constant_p)
1963 return NULL_TREE;
1964 /* Don't fold an out-of-bound access. */
1965 if (!tree_int_cst_le (t, nelts))
1966 return NULL_TREE;
1967 rhs = cp_fold_convert (ssizetype, rhs);
1968 /* Don't fold if rhs can't be divided exactly by TYPE_SIZE_UNIT.
1969 constexpr int A[1]; ... (char *)&A[0] + 1 */
1970 if (!integer_zerop (fold_build2_loc (loc, TRUNC_MOD_EXPR, sizetype,
1971 rhs, TYPE_SIZE_UNIT (type))))
1972 return NULL_TREE;
1973 /* Make sure to treat the second operand of POINTER_PLUS_EXPR
1974 as signed. */
1975 rhs = fold_build2_loc (loc, EXACT_DIV_EXPR, ssizetype, rhs,
1976 TYPE_SIZE_UNIT (type));
1977 t = size_binop_loc (loc, PLUS_EXPR, rhs, t);
1978 t = build4_loc (loc, ARRAY_REF, type, TREE_OPERAND (lhs, 0),
1979 t, NULL_TREE, NULL_TREE);
1980 t = cp_build_addr_expr (t, tf_warning_or_error);
1981 t = cp_fold_convert (orig_type, t);
1982 return cxx_eval_constant_expression (ctx, t, /*lval*/false,
1983 non_constant_p, overflow_p);
1986 return NULL_TREE;
1989 /* Subroutine of cxx_eval_constant_expression.
1990 Like cxx_eval_unary_expression, except for binary expressions. */
1992 static tree
1993 cxx_eval_binary_expression (const constexpr_ctx *ctx, tree t,
1994 bool /*lval*/,
1995 bool *non_constant_p, bool *overflow_p)
1997 tree r = NULL_TREE;
1998 tree orig_lhs = TREE_OPERAND (t, 0);
1999 tree orig_rhs = TREE_OPERAND (t, 1);
2000 tree lhs, rhs;
2001 lhs = cxx_eval_constant_expression (ctx, orig_lhs, /*lval*/false,
2002 non_constant_p, overflow_p);
2003 /* Don't VERIFY_CONSTANT here, it's unnecessary and will break pointer
2004 subtraction. */
2005 if (*non_constant_p)
2006 return t;
2007 rhs = cxx_eval_constant_expression (ctx, orig_rhs, /*lval*/false,
2008 non_constant_p, overflow_p);
2009 if (*non_constant_p)
2010 return t;
2012 location_t loc = EXPR_LOCATION (t);
2013 enum tree_code code = TREE_CODE (t);
2014 tree type = TREE_TYPE (t);
2016 if (code == EQ_EXPR || code == NE_EXPR)
2018 bool is_code_eq = (code == EQ_EXPR);
2020 if (TREE_CODE (lhs) == PTRMEM_CST
2021 && TREE_CODE (rhs) == PTRMEM_CST)
2022 r = constant_boolean_node (cp_tree_equal (lhs, rhs) == is_code_eq,
2023 type);
2024 else if ((TREE_CODE (lhs) == PTRMEM_CST
2025 || TREE_CODE (rhs) == PTRMEM_CST)
2026 && (null_member_pointer_value_p (lhs)
2027 || null_member_pointer_value_p (rhs)))
2028 r = constant_boolean_node (!is_code_eq, type);
2029 else if (TREE_CODE (lhs) == PTRMEM_CST)
2030 lhs = cplus_expand_constant (lhs);
2031 else if (TREE_CODE (rhs) == PTRMEM_CST)
2032 rhs = cplus_expand_constant (rhs);
2034 if (code == POINTER_PLUS_EXPR && !*non_constant_p
2035 && integer_zerop (lhs) && !integer_zerop (rhs))
2037 if (!ctx->quiet)
2038 error ("arithmetic involving a null pointer in %qE", lhs);
2039 return t;
2041 else if (code == POINTER_PLUS_EXPR)
2042 r = cxx_fold_pointer_plus_expression (ctx, t, lhs, rhs, non_constant_p,
2043 overflow_p);
2045 if (r == NULL_TREE)
2046 r = fold_binary_loc (loc, code, type, lhs, rhs);
2048 if (r == NULL_TREE)
2050 if (lhs == orig_lhs && rhs == orig_rhs)
2051 r = t;
2052 else
2053 r = build2_loc (loc, code, type, lhs, rhs);
2055 else if (cxx_eval_check_shift_p (loc, ctx, code, type, lhs, rhs))
2056 *non_constant_p = true;
2057 /* Don't VERIFY_CONSTANT if this might be dealing with a pointer to
2058 a local array in a constexpr function. */
2059 bool ptr = POINTER_TYPE_P (TREE_TYPE (lhs));
2060 if (!ptr)
2061 VERIFY_CONSTANT (r);
2062 return r;
2065 /* Subroutine of cxx_eval_constant_expression.
2066 Attempt to evaluate condition expressions. Dead branches are not
2067 looked into. */
2069 static tree
2070 cxx_eval_conditional_expression (const constexpr_ctx *ctx, tree t,
2071 bool lval,
2072 bool *non_constant_p, bool *overflow_p,
2073 tree *jump_target)
2075 tree val = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
2076 /*lval*/false,
2077 non_constant_p, overflow_p);
2078 VERIFY_CONSTANT (val);
2079 /* Don't VERIFY_CONSTANT the other operands. */
2080 if (integer_zerop (val))
2081 return cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 2),
2082 lval,
2083 non_constant_p, overflow_p,
2084 jump_target);
2085 return cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
2086 lval,
2087 non_constant_p, overflow_p,
2088 jump_target);
2091 /* Subroutine of cxx_eval_constant_expression.
2092 Attempt to evaluate vector condition expressions. Unlike
2093 cxx_eval_conditional_expression, VEC_COND_EXPR acts like a normal
2094 ternary arithmetics operation, where all 3 arguments have to be
2095 evaluated as constants and then folding computes the result from
2096 them. */
2098 static tree
2099 cxx_eval_vector_conditional_expression (const constexpr_ctx *ctx, tree t,
2100 bool *non_constant_p, bool *overflow_p)
2102 tree arg1 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
2103 /*lval*/false,
2104 non_constant_p, overflow_p);
2105 VERIFY_CONSTANT (arg1);
2106 tree arg2 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
2107 /*lval*/false,
2108 non_constant_p, overflow_p);
2109 VERIFY_CONSTANT (arg2);
2110 tree arg3 = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 2),
2111 /*lval*/false,
2112 non_constant_p, overflow_p);
2113 VERIFY_CONSTANT (arg3);
2114 location_t loc = EXPR_LOCATION (t);
2115 tree type = TREE_TYPE (t);
2116 tree r = fold_ternary_loc (loc, VEC_COND_EXPR, type, arg1, arg2, arg3);
2117 if (r == NULL_TREE)
2119 if (arg1 == TREE_OPERAND (t, 0)
2120 && arg2 == TREE_OPERAND (t, 1)
2121 && arg3 == TREE_OPERAND (t, 2))
2122 r = t;
2123 else
2124 r = build3_loc (loc, VEC_COND_EXPR, type, arg1, arg2, arg3);
2126 VERIFY_CONSTANT (r);
2127 return r;
2130 /* Returns less than, equal to, or greater than zero if KEY is found to be
2131 less than, to match, or to be greater than the constructor_elt's INDEX. */
2133 static int
2134 array_index_cmp (tree key, tree index)
2136 gcc_assert (TREE_CODE (key) == INTEGER_CST);
2138 switch (TREE_CODE (index))
2140 case INTEGER_CST:
2141 return tree_int_cst_compare (key, index);
2142 case RANGE_EXPR:
2144 tree lo = TREE_OPERAND (index, 0);
2145 tree hi = TREE_OPERAND (index, 1);
2146 if (tree_int_cst_lt (key, lo))
2147 return -1;
2148 else if (tree_int_cst_lt (hi, key))
2149 return 1;
2150 else
2151 return 0;
2153 default:
2154 gcc_unreachable ();
2158 /* Returns the index of the constructor_elt of ARY which matches DINDEX, or -1
2159 if none. If INSERT is true, insert a matching element rather than fail. */
2161 static HOST_WIDE_INT
2162 find_array_ctor_elt (tree ary, tree dindex, bool insert = false)
2164 if (tree_int_cst_sgn (dindex) < 0)
2165 return -1;
2167 unsigned HOST_WIDE_INT i = tree_to_uhwi (dindex);
2168 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ary);
2169 unsigned HOST_WIDE_INT len = vec_safe_length (elts);
2171 unsigned HOST_WIDE_INT end = len;
2172 unsigned HOST_WIDE_INT begin = 0;
2174 /* If the last element of the CONSTRUCTOR has its own index, we can assume
2175 that the same is true of the other elements and index directly. */
2176 if (end > 0)
2178 tree cindex = (*elts)[end-1].index;
2179 if (TREE_CODE (cindex) == INTEGER_CST
2180 && compare_tree_int (cindex, end-1) == 0)
2182 if (i < end)
2183 return i;
2184 else
2185 begin = end;
2189 /* Otherwise, find a matching index by means of a binary search. */
2190 while (begin != end)
2192 unsigned HOST_WIDE_INT middle = (begin + end) / 2;
2193 constructor_elt &elt = (*elts)[middle];
2194 tree idx = elt.index;
2196 int cmp = array_index_cmp (dindex, idx);
2197 if (cmp < 0)
2198 end = middle;
2199 else if (cmp > 0)
2200 begin = middle + 1;
2201 else
2203 if (insert && TREE_CODE (idx) == RANGE_EXPR)
2205 /* We need to split the range. */
2206 constructor_elt e;
2207 tree lo = TREE_OPERAND (idx, 0);
2208 tree hi = TREE_OPERAND (idx, 1);
2209 if (tree_int_cst_lt (lo, dindex))
2211 /* There are still some lower elts; shorten the range. */
2212 tree new_hi = int_const_binop (MINUS_EXPR, dindex,
2213 size_one_node);
2214 if (tree_int_cst_equal (lo, new_hi))
2215 /* Only one element left, no longer a range. */
2216 elt.index = lo;
2217 else
2218 TREE_OPERAND (idx, 1) = new_hi;
2219 /* Append the element we want to insert. */
2220 ++middle;
2221 e.index = dindex;
2222 e.value = unshare_constructor (elt.value);
2223 vec_safe_insert (CONSTRUCTOR_ELTS (ary), middle, e);
2225 else
2226 /* No lower elts, the range elt is now ours. */
2227 elt.index = dindex;
2229 if (tree_int_cst_lt (dindex, hi))
2231 /* There are still some higher elts; append a range. */
2232 tree new_lo = int_const_binop (PLUS_EXPR, dindex,
2233 size_one_node);
2234 if (tree_int_cst_equal (new_lo, hi))
2235 e.index = hi;
2236 else
2237 e.index = build2 (RANGE_EXPR, sizetype, new_lo, hi);
2238 e.value = unshare_constructor (elt.value);
2239 vec_safe_insert (CONSTRUCTOR_ELTS (ary), middle+1, e);
2242 return middle;
2246 if (insert)
2248 constructor_elt e = { dindex, NULL_TREE };
2249 vec_safe_insert (CONSTRUCTOR_ELTS (ary), end, e);
2250 return end;
2253 return -1;
2256 /* Under the control of CTX, issue a detailed diagnostic for
2257 an out-of-bounds subscript INDEX into the expression ARRAY. */
2259 static void
2260 diag_array_subscript (const constexpr_ctx *ctx, tree array, tree index)
2262 if (!ctx->quiet)
2264 tree arraytype = TREE_TYPE (array);
2266 /* Convert the unsigned array subscript to a signed integer to avoid
2267 printing huge numbers for small negative values. */
2268 tree sidx = fold_convert (ssizetype, index);
2269 if (DECL_P (array))
2271 error ("array subscript value %qE is outside the bounds "
2272 "of array %qD of type %qT", sidx, array, arraytype);
2273 inform (DECL_SOURCE_LOCATION (array), "declared here");
2275 else
2276 error ("array subscript value %qE is outside the bounds "
2277 "of array type %qT", sidx, arraytype);
2281 /* Extract element INDEX consisting of CHARS_PER_ELT chars from
2282 STRING_CST STRING. */
2284 static tree
2285 extract_string_elt (tree string, unsigned chars_per_elt, unsigned index)
2287 tree type = cv_unqualified (TREE_TYPE (TREE_TYPE (string)));
2288 tree r;
2290 if (chars_per_elt == 1)
2291 r = build_int_cst (type, TREE_STRING_POINTER (string)[index]);
2292 else
2294 const unsigned char *ptr
2295 = ((const unsigned char *)TREE_STRING_POINTER (string)
2296 + index * chars_per_elt);
2297 r = native_interpret_expr (type, ptr, chars_per_elt);
2299 return r;
2302 /* Subroutine of cxx_eval_constant_expression.
2303 Attempt to reduce a reference to an array slot. */
2305 static tree
2306 cxx_eval_array_reference (const constexpr_ctx *ctx, tree t,
2307 bool lval,
2308 bool *non_constant_p, bool *overflow_p)
2310 tree oldary = TREE_OPERAND (t, 0);
2311 tree ary = cxx_eval_constant_expression (ctx, oldary,
2312 lval,
2313 non_constant_p, overflow_p);
2314 tree index, oldidx;
2315 HOST_WIDE_INT i = 0;
2316 tree elem_type = NULL_TREE;
2317 unsigned len = 0, elem_nchars = 1;
2318 if (*non_constant_p)
2319 return t;
2320 oldidx = TREE_OPERAND (t, 1);
2321 index = cxx_eval_constant_expression (ctx, oldidx,
2322 false,
2323 non_constant_p, overflow_p);
2324 VERIFY_CONSTANT (index);
2325 if (!lval)
2327 elem_type = TREE_TYPE (TREE_TYPE (ary));
2328 if (TREE_CODE (ary) == VIEW_CONVERT_EXPR
2329 && VECTOR_TYPE_P (TREE_TYPE (TREE_OPERAND (ary, 0)))
2330 && TREE_TYPE (t) == TREE_TYPE (TREE_TYPE (TREE_OPERAND (ary, 0))))
2331 ary = TREE_OPERAND (ary, 0);
2332 if (TREE_CODE (ary) == CONSTRUCTOR)
2333 len = CONSTRUCTOR_NELTS (ary);
2334 else if (TREE_CODE (ary) == STRING_CST)
2336 elem_nchars = (TYPE_PRECISION (elem_type)
2337 / TYPE_PRECISION (char_type_node));
2338 len = (unsigned) TREE_STRING_LENGTH (ary) / elem_nchars;
2340 else if (TREE_CODE (ary) == VECTOR_CST)
2341 len = VECTOR_CST_NELTS (ary);
2342 else
2344 /* We can't do anything with other tree codes, so use
2345 VERIFY_CONSTANT to complain and fail. */
2346 VERIFY_CONSTANT (ary);
2347 gcc_unreachable ();
2350 if (!tree_fits_shwi_p (index)
2351 || (i = tree_to_shwi (index)) < 0)
2353 diag_array_subscript (ctx, ary, index);
2354 *non_constant_p = true;
2355 return t;
2359 tree nelts;
2360 if (TREE_CODE (TREE_TYPE (ary)) == ARRAY_TYPE)
2361 nelts = array_type_nelts_top (TREE_TYPE (ary));
2362 else if (VECTOR_TYPE_P (TREE_TYPE (ary)))
2363 nelts = size_int (TYPE_VECTOR_SUBPARTS (TREE_TYPE (ary)));
2364 else
2365 gcc_unreachable ();
2367 /* For VLAs, the number of elements won't be an integer constant. */
2368 nelts = cxx_eval_constant_expression (ctx, nelts, false, non_constant_p,
2369 overflow_p);
2370 VERIFY_CONSTANT (nelts);
2371 if ((lval
2372 ? !tree_int_cst_le (index, nelts)
2373 : !tree_int_cst_lt (index, nelts))
2374 || tree_int_cst_sgn (index) < 0)
2376 diag_array_subscript (ctx, ary, index);
2377 *non_constant_p = true;
2378 return t;
2381 if (lval && ary == oldary && index == oldidx)
2382 return t;
2383 else if (lval)
2384 return build4 (ARRAY_REF, TREE_TYPE (t), ary, index, NULL, NULL);
2386 bool found;
2387 if (TREE_CODE (ary) == CONSTRUCTOR)
2389 HOST_WIDE_INT ix = find_array_ctor_elt (ary, index);
2390 found = (ix >= 0);
2391 if (found)
2392 i = ix;
2394 else
2395 found = (i < len);
2397 if (found)
2399 tree r;
2400 if (TREE_CODE (ary) == CONSTRUCTOR)
2401 r = (*CONSTRUCTOR_ELTS (ary))[i].value;
2402 else if (TREE_CODE (ary) == VECTOR_CST)
2403 r = VECTOR_CST_ELT (ary, i);
2404 else
2405 r = extract_string_elt (ary, elem_nchars, i);
2407 if (r)
2408 /* Don't VERIFY_CONSTANT here. */
2409 return r;
2411 /* Otherwise the element doesn't have a value yet. */
2414 /* Not found. */
2416 if (TREE_CODE (ary) == CONSTRUCTOR
2417 && CONSTRUCTOR_NO_IMPLICIT_ZERO (ary))
2419 /* 'ary' is part of the aggregate initializer we're currently
2420 building; if there's no initializer for this element yet,
2421 that's an error. */
2422 if (!ctx->quiet)
2423 error ("accessing uninitialized array element");
2424 *non_constant_p = true;
2425 return t;
2428 /* If it's within the array bounds but doesn't have an explicit
2429 initializer, it's value-initialized. */
2430 tree val = build_value_init (elem_type, tf_warning_or_error);
2431 return cxx_eval_constant_expression (ctx, val, lval, non_constant_p,
2432 overflow_p);
2435 /* Subroutine of cxx_eval_constant_expression.
2436 Attempt to reduce a field access of a value of class type. */
2438 static tree
2439 cxx_eval_component_reference (const constexpr_ctx *ctx, tree t,
2440 bool lval,
2441 bool *non_constant_p, bool *overflow_p)
2443 unsigned HOST_WIDE_INT i;
2444 tree field;
2445 tree value;
2446 tree part = TREE_OPERAND (t, 1);
2447 tree orig_whole = TREE_OPERAND (t, 0);
2448 tree whole = cxx_eval_constant_expression (ctx, orig_whole,
2449 lval,
2450 non_constant_p, overflow_p);
2451 if (TREE_CODE (whole) == INDIRECT_REF
2452 && integer_zerop (TREE_OPERAND (whole, 0))
2453 && !ctx->quiet)
2454 error ("dereferencing a null pointer in %qE", orig_whole);
2456 if (TREE_CODE (whole) == PTRMEM_CST)
2457 whole = cplus_expand_constant (whole);
2458 if (whole == orig_whole)
2459 return t;
2460 if (lval)
2461 return fold_build3 (COMPONENT_REF, TREE_TYPE (t),
2462 whole, part, NULL_TREE);
2463 /* Don't VERIFY_CONSTANT here; we only want to check that we got a
2464 CONSTRUCTOR. */
2465 if (!*non_constant_p && TREE_CODE (whole) != CONSTRUCTOR)
2467 if (!ctx->quiet)
2468 error ("%qE is not a constant expression", orig_whole);
2469 *non_constant_p = true;
2471 if (DECL_MUTABLE_P (part))
2473 if (!ctx->quiet)
2474 error ("mutable %qD is not usable in a constant expression", part);
2475 *non_constant_p = true;
2477 if (*non_constant_p)
2478 return t;
2479 bool pmf = TYPE_PTRMEMFUNC_P (TREE_TYPE (whole));
2480 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
2482 /* Use name match for PMF fields, as a variant will have a
2483 different FIELD_DECL with a different type. */
2484 if (pmf ? DECL_NAME (field) == DECL_NAME (part)
2485 : field == part)
2487 if (value)
2488 return value;
2489 else
2490 /* We're in the middle of initializing it. */
2491 break;
2494 if (TREE_CODE (TREE_TYPE (whole)) == UNION_TYPE
2495 && CONSTRUCTOR_NELTS (whole) > 0)
2497 /* DR 1188 says we don't have to deal with this. */
2498 if (!ctx->quiet)
2499 error ("accessing %qD member instead of initialized %qD member in "
2500 "constant expression", part, CONSTRUCTOR_ELT (whole, 0)->index);
2501 *non_constant_p = true;
2502 return t;
2505 /* We only create a CONSTRUCTOR for a subobject when we modify it, so empty
2506 classes never get represented; throw together a value now. */
2507 if (is_really_empty_class (TREE_TYPE (t)))
2508 return build_constructor (TREE_TYPE (t), NULL);
2510 gcc_assert (DECL_CONTEXT (part) == TYPE_MAIN_VARIANT (TREE_TYPE (whole)));
2512 if (CONSTRUCTOR_NO_IMPLICIT_ZERO (whole))
2514 /* 'whole' is part of the aggregate initializer we're currently
2515 building; if there's no initializer for this member yet, that's an
2516 error. */
2517 if (!ctx->quiet)
2518 error ("accessing uninitialized member %qD", part);
2519 *non_constant_p = true;
2520 return t;
2523 /* If there's no explicit init for this field, it's value-initialized. */
2524 value = build_value_init (TREE_TYPE (t), tf_warning_or_error);
2525 return cxx_eval_constant_expression (ctx, value,
2526 lval,
2527 non_constant_p, overflow_p);
2530 /* Subroutine of cxx_eval_constant_expression.
2531 Attempt to reduce a field access of a value of class type that is
2532 expressed as a BIT_FIELD_REF. */
2534 static tree
2535 cxx_eval_bit_field_ref (const constexpr_ctx *ctx, tree t,
2536 bool lval,
2537 bool *non_constant_p, bool *overflow_p)
2539 tree orig_whole = TREE_OPERAND (t, 0);
2540 tree retval, fldval, utype, mask;
2541 bool fld_seen = false;
2542 HOST_WIDE_INT istart, isize;
2543 tree whole = cxx_eval_constant_expression (ctx, orig_whole,
2544 lval,
2545 non_constant_p, overflow_p);
2546 tree start, field, value;
2547 unsigned HOST_WIDE_INT i;
2549 if (whole == orig_whole)
2550 return t;
2551 /* Don't VERIFY_CONSTANT here; we only want to check that we got a
2552 CONSTRUCTOR. */
2553 if (!*non_constant_p
2554 && TREE_CODE (whole) != VECTOR_CST
2555 && TREE_CODE (whole) != CONSTRUCTOR)
2557 if (!ctx->quiet)
2558 error ("%qE is not a constant expression", orig_whole);
2559 *non_constant_p = true;
2561 if (*non_constant_p)
2562 return t;
2564 if (TREE_CODE (whole) == VECTOR_CST)
2565 return fold_ternary (BIT_FIELD_REF, TREE_TYPE (t), whole,
2566 TREE_OPERAND (t, 1), TREE_OPERAND (t, 2));
2568 start = TREE_OPERAND (t, 2);
2569 istart = tree_to_shwi (start);
2570 isize = tree_to_shwi (TREE_OPERAND (t, 1));
2571 utype = TREE_TYPE (t);
2572 if (!TYPE_UNSIGNED (utype))
2573 utype = build_nonstandard_integer_type (TYPE_PRECISION (utype), 1);
2574 retval = build_int_cst (utype, 0);
2575 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
2577 tree bitpos = bit_position (field);
2578 if (bitpos == start && DECL_SIZE (field) == TREE_OPERAND (t, 1))
2579 return value;
2580 if (TREE_CODE (TREE_TYPE (field)) == INTEGER_TYPE
2581 && TREE_CODE (value) == INTEGER_CST
2582 && tree_fits_shwi_p (bitpos)
2583 && tree_fits_shwi_p (DECL_SIZE (field)))
2585 HOST_WIDE_INT bit = tree_to_shwi (bitpos);
2586 HOST_WIDE_INT sz = tree_to_shwi (DECL_SIZE (field));
2587 HOST_WIDE_INT shift;
2588 if (bit >= istart && bit + sz <= istart + isize)
2590 fldval = fold_convert (utype, value);
2591 mask = build_int_cst_type (utype, -1);
2592 mask = fold_build2 (LSHIFT_EXPR, utype, mask,
2593 size_int (TYPE_PRECISION (utype) - sz));
2594 mask = fold_build2 (RSHIFT_EXPR, utype, mask,
2595 size_int (TYPE_PRECISION (utype) - sz));
2596 fldval = fold_build2 (BIT_AND_EXPR, utype, fldval, mask);
2597 shift = bit - istart;
2598 if (BYTES_BIG_ENDIAN)
2599 shift = TYPE_PRECISION (utype) - shift - sz;
2600 fldval = fold_build2 (LSHIFT_EXPR, utype, fldval,
2601 size_int (shift));
2602 retval = fold_build2 (BIT_IOR_EXPR, utype, retval, fldval);
2603 fld_seen = true;
2607 if (fld_seen)
2608 return fold_convert (TREE_TYPE (t), retval);
2609 gcc_unreachable ();
2610 return error_mark_node;
2613 /* Subroutine of cxx_eval_constant_expression.
2614 Evaluate a short-circuited logical expression T in the context
2615 of a given constexpr CALL. BAILOUT_VALUE is the value for
2616 early return. CONTINUE_VALUE is used here purely for
2617 sanity check purposes. */
2619 static tree
2620 cxx_eval_logical_expression (const constexpr_ctx *ctx, tree t,
2621 tree bailout_value, tree continue_value,
2622 bool lval,
2623 bool *non_constant_p, bool *overflow_p)
2625 tree r;
2626 tree lhs = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
2627 lval,
2628 non_constant_p, overflow_p);
2629 VERIFY_CONSTANT (lhs);
2630 if (tree_int_cst_equal (lhs, bailout_value))
2631 return lhs;
2632 gcc_assert (tree_int_cst_equal (lhs, continue_value));
2633 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
2634 lval, non_constant_p,
2635 overflow_p);
2636 VERIFY_CONSTANT (r);
2637 return r;
2640 /* REF is a COMPONENT_REF designating a particular field. V is a vector of
2641 CONSTRUCTOR elements to initialize (part of) an object containing that
2642 field. Return a pointer to the constructor_elt corresponding to the
2643 initialization of the field. */
2645 static constructor_elt *
2646 base_field_constructor_elt (vec<constructor_elt, va_gc> *v, tree ref)
2648 tree aggr = TREE_OPERAND (ref, 0);
2649 tree field = TREE_OPERAND (ref, 1);
2650 HOST_WIDE_INT i;
2651 constructor_elt *ce;
2653 gcc_assert (TREE_CODE (ref) == COMPONENT_REF);
2655 if (TREE_CODE (aggr) == COMPONENT_REF)
2657 constructor_elt *base_ce
2658 = base_field_constructor_elt (v, aggr);
2659 v = CONSTRUCTOR_ELTS (base_ce->value);
2662 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
2663 if (ce->index == field)
2664 return ce;
2666 gcc_unreachable ();
2667 return NULL;
2670 /* Some of the expressions fed to the constexpr mechanism are calls to
2671 constructors, which have type void. In that case, return the type being
2672 initialized by the constructor. */
2674 static tree
2675 initialized_type (tree t)
2677 if (TYPE_P (t))
2678 return t;
2679 tree type = cv_unqualified (TREE_TYPE (t));
2680 if (TREE_CODE (t) == CALL_EXPR || TREE_CODE (t) == AGGR_INIT_EXPR)
2682 /* A constructor call has void type, so we need to look deeper. */
2683 tree fn = get_function_named_in_call (t);
2684 if (fn && TREE_CODE (fn) == FUNCTION_DECL
2685 && DECL_CXX_CONSTRUCTOR_P (fn))
2686 type = DECL_CONTEXT (fn);
2688 return type;
2691 /* We're about to initialize element INDEX of an array or class from VALUE.
2692 Set up NEW_CTX appropriately by adjusting .object to refer to the
2693 subobject and creating a new CONSTRUCTOR if the element is itself
2694 a class or array. */
2696 static void
2697 init_subob_ctx (const constexpr_ctx *ctx, constexpr_ctx &new_ctx,
2698 tree index, tree &value)
2700 new_ctx = *ctx;
2702 if (index && TREE_CODE (index) != INTEGER_CST
2703 && TREE_CODE (index) != FIELD_DECL)
2704 /* This won't have an element in the new CONSTRUCTOR. */
2705 return;
2707 tree type = initialized_type (value);
2708 if (!AGGREGATE_TYPE_P (type) && !VECTOR_TYPE_P (type))
2709 /* A non-aggregate member doesn't get its own CONSTRUCTOR. */
2710 return;
2712 /* The sub-aggregate initializer might contain a placeholder;
2713 update object to refer to the subobject and ctor to refer to
2714 the (newly created) sub-initializer. */
2715 if (ctx->object)
2716 new_ctx.object = build_ctor_subob_ref (index, type, ctx->object);
2717 tree elt = build_constructor (type, NULL);
2718 CONSTRUCTOR_NO_IMPLICIT_ZERO (elt) = true;
2719 new_ctx.ctor = elt;
2721 if (TREE_CODE (value) == TARGET_EXPR)
2722 /* Avoid creating another CONSTRUCTOR when we expand the TARGET_EXPR. */
2723 value = TARGET_EXPR_INITIAL (value);
2726 /* We're about to process an initializer for a class or array TYPE. Make
2727 sure that CTX is set up appropriately. */
2729 static void
2730 verify_ctor_sanity (const constexpr_ctx *ctx, tree type)
2732 /* We don't bother building a ctor for an empty base subobject. */
2733 if (is_empty_class (type))
2734 return;
2736 /* We're in the middle of an initializer that might involve placeholders;
2737 our caller should have created a CONSTRUCTOR for us to put the
2738 initializer into. We will either return that constructor or T. */
2739 gcc_assert (ctx->ctor);
2740 gcc_assert (same_type_ignoring_top_level_qualifiers_p
2741 (type, TREE_TYPE (ctx->ctor)));
2742 /* We used to check that ctx->ctor was empty, but that isn't the case when
2743 the object is zero-initialized before calling the constructor. */
2744 if (ctx->object)
2746 tree otype = TREE_TYPE (ctx->object);
2747 gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, otype)
2748 /* Handle flexible array members. */
2749 || (TREE_CODE (otype) == ARRAY_TYPE
2750 && TYPE_DOMAIN (otype) == NULL_TREE
2751 && TREE_CODE (type) == ARRAY_TYPE
2752 && (same_type_ignoring_top_level_qualifiers_p
2753 (TREE_TYPE (type), TREE_TYPE (otype)))));
2755 gcc_assert (!ctx->object || !DECL_P (ctx->object)
2756 || *(ctx->values->get (ctx->object)) == ctx->ctor);
2759 /* Subroutine of cxx_eval_constant_expression.
2760 The expression tree T denotes a C-style array or a C-style
2761 aggregate. Reduce it to a constant expression. */
2763 static tree
2764 cxx_eval_bare_aggregate (const constexpr_ctx *ctx, tree t,
2765 bool lval,
2766 bool *non_constant_p, bool *overflow_p)
2768 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
2769 bool changed = false;
2770 gcc_assert (!BRACE_ENCLOSED_INITIALIZER_P (t));
2771 tree type = TREE_TYPE (t);
2773 constexpr_ctx new_ctx;
2774 if (TYPE_PTRMEMFUNC_P (type) || VECTOR_TYPE_P (type))
2776 /* We don't really need the ctx->ctor business for a PMF or
2777 vector, but it's simpler to use the same code. */
2778 new_ctx = *ctx;
2779 new_ctx.ctor = build_constructor (type, NULL);
2780 new_ctx.object = NULL_TREE;
2781 ctx = &new_ctx;
2783 verify_ctor_sanity (ctx, type);
2784 vec<constructor_elt, va_gc> **p = &CONSTRUCTOR_ELTS (ctx->ctor);
2785 vec_alloc (*p, vec_safe_length (v));
2787 unsigned i;
2788 tree index, value;
2789 bool constant_p = true;
2790 bool side_effects_p = false;
2791 FOR_EACH_CONSTRUCTOR_ELT (v, i, index, value)
2793 tree orig_value = value;
2794 init_subob_ctx (ctx, new_ctx, index, value);
2795 if (new_ctx.ctor != ctx->ctor)
2796 /* If we built a new CONSTRUCTOR, attach it now so that other
2797 initializers can refer to it. */
2798 CONSTRUCTOR_APPEND_ELT (*p, index, new_ctx.ctor);
2799 tree elt = cxx_eval_constant_expression (&new_ctx, value,
2800 lval,
2801 non_constant_p, overflow_p);
2802 /* Don't VERIFY_CONSTANT here. */
2803 if (ctx->quiet && *non_constant_p)
2804 break;
2805 if (elt != orig_value)
2806 changed = true;
2808 if (!TREE_CONSTANT (elt))
2809 constant_p = false;
2810 if (TREE_SIDE_EFFECTS (elt))
2811 side_effects_p = true;
2812 if (index && TREE_CODE (index) == COMPONENT_REF)
2814 /* This is an initialization of a vfield inside a base
2815 subaggregate that we already initialized; push this
2816 initialization into the previous initialization. */
2817 constructor_elt *inner = base_field_constructor_elt (*p, index);
2818 inner->value = elt;
2819 changed = true;
2821 else if (index
2822 && (TREE_CODE (index) == NOP_EXPR
2823 || TREE_CODE (index) == POINTER_PLUS_EXPR))
2825 /* This is an initializer for an empty base; now that we've
2826 checked that it's constant, we can ignore it. */
2827 gcc_assert (is_empty_class (TREE_TYPE (TREE_TYPE (index))));
2828 changed = true;
2830 else if (new_ctx.ctor != ctx->ctor)
2832 /* We appended this element above; update the value. */
2833 gcc_assert ((*p)->last().index == index);
2834 (*p)->last().value = elt;
2836 else
2837 CONSTRUCTOR_APPEND_ELT (*p, index, elt);
2839 if (*non_constant_p || !changed)
2840 return t;
2841 t = ctx->ctor;
2842 /* We're done building this CONSTRUCTOR, so now we can interpret an
2843 element without an explicit initializer as value-initialized. */
2844 CONSTRUCTOR_NO_IMPLICIT_ZERO (t) = false;
2845 TREE_CONSTANT (t) = constant_p;
2846 TREE_SIDE_EFFECTS (t) = side_effects_p;
2847 if (VECTOR_TYPE_P (type))
2848 t = fold (t);
2849 return t;
2852 /* Subroutine of cxx_eval_constant_expression.
2853 The expression tree T is a VEC_INIT_EXPR which denotes the desired
2854 initialization of a non-static data member of array type. Reduce it to a
2855 CONSTRUCTOR.
2857 Note that apart from value-initialization (when VALUE_INIT is true),
2858 this is only intended to support value-initialization and the
2859 initializations done by defaulted constructors for classes with
2860 non-static data members of array type. In this case, VEC_INIT_EXPR_INIT
2861 will either be NULL_TREE for the default constructor, or a COMPONENT_REF
2862 for the copy/move constructor. */
2864 static tree
2865 cxx_eval_vec_init_1 (const constexpr_ctx *ctx, tree atype, tree init,
2866 bool value_init, bool lval,
2867 bool *non_constant_p, bool *overflow_p)
2869 tree elttype = TREE_TYPE (atype);
2870 unsigned HOST_WIDE_INT max = tree_to_uhwi (array_type_nelts_top (atype));
2871 verify_ctor_sanity (ctx, atype);
2872 vec<constructor_elt, va_gc> **p = &CONSTRUCTOR_ELTS (ctx->ctor);
2873 vec_alloc (*p, max + 1);
2874 bool pre_init = false;
2875 unsigned HOST_WIDE_INT i;
2877 /* For the default constructor, build up a call to the default
2878 constructor of the element type. We only need to handle class types
2879 here, as for a constructor to be constexpr, all members must be
2880 initialized, which for a defaulted default constructor means they must
2881 be of a class type with a constexpr default constructor. */
2882 if (TREE_CODE (elttype) == ARRAY_TYPE)
2883 /* We only do this at the lowest level. */;
2884 else if (value_init)
2886 init = build_value_init (elttype, tf_warning_or_error);
2887 pre_init = true;
2889 else if (!init)
2891 vec<tree, va_gc> *argvec = make_tree_vector ();
2892 init = build_special_member_call (NULL_TREE, complete_ctor_identifier,
2893 &argvec, elttype, LOOKUP_NORMAL,
2894 tf_warning_or_error);
2895 release_tree_vector (argvec);
2896 init = build_aggr_init_expr (TREE_TYPE (init), init);
2897 pre_init = true;
2900 for (i = 0; i < max; ++i)
2902 tree idx = build_int_cst (size_type_node, i);
2903 tree eltinit;
2904 bool reuse = false;
2905 constexpr_ctx new_ctx;
2906 init_subob_ctx (ctx, new_ctx, idx, pre_init ? init : elttype);
2907 if (new_ctx.ctor != ctx->ctor)
2908 CONSTRUCTOR_APPEND_ELT (*p, idx, new_ctx.ctor);
2909 if (TREE_CODE (elttype) == ARRAY_TYPE)
2911 /* A multidimensional array; recurse. */
2912 if (value_init || init == NULL_TREE)
2914 eltinit = NULL_TREE;
2915 reuse = i == 0;
2917 else
2918 eltinit = cp_build_array_ref (input_location, init, idx,
2919 tf_warning_or_error);
2920 eltinit = cxx_eval_vec_init_1 (&new_ctx, elttype, eltinit, value_init,
2921 lval,
2922 non_constant_p, overflow_p);
2924 else if (pre_init)
2926 /* Initializing an element using value or default initialization
2927 we just pre-built above. */
2928 eltinit = cxx_eval_constant_expression (&new_ctx, init, lval,
2929 non_constant_p, overflow_p);
2930 reuse = i == 0;
2932 else
2934 /* Copying an element. */
2935 gcc_assert (same_type_ignoring_top_level_qualifiers_p
2936 (atype, TREE_TYPE (init)));
2937 eltinit = cp_build_array_ref (input_location, init, idx,
2938 tf_warning_or_error);
2939 if (!lvalue_p (init))
2940 eltinit = move (eltinit);
2941 eltinit = force_rvalue (eltinit, tf_warning_or_error);
2942 eltinit = (cxx_eval_constant_expression
2943 (&new_ctx, eltinit, lval,
2944 non_constant_p, overflow_p));
2946 if (*non_constant_p && !ctx->quiet)
2947 break;
2948 if (new_ctx.ctor != ctx->ctor)
2950 /* We appended this element above; update the value. */
2951 gcc_assert ((*p)->last().index == idx);
2952 (*p)->last().value = eltinit;
2954 else
2955 CONSTRUCTOR_APPEND_ELT (*p, idx, eltinit);
2956 /* Reuse the result of cxx_eval_constant_expression call
2957 from the first iteration to all others if it is a constant
2958 initializer that doesn't require relocations. */
2959 if (reuse
2960 && max > 1
2961 && (initializer_constant_valid_p (eltinit, TREE_TYPE (eltinit))
2962 == null_pointer_node))
2964 if (new_ctx.ctor != ctx->ctor)
2965 eltinit = new_ctx.ctor;
2966 for (i = 1; i < max; ++i)
2968 idx = build_int_cst (size_type_node, i);
2969 CONSTRUCTOR_APPEND_ELT (*p, idx, unshare_constructor (eltinit));
2971 break;
2975 if (!*non_constant_p)
2977 init = ctx->ctor;
2978 CONSTRUCTOR_NO_IMPLICIT_ZERO (init) = false;
2980 return init;
2983 static tree
2984 cxx_eval_vec_init (const constexpr_ctx *ctx, tree t,
2985 bool lval,
2986 bool *non_constant_p, bool *overflow_p)
2988 tree atype = TREE_TYPE (t);
2989 tree init = VEC_INIT_EXPR_INIT (t);
2990 tree r = cxx_eval_vec_init_1 (ctx, atype, init,
2991 VEC_INIT_EXPR_VALUE_INIT (t),
2992 lval, non_constant_p, overflow_p);
2993 if (*non_constant_p)
2994 return t;
2995 else
2996 return r;
2999 /* A less strict version of fold_indirect_ref_1, which requires cv-quals to
3000 match. We want to be less strict for simple *& folding; if we have a
3001 non-const temporary that we access through a const pointer, that should
3002 work. We handle this here rather than change fold_indirect_ref_1
3003 because we're dealing with things like ADDR_EXPR of INTEGER_CST which
3004 don't really make sense outside of constant expression evaluation. Also
3005 we want to allow folding to COMPONENT_REF, which could cause trouble
3006 with TBAA in fold_indirect_ref_1.
3008 Try to keep this function synced with fold_indirect_ref_1. */
3010 static tree
3011 cxx_fold_indirect_ref (location_t loc, tree type, tree op0, bool *empty_base)
3013 tree sub, subtype;
3015 sub = op0;
3016 STRIP_NOPS (sub);
3017 subtype = TREE_TYPE (sub);
3018 if (!POINTER_TYPE_P (subtype))
3019 return NULL_TREE;
3021 if (TREE_CODE (sub) == ADDR_EXPR)
3023 tree op = TREE_OPERAND (sub, 0);
3024 tree optype = TREE_TYPE (op);
3026 /* *&CONST_DECL -> to the value of the const decl. */
3027 if (TREE_CODE (op) == CONST_DECL)
3028 return DECL_INITIAL (op);
3029 /* *&p => p; make sure to handle *&"str"[cst] here. */
3030 if (same_type_ignoring_top_level_qualifiers_p (optype, type)
3031 /* Also handle the case where the desired type is an array of unknown
3032 bounds because the variable has had its bounds deduced since the
3033 ADDR_EXPR was created. */
3034 || (TREE_CODE (type) == ARRAY_TYPE
3035 && TREE_CODE (optype) == ARRAY_TYPE
3036 && TYPE_DOMAIN (type) == NULL_TREE
3037 && same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (optype),
3038 TREE_TYPE (type))))
3040 tree fop = fold_read_from_constant_string (op);
3041 if (fop)
3042 return fop;
3043 else
3044 return op;
3046 /* *(foo *)&fooarray => fooarray[0] */
3047 else if (TREE_CODE (optype) == ARRAY_TYPE
3048 && (same_type_ignoring_top_level_qualifiers_p
3049 (type, TREE_TYPE (optype))))
3051 tree type_domain = TYPE_DOMAIN (optype);
3052 tree min_val = size_zero_node;
3053 if (type_domain && TYPE_MIN_VALUE (type_domain))
3054 min_val = TYPE_MIN_VALUE (type_domain);
3055 return build4_loc (loc, ARRAY_REF, type, op, min_val,
3056 NULL_TREE, NULL_TREE);
3058 /* *(foo *)&complexfoo => __real__ complexfoo */
3059 else if (TREE_CODE (optype) == COMPLEX_TYPE
3060 && (same_type_ignoring_top_level_qualifiers_p
3061 (type, TREE_TYPE (optype))))
3062 return fold_build1_loc (loc, REALPART_EXPR, type, op);
3063 /* *(foo *)&vectorfoo => BIT_FIELD_REF<vectorfoo,...> */
3064 else if (VECTOR_TYPE_P (optype)
3065 && (same_type_ignoring_top_level_qualifiers_p
3066 (type, TREE_TYPE (optype))))
3068 tree part_width = TYPE_SIZE (type);
3069 tree index = bitsize_int (0);
3070 return fold_build3_loc (loc, BIT_FIELD_REF, type, op, part_width, index);
3072 /* Also handle conversion to an empty base class, which
3073 is represented with a NOP_EXPR. */
3074 else if (is_empty_class (type)
3075 && CLASS_TYPE_P (optype)
3076 && DERIVED_FROM_P (type, optype))
3078 *empty_base = true;
3079 return op;
3081 /* *(foo *)&struct_with_foo_field => COMPONENT_REF */
3082 else if (RECORD_OR_UNION_TYPE_P (optype))
3084 tree field = TYPE_FIELDS (optype);
3085 for (; field; field = DECL_CHAIN (field))
3086 if (TREE_CODE (field) == FIELD_DECL
3087 && TREE_TYPE (field) != error_mark_node
3088 && integer_zerop (byte_position (field))
3089 && (same_type_ignoring_top_level_qualifiers_p
3090 (TREE_TYPE (field), type)))
3091 return fold_build3 (COMPONENT_REF, type, op, field, NULL_TREE);
3094 else if (TREE_CODE (sub) == POINTER_PLUS_EXPR
3095 && TREE_CODE (TREE_OPERAND (sub, 1)) == INTEGER_CST)
3097 tree op00 = TREE_OPERAND (sub, 0);
3098 tree op01 = TREE_OPERAND (sub, 1);
3100 STRIP_NOPS (op00);
3101 if (TREE_CODE (op00) == ADDR_EXPR)
3103 tree op00type;
3104 op00 = TREE_OPERAND (op00, 0);
3105 op00type = TREE_TYPE (op00);
3107 /* ((foo*)&vectorfoo)[1] => BIT_FIELD_REF<vectorfoo,...> */
3108 if (VECTOR_TYPE_P (op00type)
3109 && (same_type_ignoring_top_level_qualifiers_p
3110 (type, TREE_TYPE (op00type))))
3112 HOST_WIDE_INT offset = tree_to_shwi (op01);
3113 tree part_width = TYPE_SIZE (type);
3114 unsigned HOST_WIDE_INT part_widthi = tree_to_shwi (part_width)/BITS_PER_UNIT;
3115 unsigned HOST_WIDE_INT indexi = offset * BITS_PER_UNIT;
3116 tree index = bitsize_int (indexi);
3118 if (offset / part_widthi < TYPE_VECTOR_SUBPARTS (op00type))
3119 return fold_build3_loc (loc,
3120 BIT_FIELD_REF, type, op00,
3121 part_width, index);
3124 /* ((foo*)&complexfoo)[1] => __imag__ complexfoo */
3125 else if (TREE_CODE (op00type) == COMPLEX_TYPE
3126 && (same_type_ignoring_top_level_qualifiers_p
3127 (type, TREE_TYPE (op00type))))
3129 tree size = TYPE_SIZE_UNIT (type);
3130 if (tree_int_cst_equal (size, op01))
3131 return fold_build1_loc (loc, IMAGPART_EXPR, type, op00);
3133 /* ((foo *)&fooarray)[1] => fooarray[1] */
3134 else if (TREE_CODE (op00type) == ARRAY_TYPE
3135 && (same_type_ignoring_top_level_qualifiers_p
3136 (type, TREE_TYPE (op00type))))
3138 tree type_domain = TYPE_DOMAIN (op00type);
3139 tree min_val = size_zero_node;
3140 if (type_domain && TYPE_MIN_VALUE (type_domain))
3141 min_val = TYPE_MIN_VALUE (type_domain);
3142 op01 = size_binop_loc (loc, EXACT_DIV_EXPR, op01,
3143 TYPE_SIZE_UNIT (type));
3144 op01 = size_binop_loc (loc, PLUS_EXPR, op01, min_val);
3145 return build4_loc (loc, ARRAY_REF, type, op00, op01,
3146 NULL_TREE, NULL_TREE);
3148 /* Also handle conversion to an empty base class, which
3149 is represented with a NOP_EXPR. */
3150 else if (is_empty_class (type)
3151 && CLASS_TYPE_P (op00type)
3152 && DERIVED_FROM_P (type, op00type))
3154 *empty_base = true;
3155 return op00;
3157 /* ((foo *)&struct_with_foo_field)[1] => COMPONENT_REF */
3158 else if (RECORD_OR_UNION_TYPE_P (op00type))
3160 tree field = TYPE_FIELDS (op00type);
3161 for (; field; field = DECL_CHAIN (field))
3162 if (TREE_CODE (field) == FIELD_DECL
3163 && TREE_TYPE (field) != error_mark_node
3164 && tree_int_cst_equal (byte_position (field), op01)
3165 && (same_type_ignoring_top_level_qualifiers_p
3166 (TREE_TYPE (field), type)))
3167 return fold_build3 (COMPONENT_REF, type, op00,
3168 field, NULL_TREE);
3172 /* *(foo *)fooarrptr => (*fooarrptr)[0] */
3173 else if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
3174 && (same_type_ignoring_top_level_qualifiers_p
3175 (type, TREE_TYPE (TREE_TYPE (subtype)))))
3177 tree type_domain;
3178 tree min_val = size_zero_node;
3179 tree newsub = cxx_fold_indirect_ref (loc, TREE_TYPE (subtype), sub, NULL);
3180 if (newsub)
3181 sub = newsub;
3182 else
3183 sub = build1_loc (loc, INDIRECT_REF, TREE_TYPE (subtype), sub);
3184 type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
3185 if (type_domain && TYPE_MIN_VALUE (type_domain))
3186 min_val = TYPE_MIN_VALUE (type_domain);
3187 return build4_loc (loc, ARRAY_REF, type, sub, min_val, NULL_TREE,
3188 NULL_TREE);
3191 return NULL_TREE;
3194 static tree
3195 cxx_eval_indirect_ref (const constexpr_ctx *ctx, tree t,
3196 bool lval,
3197 bool *non_constant_p, bool *overflow_p)
3199 tree orig_op0 = TREE_OPERAND (t, 0);
3200 bool empty_base = false;
3202 /* We can handle a MEM_REF like an INDIRECT_REF, if MEM_REF's second
3203 operand is an integer-zero. Otherwise reject the MEM_REF for now. */
3205 if (TREE_CODE (t) == MEM_REF
3206 && (!TREE_OPERAND (t, 1) || !integer_zerop (TREE_OPERAND (t, 1))))
3208 gcc_assert (ctx->quiet);
3209 *non_constant_p = true;
3210 return t;
3213 /* First try to simplify it directly. */
3214 tree r = cxx_fold_indirect_ref (EXPR_LOCATION (t), TREE_TYPE (t), orig_op0,
3215 &empty_base);
3216 if (!r)
3218 /* If that didn't work, evaluate the operand first. */
3219 tree op0 = cxx_eval_constant_expression (ctx, orig_op0,
3220 /*lval*/false, non_constant_p,
3221 overflow_p);
3222 /* Don't VERIFY_CONSTANT here. */
3223 if (*non_constant_p)
3224 return t;
3226 if (!lval && integer_zerop (op0))
3228 if (!ctx->quiet)
3229 error ("dereferencing a null pointer");
3230 *non_constant_p = true;
3231 return t;
3234 r = cxx_fold_indirect_ref (EXPR_LOCATION (t), TREE_TYPE (t), op0,
3235 &empty_base);
3236 if (r == NULL_TREE)
3238 /* We couldn't fold to a constant value. Make sure it's not
3239 something we should have been able to fold. */
3240 tree sub = op0;
3241 STRIP_NOPS (sub);
3242 if (TREE_CODE (sub) == ADDR_EXPR)
3244 gcc_assert (!same_type_ignoring_top_level_qualifiers_p
3245 (TREE_TYPE (TREE_TYPE (sub)), TREE_TYPE (t)));
3246 /* DR 1188 says we don't have to deal with this. */
3247 if (!ctx->quiet)
3248 error ("accessing value of %qE through a %qT glvalue in a "
3249 "constant expression", build_fold_indirect_ref (sub),
3250 TREE_TYPE (t));
3251 *non_constant_p = true;
3252 return t;
3255 if (lval && op0 != orig_op0)
3256 return build1 (INDIRECT_REF, TREE_TYPE (t), op0);
3257 if (!lval)
3258 VERIFY_CONSTANT (t);
3259 return t;
3263 r = cxx_eval_constant_expression (ctx, r,
3264 lval, non_constant_p, overflow_p);
3265 if (*non_constant_p)
3266 return t;
3268 /* If we're pulling out the value of an empty base, just return an empty
3269 CONSTRUCTOR. */
3270 if (empty_base && !lval)
3272 r = build_constructor (TREE_TYPE (t), NULL);
3273 TREE_CONSTANT (r) = true;
3276 return r;
3279 /* Complain about R, a VAR_DECL, not being usable in a constant expression.
3280 Shared between potential_constant_expression and
3281 cxx_eval_constant_expression. */
3283 static void
3284 non_const_var_error (tree r)
3286 tree type = TREE_TYPE (r);
3287 error ("the value of %qD is not usable in a constant "
3288 "expression", r);
3289 /* Avoid error cascade. */
3290 if (DECL_INITIAL (r) == error_mark_node)
3291 return;
3292 if (DECL_DECLARED_CONSTEXPR_P (r))
3293 inform (DECL_SOURCE_LOCATION (r),
3294 "%qD used in its own initializer", r);
3295 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
3297 if (!CP_TYPE_CONST_P (type))
3298 inform (DECL_SOURCE_LOCATION (r),
3299 "%q#D is not const", r);
3300 else if (CP_TYPE_VOLATILE_P (type))
3301 inform (DECL_SOURCE_LOCATION (r),
3302 "%q#D is volatile", r);
3303 else if (!DECL_INITIAL (r)
3304 || !TREE_CONSTANT (DECL_INITIAL (r))
3305 || !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r))
3306 inform (DECL_SOURCE_LOCATION (r),
3307 "%qD was not initialized with a constant "
3308 "expression", r);
3309 else
3310 gcc_unreachable ();
3312 else if (TREE_CODE (type) == REFERENCE_TYPE)
3313 inform (DECL_SOURCE_LOCATION (r),
3314 "%qD was not initialized with a constant "
3315 "expression", r);
3316 else
3318 if (cxx_dialect >= cxx11 && !DECL_DECLARED_CONSTEXPR_P (r))
3319 inform (DECL_SOURCE_LOCATION (r),
3320 "%qD was not declared %<constexpr%>", r);
3321 else
3322 inform (DECL_SOURCE_LOCATION (r),
3323 "%qD does not have integral or enumeration type",
3328 /* Subroutine of cxx_eval_constant_expression.
3329 Like cxx_eval_unary_expression, except for trinary expressions. */
3331 static tree
3332 cxx_eval_trinary_expression (const constexpr_ctx *ctx, tree t,
3333 bool lval,
3334 bool *non_constant_p, bool *overflow_p)
3336 int i;
3337 tree args[3];
3338 tree val;
3340 for (i = 0; i < 3; i++)
3342 args[i] = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, i),
3343 lval,
3344 non_constant_p, overflow_p);
3345 VERIFY_CONSTANT (args[i]);
3348 val = fold_ternary_loc (EXPR_LOCATION (t), TREE_CODE (t), TREE_TYPE (t),
3349 args[0], args[1], args[2]);
3350 if (val == NULL_TREE)
3351 return t;
3352 VERIFY_CONSTANT (val);
3353 return val;
3356 /* True if T was declared in a function declared to be constexpr, and
3357 therefore potentially constant in C++14. */
3359 bool
3360 var_in_constexpr_fn (tree t)
3362 tree ctx = DECL_CONTEXT (t);
3363 return (ctx && TREE_CODE (ctx) == FUNCTION_DECL
3364 && DECL_DECLARED_CONSTEXPR_P (ctx));
3367 /* True if T was declared in a function that might be constexpr: either a
3368 function that was declared constexpr, or a C++17 lambda op(). */
3370 bool
3371 var_in_maybe_constexpr_fn (tree t)
3373 if (cxx_dialect >= cxx17
3374 && DECL_FUNCTION_SCOPE_P (t)
3375 && LAMBDA_FUNCTION_P (DECL_CONTEXT (t)))
3376 return true;
3377 return var_in_constexpr_fn (t);
3380 /* We're assigning INIT to TARGET. In do_build_copy_constructor and
3381 build_over_call we implement trivial copy of a class with tail padding using
3382 assignment of character arrays, which is valid in normal code, but not in
3383 constexpr evaluation. We don't need to worry about clobbering tail padding
3384 in constexpr evaluation, so strip the type punning. */
3386 static void
3387 maybe_simplify_trivial_copy (tree &target, tree &init)
3389 if (TREE_CODE (target) == MEM_REF
3390 && TREE_CODE (init) == MEM_REF
3391 && TREE_TYPE (target) == TREE_TYPE (init)
3392 && TREE_CODE (TREE_TYPE (target)) == ARRAY_TYPE
3393 && TREE_TYPE (TREE_TYPE (target)) == unsigned_char_type_node)
3395 target = build_fold_indirect_ref (TREE_OPERAND (target, 0));
3396 init = build_fold_indirect_ref (TREE_OPERAND (init, 0));
3400 /* Evaluate an INIT_EXPR or MODIFY_EXPR. */
3402 static tree
3403 cxx_eval_store_expression (const constexpr_ctx *ctx, tree t,
3404 bool lval,
3405 bool *non_constant_p, bool *overflow_p)
3407 constexpr_ctx new_ctx = *ctx;
3409 tree init = TREE_OPERAND (t, 1);
3410 if (TREE_CLOBBER_P (init))
3411 /* Just ignore clobbers. */
3412 return void_node;
3414 /* First we figure out where we're storing to. */
3415 tree target = TREE_OPERAND (t, 0);
3417 maybe_simplify_trivial_copy (target, init);
3419 tree type = TREE_TYPE (target);
3420 target = cxx_eval_constant_expression (ctx, target,
3421 true,
3422 non_constant_p, overflow_p);
3423 if (*non_constant_p)
3424 return t;
3426 /* cxx_eval_array_reference for lval = true allows references one past
3427 end of array, because it does not know if it is just taking address
3428 (which is valid), or actual dereference. Here we know it is
3429 a dereference, so diagnose it here. */
3430 for (tree probe = target; probe; )
3432 switch (TREE_CODE (probe))
3434 case ARRAY_REF:
3435 tree nelts, ary;
3436 ary = TREE_OPERAND (probe, 0);
3437 if (TREE_CODE (TREE_TYPE (ary)) == ARRAY_TYPE)
3438 nelts = array_type_nelts_top (TREE_TYPE (ary));
3439 else if (VECTOR_TYPE_P (TREE_TYPE (ary)))
3440 nelts = size_int (TYPE_VECTOR_SUBPARTS (TREE_TYPE (ary)));
3441 else
3442 gcc_unreachable ();
3443 nelts = cxx_eval_constant_expression (ctx, nelts, false,
3444 non_constant_p, overflow_p);
3445 VERIFY_CONSTANT (nelts);
3446 gcc_assert (TREE_CODE (nelts) == INTEGER_CST
3447 && TREE_CODE (TREE_OPERAND (probe, 1)) == INTEGER_CST);
3448 if (wi::to_widest (TREE_OPERAND (probe, 1)) == wi::to_widest (nelts))
3450 diag_array_subscript (ctx, ary, TREE_OPERAND (probe, 1));
3451 *non_constant_p = true;
3452 return t;
3454 /* FALLTHRU */
3456 case BIT_FIELD_REF:
3457 case COMPONENT_REF:
3458 probe = TREE_OPERAND (probe, 0);
3459 continue;
3461 default:
3462 probe = NULL_TREE;
3463 continue;
3467 if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (target), type))
3469 /* For initialization of an empty base, the original target will be
3470 *(base*)this, which the above evaluation resolves to the object
3471 argument, which has the derived type rather than the base type. In
3472 this situation, just evaluate the initializer and return, since
3473 there's no actual data to store. */
3474 gcc_assert (is_empty_class (type));
3475 return cxx_eval_constant_expression (ctx, init, false,
3476 non_constant_p, overflow_p);
3479 /* And then find the underlying variable. */
3480 vec<tree,va_gc> *refs = make_tree_vector();
3481 tree object = NULL_TREE;
3482 for (tree probe = target; object == NULL_TREE; )
3484 switch (TREE_CODE (probe))
3486 case BIT_FIELD_REF:
3487 case COMPONENT_REF:
3488 case ARRAY_REF:
3489 vec_safe_push (refs, TREE_OPERAND (probe, 1));
3490 vec_safe_push (refs, TREE_TYPE (probe));
3491 probe = TREE_OPERAND (probe, 0);
3492 break;
3494 default:
3495 object = probe;
3499 /* And then find/build up our initializer for the path to the subobject
3500 we're initializing. */
3501 tree *valp;
3502 if (object == ctx->object && VAR_P (object)
3503 && DECL_NAME (object) && ctx->call == NULL)
3504 /* The variable we're building up an aggregate initializer for is outside
3505 the constant-expression, so don't evaluate the store. We check
3506 DECL_NAME to handle TARGET_EXPR temporaries, which are fair game. */
3507 valp = NULL;
3508 else if (DECL_P (object))
3509 valp = ctx->values->get (object);
3510 else
3511 valp = NULL;
3512 if (!valp)
3514 /* A constant-expression cannot modify objects from outside the
3515 constant-expression. */
3516 if (!ctx->quiet)
3517 error ("modification of %qE is not a constant expression", object);
3518 *non_constant_p = true;
3519 return t;
3521 type = TREE_TYPE (object);
3522 bool no_zero_init = true;
3524 vec<tree,va_gc> *ctors = make_tree_vector ();
3525 while (!refs->is_empty())
3527 if (*valp == NULL_TREE)
3529 *valp = build_constructor (type, NULL);
3530 CONSTRUCTOR_NO_IMPLICIT_ZERO (*valp) = no_zero_init;
3532 else if (TREE_CODE (*valp) == STRING_CST)
3534 /* An array was initialized with a string constant, and now
3535 we're writing into one of its elements. Explode the
3536 single initialization into a set of element
3537 initializations. */
3538 gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
3540 tree string = *valp;
3541 tree elt_type = TREE_TYPE (type);
3542 unsigned chars_per_elt = (TYPE_PRECISION (elt_type)
3543 / TYPE_PRECISION (char_type_node));
3544 unsigned num_elts = TREE_STRING_LENGTH (string) / chars_per_elt;
3545 tree ary_ctor = build_constructor (type, NULL);
3547 vec_safe_reserve (CONSTRUCTOR_ELTS (ary_ctor), num_elts);
3548 for (unsigned ix = 0; ix != num_elts; ix++)
3550 constructor_elt elt =
3552 build_int_cst (size_type_node, ix),
3553 extract_string_elt (string, chars_per_elt, ix)
3555 CONSTRUCTOR_ELTS (ary_ctor)->quick_push (elt);
3558 *valp = ary_ctor;
3561 /* If the value of object is already zero-initialized, any new ctors for
3562 subobjects will also be zero-initialized. */
3563 no_zero_init = CONSTRUCTOR_NO_IMPLICIT_ZERO (*valp);
3565 vec_safe_push (ctors, *valp);
3567 enum tree_code code = TREE_CODE (type);
3568 type = refs->pop();
3569 tree index = refs->pop();
3571 constructor_elt *cep = NULL;
3572 if (code == ARRAY_TYPE)
3574 HOST_WIDE_INT i
3575 = find_array_ctor_elt (*valp, index, /*insert*/true);
3576 gcc_assert (i >= 0);
3577 cep = CONSTRUCTOR_ELT (*valp, i);
3578 gcc_assert (TREE_CODE (cep->index) != RANGE_EXPR);
3580 else
3582 gcc_assert (TREE_CODE (index) == FIELD_DECL);
3584 /* We must keep the CONSTRUCTOR's ELTS in FIELD order.
3585 Usually we meet initializers in that order, but it is
3586 possible for base types to be placed not in program
3587 order. */
3588 tree fields = TYPE_FIELDS (DECL_CONTEXT (index));
3589 unsigned HOST_WIDE_INT idx;
3591 if (code == UNION_TYPE && CONSTRUCTOR_NELTS (*valp)
3592 && CONSTRUCTOR_ELT (*valp, 0)->index != index)
3593 /* Changing active member. */
3594 vec_safe_truncate (CONSTRUCTOR_ELTS (*valp), 0);
3596 for (idx = 0;
3597 vec_safe_iterate (CONSTRUCTOR_ELTS (*valp), idx, &cep);
3598 idx++, fields = DECL_CHAIN (fields))
3600 if (index == cep->index)
3601 goto found;
3603 /* The field we're initializing must be on the field
3604 list. Look to see if it is present before the
3605 field the current ELT initializes. */
3606 for (; fields != cep->index; fields = DECL_CHAIN (fields))
3607 if (index == fields)
3608 goto insert;
3611 /* We fell off the end of the CONSTRUCTOR, so insert a new
3612 entry at the end. */
3613 insert:
3615 constructor_elt ce = { index, NULL_TREE };
3617 vec_safe_insert (CONSTRUCTOR_ELTS (*valp), idx, ce);
3618 cep = CONSTRUCTOR_ELT (*valp, idx);
3620 found:;
3622 valp = &cep->value;
3624 release_tree_vector (refs);
3626 if (AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type))
3628 /* Create a new CONSTRUCTOR in case evaluation of the initializer
3629 wants to modify it. */
3630 if (*valp == NULL_TREE)
3632 *valp = build_constructor (type, NULL);
3633 CONSTRUCTOR_NO_IMPLICIT_ZERO (*valp) = no_zero_init;
3635 else if (TREE_CODE (*valp) == PTRMEM_CST)
3636 *valp = cplus_expand_constant (*valp);
3637 new_ctx.ctor = *valp;
3638 new_ctx.object = target;
3641 init = cxx_eval_constant_expression (&new_ctx, init, false,
3642 non_constant_p, overflow_p);
3643 /* Don't share a CONSTRUCTOR that might be changed later. */
3644 init = unshare_constructor (init);
3645 if (target == object)
3646 /* The hash table might have moved since the get earlier. */
3647 valp = ctx->values->get (object);
3649 if (TREE_CODE (init) == CONSTRUCTOR)
3651 /* An outer ctx->ctor might be pointing to *valp, so replace
3652 its contents. */
3653 CONSTRUCTOR_ELTS (*valp) = CONSTRUCTOR_ELTS (init);
3654 TREE_CONSTANT (*valp) = TREE_CONSTANT (init);
3655 TREE_SIDE_EFFECTS (*valp) = TREE_SIDE_EFFECTS (init);
3656 CONSTRUCTOR_NO_IMPLICIT_ZERO (*valp)
3657 = CONSTRUCTOR_NO_IMPLICIT_ZERO (init);
3659 else
3660 *valp = init;
3662 /* Update TREE_CONSTANT and TREE_SIDE_EFFECTS on enclosing
3663 CONSTRUCTORs, if any. */
3664 tree elt;
3665 unsigned i;
3666 bool c = TREE_CONSTANT (init);
3667 bool s = TREE_SIDE_EFFECTS (init);
3668 if (!c || s)
3669 FOR_EACH_VEC_SAFE_ELT (ctors, i, elt)
3671 if (!c)
3672 TREE_CONSTANT (elt) = false;
3673 if (s)
3674 TREE_SIDE_EFFECTS (elt) = true;
3676 release_tree_vector (ctors);
3678 if (*non_constant_p)
3679 return t;
3680 else if (lval)
3681 return target;
3682 else
3683 return init;
3686 /* Evaluate a ++ or -- expression. */
3688 static tree
3689 cxx_eval_increment_expression (const constexpr_ctx *ctx, tree t,
3690 bool lval,
3691 bool *non_constant_p, bool *overflow_p)
3693 enum tree_code code = TREE_CODE (t);
3694 tree type = TREE_TYPE (t);
3695 tree op = TREE_OPERAND (t, 0);
3696 tree offset = TREE_OPERAND (t, 1);
3697 gcc_assert (TREE_CONSTANT (offset));
3699 /* The operand as an lvalue. */
3700 op = cxx_eval_constant_expression (ctx, op, true,
3701 non_constant_p, overflow_p);
3703 /* The operand as an rvalue. */
3704 tree val
3705 = cxx_eval_constant_expression (ctx, op, false,
3706 non_constant_p, overflow_p);
3707 /* Don't VERIFY_CONSTANT if this might be dealing with a pointer to
3708 a local array in a constexpr function. */
3709 bool ptr = POINTER_TYPE_P (TREE_TYPE (val));
3710 if (!ptr)
3711 VERIFY_CONSTANT (val);
3713 /* The modified value. */
3714 bool inc = (code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR);
3715 tree mod;
3716 if (POINTER_TYPE_P (type))
3718 /* The middle end requires pointers to use POINTER_PLUS_EXPR. */
3719 offset = convert_to_ptrofftype (offset);
3720 if (!inc)
3721 offset = fold_build1 (NEGATE_EXPR, TREE_TYPE (offset), offset);
3722 mod = fold_build2 (POINTER_PLUS_EXPR, type, val, offset);
3724 else
3725 mod = fold_build2 (inc ? PLUS_EXPR : MINUS_EXPR, type, val, offset);
3726 if (!ptr)
3727 VERIFY_CONSTANT (mod);
3729 /* Storing the modified value. */
3730 tree store = build2 (MODIFY_EXPR, type, op, mod);
3731 cxx_eval_constant_expression (ctx, store,
3732 true, non_constant_p, overflow_p);
3734 /* And the value of the expression. */
3735 if (code == PREINCREMENT_EXPR || code == PREDECREMENT_EXPR)
3737 /* Prefix ops are lvalues. */
3738 if (lval)
3739 return op;
3740 else
3741 /* But we optimize when the caller wants an rvalue. */
3742 return mod;
3744 else
3745 /* Postfix ops are rvalues. */
3746 return val;
3749 /* Predicates for the meaning of *jump_target. */
3751 static bool
3752 returns (tree *jump_target)
3754 return *jump_target
3755 && (TREE_CODE (*jump_target) == RETURN_EXPR
3756 || (TREE_CODE (*jump_target) == LABEL_DECL
3757 && LABEL_DECL_CDTOR (*jump_target)));
3760 static bool
3761 breaks (tree *jump_target)
3763 return *jump_target
3764 && ((TREE_CODE (*jump_target) == LABEL_DECL
3765 && LABEL_DECL_BREAK (*jump_target))
3766 || TREE_CODE (*jump_target) == EXIT_EXPR);
3769 static bool
3770 continues (tree *jump_target)
3772 return *jump_target
3773 && TREE_CODE (*jump_target) == LABEL_DECL
3774 && LABEL_DECL_CONTINUE (*jump_target);
3777 static bool
3778 switches (tree *jump_target)
3780 return *jump_target
3781 && TREE_CODE (*jump_target) == INTEGER_CST;
3784 /* Subroutine of cxx_eval_statement_list. Determine whether the statement
3785 STMT matches *jump_target. If we're looking for a case label and we see
3786 the default label, note it in ctx->css_state. */
3788 static bool
3789 label_matches (const constexpr_ctx *ctx, tree *jump_target, tree stmt)
3791 switch (TREE_CODE (*jump_target))
3793 case LABEL_DECL:
3794 if (TREE_CODE (stmt) == LABEL_EXPR
3795 && LABEL_EXPR_LABEL (stmt) == *jump_target)
3796 return true;
3797 break;
3799 case INTEGER_CST:
3800 if (TREE_CODE (stmt) == CASE_LABEL_EXPR)
3802 gcc_assert (ctx->css_state != NULL);
3803 if (!CASE_LOW (stmt))
3805 /* default: should appear just once in a SWITCH_EXPR
3806 body (excluding nested SWITCH_EXPR). */
3807 gcc_assert (*ctx->css_state != css_default_seen);
3808 /* When evaluating SWITCH_EXPR body for the second time,
3809 return true for the default: label. */
3810 if (*ctx->css_state == css_default_processing)
3811 return true;
3812 *ctx->css_state = css_default_seen;
3814 else if (CASE_HIGH (stmt))
3816 if (tree_int_cst_le (CASE_LOW (stmt), *jump_target)
3817 && tree_int_cst_le (*jump_target, CASE_HIGH (stmt)))
3818 return true;
3820 else if (tree_int_cst_equal (*jump_target, CASE_LOW (stmt)))
3821 return true;
3823 break;
3825 default:
3826 gcc_unreachable ();
3828 return false;
3831 /* Evaluate a STATEMENT_LIST for side-effects. Handles various jump
3832 semantics, for switch, break, continue, and return. */
3834 static tree
3835 cxx_eval_statement_list (const constexpr_ctx *ctx, tree t,
3836 bool *non_constant_p, bool *overflow_p,
3837 tree *jump_target)
3839 tree_stmt_iterator i;
3840 tree local_target;
3841 /* In a statement-expression we want to return the last value.
3842 For empty statement expression return void_node. */
3843 tree r = void_node;
3844 if (!jump_target)
3846 local_target = NULL_TREE;
3847 jump_target = &local_target;
3849 for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
3851 tree stmt = tsi_stmt (i);
3852 r = cxx_eval_constant_expression (ctx, stmt, false,
3853 non_constant_p, overflow_p,
3854 jump_target);
3855 if (*non_constant_p)
3856 break;
3857 if (returns (jump_target) || breaks (jump_target))
3858 break;
3860 /* Make sure we don't use the "result" of a debug-only marker. That
3861 would be wrong. We should be using the result of the previous
3862 statement, or NULL if there isn't one. In practice, this should
3863 never happen: the statement after the marker should override the
3864 result of the marker, so its value shouldn't survive in R. Now,
3865 should that ever change, we'll need some fixing here to stop
3866 markers from modifying the generated executable code. */
3867 gcc_checking_assert (!r || TREE_CODE (r) != DEBUG_BEGIN_STMT);
3868 return r;
3871 /* Evaluate a LOOP_EXPR for side-effects. Handles break and return
3872 semantics; continue semantics are covered by cxx_eval_statement_list. */
3874 static tree
3875 cxx_eval_loop_expr (const constexpr_ctx *ctx, tree t,
3876 bool *non_constant_p, bool *overflow_p,
3877 tree *jump_target)
3879 constexpr_ctx new_ctx = *ctx;
3881 tree body = TREE_OPERAND (t, 0);
3882 int count = 0;
3885 hash_set<tree> save_exprs;
3886 new_ctx.save_exprs = &save_exprs;
3888 cxx_eval_constant_expression (&new_ctx, body, /*lval*/false,
3889 non_constant_p, overflow_p, jump_target);
3891 /* Forget saved values of SAVE_EXPRs. */
3892 for (hash_set<tree>::iterator iter = save_exprs.begin();
3893 iter != save_exprs.end(); ++iter)
3894 new_ctx.values->remove (*iter);
3895 if (++count >= constexpr_loop_limit)
3897 if (!ctx->quiet)
3898 error_at (EXPR_LOC_OR_LOC (t, input_location),
3899 "%<constexpr%> loop iteration count exceeds limit of %d "
3900 "(use -fconstexpr-loop-limit= to increase the limit)",
3901 constexpr_loop_limit);
3902 *non_constant_p = true;
3903 break;
3906 while (!returns (jump_target)
3907 && !breaks (jump_target)
3908 && !switches (jump_target)
3909 && !*non_constant_p);
3911 if (breaks (jump_target))
3912 *jump_target = NULL_TREE;
3914 return NULL_TREE;
3917 /* Evaluate a SWITCH_EXPR for side-effects. Handles switch and break jump
3918 semantics. */
3920 static tree
3921 cxx_eval_switch_expr (const constexpr_ctx *ctx, tree t,
3922 bool *non_constant_p, bool *overflow_p,
3923 tree *jump_target)
3925 tree cond = TREE_OPERAND (t, 0);
3926 cond = cxx_eval_constant_expression (ctx, cond, false,
3927 non_constant_p, overflow_p);
3928 VERIFY_CONSTANT (cond);
3929 *jump_target = cond;
3931 tree body = TREE_OPERAND (t, 1);
3932 constexpr_ctx new_ctx = *ctx;
3933 constexpr_switch_state css = css_default_not_seen;
3934 new_ctx.css_state = &css;
3935 cxx_eval_constant_expression (&new_ctx, body, false,
3936 non_constant_p, overflow_p, jump_target);
3937 if (switches (jump_target) && css == css_default_seen)
3939 /* If the SWITCH_EXPR body has default: label, process it once again,
3940 this time instructing label_matches to return true for default:
3941 label on switches (jump_target). */
3942 css = css_default_processing;
3943 cxx_eval_constant_expression (&new_ctx, body, false,
3944 non_constant_p, overflow_p, jump_target);
3946 if (breaks (jump_target) || switches (jump_target))
3947 *jump_target = NULL_TREE;
3948 return NULL_TREE;
3951 /* Find the object of TYPE under initialization in CTX. */
3953 static tree
3954 lookup_placeholder (const constexpr_ctx *ctx, bool lval, tree type)
3956 if (!ctx)
3957 return NULL_TREE;
3959 /* We could use ctx->object unconditionally, but using ctx->ctor when we
3960 can is a minor optimization. */
3961 if (!lval && ctx->ctor && same_type_p (TREE_TYPE (ctx->ctor), type))
3962 return ctx->ctor;
3964 if (!ctx->object)
3965 return NULL_TREE;
3967 /* Since an object cannot have a field of its own type, we can search outward
3968 from ctx->object to find the unique containing object of TYPE. */
3969 tree ob = ctx->object;
3970 while (ob)
3972 if (same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (ob), type))
3973 break;
3974 if (handled_component_p (ob))
3975 ob = TREE_OPERAND (ob, 0);
3976 else
3977 ob = NULL_TREE;
3980 return ob;
3983 /* Attempt to reduce the expression T to a constant value.
3984 On failure, issue diagnostic and return error_mark_node. */
3985 /* FIXME unify with c_fully_fold */
3986 /* FIXME overflow_p is too global */
3988 static tree
3989 cxx_eval_constant_expression (const constexpr_ctx *ctx, tree t,
3990 bool lval,
3991 bool *non_constant_p, bool *overflow_p,
3992 tree *jump_target)
3994 constexpr_ctx new_ctx;
3995 tree r = t;
3997 if (jump_target && *jump_target)
3999 /* If we are jumping, ignore all statements/expressions except those
4000 that could have LABEL_EXPR or CASE_LABEL_EXPR in their bodies. */
4001 switch (TREE_CODE (t))
4003 case BIND_EXPR:
4004 case STATEMENT_LIST:
4005 case LOOP_EXPR:
4006 case COND_EXPR:
4007 break;
4008 case LABEL_EXPR:
4009 case CASE_LABEL_EXPR:
4010 if (label_matches (ctx, jump_target, t))
4011 /* Found it. */
4012 *jump_target = NULL_TREE;
4013 return NULL_TREE;
4014 default:
4015 return NULL_TREE;
4018 if (t == error_mark_node)
4020 *non_constant_p = true;
4021 return t;
4023 if (CONSTANT_CLASS_P (t))
4025 if (TREE_OVERFLOW (t))
4027 if (!ctx->quiet)
4028 permerror (input_location, "overflow in constant expression");
4029 if (!flag_permissive || ctx->quiet)
4030 *overflow_p = true;
4033 if (TREE_CODE (t) == INTEGER_CST
4034 && TREE_CODE (TREE_TYPE (t)) == POINTER_TYPE
4035 && !integer_zerop (t))
4037 if (!ctx->quiet)
4038 error ("value %qE of type %qT is not a constant expression",
4039 t, TREE_TYPE (t));
4040 *non_constant_p = true;
4043 return t;
4046 tree_code tcode = TREE_CODE (t);
4047 switch (tcode)
4049 case RESULT_DECL:
4050 if (lval)
4051 return t;
4052 /* We ask for an rvalue for the RESULT_DECL when indirecting
4053 through an invisible reference, or in named return value
4054 optimization. */
4055 return (*ctx->values->get (t));
4057 case VAR_DECL:
4058 if (DECL_HAS_VALUE_EXPR_P (t))
4059 return cxx_eval_constant_expression (ctx, DECL_VALUE_EXPR (t),
4060 lval, non_constant_p, overflow_p);
4061 /* fall through */
4062 case CONST_DECL:
4063 /* We used to not check lval for CONST_DECL, but darwin.c uses
4064 CONST_DECL for aggregate constants. */
4065 if (lval)
4066 return t;
4067 if (COMPLETE_TYPE_P (TREE_TYPE (t))
4068 && is_really_empty_class (TREE_TYPE (t)))
4070 /* If the class is empty, we aren't actually loading anything. */
4071 r = build_constructor (TREE_TYPE (t), NULL);
4072 TREE_CONSTANT (r) = true;
4074 else if (ctx->strict)
4075 r = decl_really_constant_value (t);
4076 else
4077 r = decl_constant_value (t);
4078 if (TREE_CODE (r) == TARGET_EXPR
4079 && TREE_CODE (TARGET_EXPR_INITIAL (r)) == CONSTRUCTOR)
4080 r = TARGET_EXPR_INITIAL (r);
4081 if (VAR_P (r))
4082 if (tree *p = ctx->values->get (r))
4083 if (*p != NULL_TREE)
4084 r = *p;
4085 if (DECL_P (r))
4087 if (!ctx->quiet)
4088 non_const_var_error (r);
4089 *non_constant_p = true;
4091 break;
4093 case DEBUG_BEGIN_STMT:
4094 /* ??? It might be nice to retain this information somehow, so
4095 as to be able to step into a constexpr function call. */
4096 /* Fall through. */
4098 case FUNCTION_DECL:
4099 case TEMPLATE_DECL:
4100 case LABEL_DECL:
4101 case LABEL_EXPR:
4102 case CASE_LABEL_EXPR:
4103 case PREDICT_EXPR:
4104 return t;
4106 case PARM_DECL:
4107 if (lval && TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
4108 /* glvalue use. */;
4109 else if (tree *p = ctx->values->get (r))
4110 r = *p;
4111 else if (lval)
4112 /* Defer in case this is only used for its type. */;
4113 else if (TREE_CODE (TREE_TYPE (t)) == REFERENCE_TYPE)
4114 /* Defer, there's no lvalue->rvalue conversion. */;
4115 else if (COMPLETE_TYPE_P (TREE_TYPE (t))
4116 && is_really_empty_class (TREE_TYPE (t)))
4118 /* If the class is empty, we aren't actually loading anything. */
4119 r = build_constructor (TREE_TYPE (t), NULL);
4120 TREE_CONSTANT (r) = true;
4122 else
4124 if (!ctx->quiet)
4125 error ("%qE is not a constant expression", t);
4126 *non_constant_p = true;
4128 break;
4130 case CALL_EXPR:
4131 case AGGR_INIT_EXPR:
4132 r = cxx_eval_call_expression (ctx, t, lval,
4133 non_constant_p, overflow_p);
4134 break;
4136 case DECL_EXPR:
4138 r = DECL_EXPR_DECL (t);
4139 if (AGGREGATE_TYPE_P (TREE_TYPE (r))
4140 || VECTOR_TYPE_P (TREE_TYPE (r)))
4142 new_ctx = *ctx;
4143 new_ctx.object = r;
4144 new_ctx.ctor = build_constructor (TREE_TYPE (r), NULL);
4145 CONSTRUCTOR_NO_IMPLICIT_ZERO (new_ctx.ctor) = true;
4146 new_ctx.values->put (r, new_ctx.ctor);
4147 ctx = &new_ctx;
4150 if (tree init = DECL_INITIAL (r))
4152 init = cxx_eval_constant_expression (ctx, init,
4153 false,
4154 non_constant_p, overflow_p);
4155 /* Don't share a CONSTRUCTOR that might be changed. */
4156 init = unshare_constructor (init);
4157 ctx->values->put (r, init);
4159 else if (ctx == &new_ctx)
4160 /* We gave it a CONSTRUCTOR above. */;
4161 else
4162 ctx->values->put (r, NULL_TREE);
4164 break;
4166 case TARGET_EXPR:
4167 if (!literal_type_p (TREE_TYPE (t)))
4169 if (!ctx->quiet)
4171 error ("temporary of non-literal type %qT in a "
4172 "constant expression", TREE_TYPE (t));
4173 explain_non_literal_class (TREE_TYPE (t));
4175 *non_constant_p = true;
4176 break;
4178 if ((AGGREGATE_TYPE_P (TREE_TYPE (t)) || VECTOR_TYPE_P (TREE_TYPE (t))))
4180 /* We're being expanded without an explicit target, so start
4181 initializing a new object; expansion with an explicit target
4182 strips the TARGET_EXPR before we get here. */
4183 new_ctx = *ctx;
4184 new_ctx.ctor = build_constructor (TREE_TYPE (t), NULL);
4185 CONSTRUCTOR_NO_IMPLICIT_ZERO (new_ctx.ctor) = true;
4186 new_ctx.object = TARGET_EXPR_SLOT (t);
4187 ctx->values->put (new_ctx.object, new_ctx.ctor);
4188 ctx = &new_ctx;
4190 /* Pass false for 'lval' because this indicates
4191 initialization of a temporary. */
4192 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
4193 false,
4194 non_constant_p, overflow_p);
4195 if (!*non_constant_p)
4196 /* Adjust the type of the result to the type of the temporary. */
4197 r = adjust_temp_type (TREE_TYPE (t), r);
4198 if (lval)
4200 tree slot = TARGET_EXPR_SLOT (t);
4201 r = unshare_constructor (r);
4202 ctx->values->put (slot, r);
4203 return slot;
4205 break;
4207 case INIT_EXPR:
4208 case MODIFY_EXPR:
4209 gcc_assert (jump_target == NULL || *jump_target == NULL_TREE);
4210 r = cxx_eval_store_expression (ctx, t, lval,
4211 non_constant_p, overflow_p);
4212 break;
4214 case SCOPE_REF:
4215 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
4216 lval,
4217 non_constant_p, overflow_p);
4218 break;
4220 case RETURN_EXPR:
4221 if (TREE_OPERAND (t, 0) != NULL_TREE)
4222 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
4223 lval,
4224 non_constant_p, overflow_p);
4225 *jump_target = t;
4226 break;
4228 case SAVE_EXPR:
4229 /* Avoid evaluating a SAVE_EXPR more than once. */
4230 if (tree *p = ctx->values->get (t))
4231 r = *p;
4232 else
4234 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), false,
4235 non_constant_p, overflow_p);
4236 ctx->values->put (t, r);
4237 if (ctx->save_exprs)
4238 ctx->save_exprs->add (t);
4240 break;
4242 case NON_LVALUE_EXPR:
4243 case TRY_CATCH_EXPR:
4244 case TRY_BLOCK:
4245 case CLEANUP_POINT_EXPR:
4246 case MUST_NOT_THROW_EXPR:
4247 case EXPR_STMT:
4248 case EH_SPEC_BLOCK:
4249 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
4250 lval,
4251 non_constant_p, overflow_p,
4252 jump_target);
4253 break;
4255 case TRY_FINALLY_EXPR:
4256 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
4257 non_constant_p, overflow_p,
4258 jump_target);
4259 if (!*non_constant_p)
4260 /* Also evaluate the cleanup. */
4261 cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1), true,
4262 non_constant_p, overflow_p,
4263 jump_target);
4264 break;
4266 /* These differ from cxx_eval_unary_expression in that this doesn't
4267 check for a constant operand or result; an address can be
4268 constant without its operand being, and vice versa. */
4269 case MEM_REF:
4270 case INDIRECT_REF:
4271 r = cxx_eval_indirect_ref (ctx, t, lval,
4272 non_constant_p, overflow_p);
4273 break;
4275 case ADDR_EXPR:
4277 tree oldop = TREE_OPERAND (t, 0);
4278 tree op = cxx_eval_constant_expression (ctx, oldop,
4279 /*lval*/true,
4280 non_constant_p, overflow_p);
4281 /* Don't VERIFY_CONSTANT here. */
4282 if (*non_constant_p)
4283 return t;
4284 gcc_checking_assert (TREE_CODE (op) != CONSTRUCTOR);
4285 /* This function does more aggressive folding than fold itself. */
4286 r = build_fold_addr_expr_with_type (op, TREE_TYPE (t));
4287 if (TREE_CODE (r) == ADDR_EXPR && TREE_OPERAND (r, 0) == oldop)
4288 return t;
4289 break;
4292 case REALPART_EXPR:
4293 case IMAGPART_EXPR:
4294 if (lval)
4296 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
4297 non_constant_p, overflow_p);
4298 if (r == error_mark_node)
4300 else if (r == TREE_OPERAND (t, 0))
4301 r = t;
4302 else
4303 r = fold_build1 (TREE_CODE (t), TREE_TYPE (t), r);
4304 break;
4306 /* FALLTHRU */
4307 case CONJ_EXPR:
4308 case FIX_TRUNC_EXPR:
4309 case FLOAT_EXPR:
4310 case NEGATE_EXPR:
4311 case ABS_EXPR:
4312 case BIT_NOT_EXPR:
4313 case TRUTH_NOT_EXPR:
4314 case FIXED_CONVERT_EXPR:
4315 r = cxx_eval_unary_expression (ctx, t, lval,
4316 non_constant_p, overflow_p);
4317 break;
4319 case SIZEOF_EXPR:
4320 r = fold_sizeof_expr (t);
4321 VERIFY_CONSTANT (r);
4322 break;
4324 case COMPOUND_EXPR:
4326 /* check_return_expr sometimes wraps a TARGET_EXPR in a
4327 COMPOUND_EXPR; don't get confused. Also handle EMPTY_CLASS_EXPR
4328 introduced by build_call_a. */
4329 tree op0 = TREE_OPERAND (t, 0);
4330 tree op1 = TREE_OPERAND (t, 1);
4331 STRIP_NOPS (op1);
4332 if ((TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
4333 || TREE_CODE (op1) == EMPTY_CLASS_EXPR)
4334 r = cxx_eval_constant_expression (ctx, op0,
4335 lval, non_constant_p, overflow_p,
4336 jump_target);
4337 else
4339 /* Check that the LHS is constant and then discard it. */
4340 cxx_eval_constant_expression (ctx, op0,
4341 true, non_constant_p, overflow_p,
4342 jump_target);
4343 if (*non_constant_p)
4344 return t;
4345 op1 = TREE_OPERAND (t, 1);
4346 r = cxx_eval_constant_expression (ctx, op1,
4347 lval, non_constant_p, overflow_p,
4348 jump_target);
4351 break;
4353 case POINTER_PLUS_EXPR:
4354 case POINTER_DIFF_EXPR:
4355 case PLUS_EXPR:
4356 case MINUS_EXPR:
4357 case MULT_EXPR:
4358 case TRUNC_DIV_EXPR:
4359 case CEIL_DIV_EXPR:
4360 case FLOOR_DIV_EXPR:
4361 case ROUND_DIV_EXPR:
4362 case TRUNC_MOD_EXPR:
4363 case CEIL_MOD_EXPR:
4364 case ROUND_MOD_EXPR:
4365 case RDIV_EXPR:
4366 case EXACT_DIV_EXPR:
4367 case MIN_EXPR:
4368 case MAX_EXPR:
4369 case LSHIFT_EXPR:
4370 case RSHIFT_EXPR:
4371 case LROTATE_EXPR:
4372 case RROTATE_EXPR:
4373 case BIT_IOR_EXPR:
4374 case BIT_XOR_EXPR:
4375 case BIT_AND_EXPR:
4376 case TRUTH_XOR_EXPR:
4377 case LT_EXPR:
4378 case LE_EXPR:
4379 case GT_EXPR:
4380 case GE_EXPR:
4381 case EQ_EXPR:
4382 case NE_EXPR:
4383 case UNORDERED_EXPR:
4384 case ORDERED_EXPR:
4385 case UNLT_EXPR:
4386 case UNLE_EXPR:
4387 case UNGT_EXPR:
4388 case UNGE_EXPR:
4389 case UNEQ_EXPR:
4390 case LTGT_EXPR:
4391 case RANGE_EXPR:
4392 case COMPLEX_EXPR:
4393 r = cxx_eval_binary_expression (ctx, t, lval,
4394 non_constant_p, overflow_p);
4395 break;
4397 /* fold can introduce non-IF versions of these; still treat them as
4398 short-circuiting. */
4399 case TRUTH_AND_EXPR:
4400 case TRUTH_ANDIF_EXPR:
4401 r = cxx_eval_logical_expression (ctx, t, boolean_false_node,
4402 boolean_true_node,
4403 lval,
4404 non_constant_p, overflow_p);
4405 break;
4407 case TRUTH_OR_EXPR:
4408 case TRUTH_ORIF_EXPR:
4409 r = cxx_eval_logical_expression (ctx, t, boolean_true_node,
4410 boolean_false_node,
4411 lval,
4412 non_constant_p, overflow_p);
4413 break;
4415 case ARRAY_REF:
4416 r = cxx_eval_array_reference (ctx, t, lval,
4417 non_constant_p, overflow_p);
4418 break;
4420 case COMPONENT_REF:
4421 if (is_overloaded_fn (t))
4423 /* We can only get here in checking mode via
4424 build_non_dependent_expr, because any expression that
4425 calls or takes the address of the function will have
4426 pulled a FUNCTION_DECL out of the COMPONENT_REF. */
4427 gcc_checking_assert (ctx->quiet || errorcount);
4428 *non_constant_p = true;
4429 return t;
4431 r = cxx_eval_component_reference (ctx, t, lval,
4432 non_constant_p, overflow_p);
4433 break;
4435 case BIT_FIELD_REF:
4436 r = cxx_eval_bit_field_ref (ctx, t, lval,
4437 non_constant_p, overflow_p);
4438 break;
4440 case COND_EXPR:
4441 if (jump_target && *jump_target)
4443 /* When jumping to a label, the label might be either in the
4444 then or else blocks, so process then block first in skipping
4445 mode first, and if we are still in the skipping mode at its end,
4446 process the else block too. */
4447 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
4448 lval, non_constant_p, overflow_p,
4449 jump_target);
4450 if (*jump_target)
4451 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 2),
4452 lval, non_constant_p, overflow_p,
4453 jump_target);
4454 break;
4456 r = cxx_eval_conditional_expression (ctx, t, lval,
4457 non_constant_p, overflow_p,
4458 jump_target);
4459 break;
4460 case VEC_COND_EXPR:
4461 r = cxx_eval_vector_conditional_expression (ctx, t, non_constant_p,
4462 overflow_p);
4463 break;
4465 case CONSTRUCTOR:
4466 if (TREE_CONSTANT (t))
4468 /* Don't re-process a constant CONSTRUCTOR, but do fold it to
4469 VECTOR_CST if applicable. */
4470 /* FIXME after GCC 6 branches, make the verify unconditional. */
4471 if (CHECKING_P)
4472 verify_constructor_flags (t);
4473 else
4474 recompute_constructor_flags (t);
4475 if (TREE_CONSTANT (t))
4476 return fold (t);
4478 r = cxx_eval_bare_aggregate (ctx, t, lval,
4479 non_constant_p, overflow_p);
4480 break;
4482 case VEC_INIT_EXPR:
4483 /* We can get this in a defaulted constructor for a class with a
4484 non-static data member of array type. Either the initializer will
4485 be NULL, meaning default-initialization, or it will be an lvalue
4486 or xvalue of the same type, meaning direct-initialization from the
4487 corresponding member. */
4488 r = cxx_eval_vec_init (ctx, t, lval,
4489 non_constant_p, overflow_p);
4490 break;
4492 case FMA_EXPR:
4493 case VEC_PERM_EXPR:
4494 r = cxx_eval_trinary_expression (ctx, t, lval,
4495 non_constant_p, overflow_p);
4496 break;
4498 case CONVERT_EXPR:
4499 case VIEW_CONVERT_EXPR:
4500 case NOP_EXPR:
4501 case UNARY_PLUS_EXPR:
4503 tree oldop = TREE_OPERAND (t, 0);
4505 tree op = cxx_eval_constant_expression (ctx, oldop,
4506 lval,
4507 non_constant_p, overflow_p);
4508 if (*non_constant_p)
4509 return t;
4510 tree type = TREE_TYPE (t);
4511 if (TREE_CODE (op) == PTRMEM_CST
4512 && !TYPE_PTRMEM_P (type))
4513 op = cplus_expand_constant (op);
4514 if (TREE_CODE (op) == PTRMEM_CST && tcode == NOP_EXPR)
4516 if (same_type_ignoring_top_level_qualifiers_p (type,
4517 TREE_TYPE (op))
4518 || can_convert_qual (type, op))
4519 return cp_fold_convert (type, op);
4520 else
4522 if (!ctx->quiet)
4523 error_at (EXPR_LOC_OR_LOC (t, input_location),
4524 "a reinterpret_cast is not a constant expression");
4525 *non_constant_p = true;
4526 return t;
4530 if (POINTER_TYPE_P (type) && TREE_CODE (op) == INTEGER_CST)
4532 if (integer_zerop (op))
4534 if (TREE_CODE (type) == REFERENCE_TYPE)
4536 if (!ctx->quiet)
4537 error_at (EXPR_LOC_OR_LOC (t, input_location),
4538 "dereferencing a null pointer");
4539 *non_constant_p = true;
4540 return t;
4542 else if (TREE_CODE (TREE_TYPE (op)) == POINTER_TYPE)
4544 tree from = TREE_TYPE (op);
4546 if (!can_convert (type, from, tf_none))
4548 if (!ctx->quiet)
4549 error_at (EXPR_LOC_OR_LOC (t, input_location),
4550 "conversion of %qT null pointer to %qT "
4551 "is not a constant expression",
4552 from, type);
4553 *non_constant_p = true;
4554 return t;
4558 else
4560 /* This detects for example:
4561 reinterpret_cast<void*>(sizeof 0)
4563 if (!ctx->quiet)
4564 error_at (EXPR_LOC_OR_LOC (t, input_location),
4565 "%<reinterpret_cast<%T>(%E)%> is not "
4566 "a constant expression",
4567 type, op);
4568 *non_constant_p = true;
4569 return t;
4572 if (op == oldop && tcode != UNARY_PLUS_EXPR)
4573 /* We didn't fold at the top so we could check for ptr-int
4574 conversion. */
4575 return fold (t);
4576 if (tcode == UNARY_PLUS_EXPR)
4577 r = fold_convert (TREE_TYPE (t), op);
4578 else
4579 r = fold_build1 (tcode, type, op);
4580 /* Conversion of an out-of-range value has implementation-defined
4581 behavior; the language considers it different from arithmetic
4582 overflow, which is undefined. */
4583 if (TREE_OVERFLOW_P (r) && !TREE_OVERFLOW_P (op))
4584 TREE_OVERFLOW (r) = false;
4586 break;
4588 case EMPTY_CLASS_EXPR:
4589 /* This is good enough for a function argument that might not get
4590 used, and they can't do anything with it, so just return it. */
4591 return t;
4593 case STATEMENT_LIST:
4594 new_ctx = *ctx;
4595 new_ctx.ctor = new_ctx.object = NULL_TREE;
4596 return cxx_eval_statement_list (&new_ctx, t,
4597 non_constant_p, overflow_p, jump_target);
4599 case BIND_EXPR:
4600 return cxx_eval_constant_expression (ctx, BIND_EXPR_BODY (t),
4601 lval,
4602 non_constant_p, overflow_p,
4603 jump_target);
4605 case PREINCREMENT_EXPR:
4606 case POSTINCREMENT_EXPR:
4607 case PREDECREMENT_EXPR:
4608 case POSTDECREMENT_EXPR:
4609 return cxx_eval_increment_expression (ctx, t,
4610 lval, non_constant_p, overflow_p);
4612 case LAMBDA_EXPR:
4613 case NEW_EXPR:
4614 case VEC_NEW_EXPR:
4615 case DELETE_EXPR:
4616 case VEC_DELETE_EXPR:
4617 case THROW_EXPR:
4618 case MODOP_EXPR:
4619 /* GCC internal stuff. */
4620 case VA_ARG_EXPR:
4621 case OBJ_TYPE_REF:
4622 case NON_DEPENDENT_EXPR:
4623 case BASELINK:
4624 case OFFSET_REF:
4625 if (!ctx->quiet)
4626 error_at (EXPR_LOC_OR_LOC (t, input_location),
4627 "expression %qE is not a constant expression", t);
4628 *non_constant_p = true;
4629 break;
4631 case PLACEHOLDER_EXPR:
4632 /* Use of the value or address of the current object. */
4633 if (tree ctor = lookup_placeholder (ctx, lval, TREE_TYPE (t)))
4634 return cxx_eval_constant_expression (ctx, ctor, lval,
4635 non_constant_p, overflow_p);
4636 /* A placeholder without a referent. We can get here when
4637 checking whether NSDMIs are noexcept, or in massage_init_elt;
4638 just say it's non-constant for now. */
4639 gcc_assert (ctx->quiet);
4640 *non_constant_p = true;
4641 break;
4643 case EXIT_EXPR:
4645 tree cond = TREE_OPERAND (t, 0);
4646 cond = cxx_eval_constant_expression (ctx, cond, /*lval*/false,
4647 non_constant_p, overflow_p);
4648 VERIFY_CONSTANT (cond);
4649 if (integer_nonzerop (cond))
4650 *jump_target = t;
4652 break;
4654 case GOTO_EXPR:
4655 *jump_target = TREE_OPERAND (t, 0);
4656 gcc_assert (breaks (jump_target) || continues (jump_target)
4657 /* Allow for jumping to a cdtor_label. */
4658 || returns (jump_target));
4659 break;
4661 case LOOP_EXPR:
4662 cxx_eval_loop_expr (ctx, t,
4663 non_constant_p, overflow_p, jump_target);
4664 break;
4666 case SWITCH_EXPR:
4667 cxx_eval_switch_expr (ctx, t,
4668 non_constant_p, overflow_p, jump_target);
4669 break;
4671 case REQUIRES_EXPR:
4672 /* It's possible to get a requires-expression in a constant
4673 expression. For example:
4675 template<typename T> concept bool C() {
4676 return requires (T t) { t; };
4679 template<typename T> requires !C<T>() void f(T);
4681 Normalization leaves f with the associated constraint
4682 '!requires (T t) { ... }' which is not transformed into
4683 a constraint. */
4684 if (!processing_template_decl)
4685 return evaluate_constraint_expression (t, NULL_TREE);
4686 else
4687 *non_constant_p = true;
4688 return t;
4690 case ANNOTATE_EXPR:
4691 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
4692 lval,
4693 non_constant_p, overflow_p,
4694 jump_target);
4695 break;
4697 default:
4698 if (STATEMENT_CODE_P (TREE_CODE (t)))
4700 /* This function doesn't know how to deal with pre-genericize
4701 statements; this can only happen with statement-expressions,
4702 so for now just fail. */
4703 if (!ctx->quiet)
4704 error_at (EXPR_LOCATION (t),
4705 "statement is not a constant expression");
4707 else
4708 internal_error ("unexpected expression %qE of kind %s", t,
4709 get_tree_code_name (TREE_CODE (t)));
4710 *non_constant_p = true;
4711 break;
4714 if (r == error_mark_node)
4715 *non_constant_p = true;
4717 if (*non_constant_p)
4718 return t;
4719 else
4720 return r;
4723 static tree
4724 cxx_eval_outermost_constant_expr (tree t, bool allow_non_constant,
4725 bool strict = true, tree object = NULL_TREE)
4727 auto_timevar time (TV_CONSTEXPR);
4729 bool non_constant_p = false;
4730 bool overflow_p = false;
4731 hash_map<tree,tree> map;
4733 constexpr_ctx ctx = { NULL, &map, NULL, NULL, NULL, NULL,
4734 allow_non_constant, strict };
4736 tree type = initialized_type (t);
4737 tree r = t;
4738 if (AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type))
4740 /* In C++14 an NSDMI can participate in aggregate initialization,
4741 and can refer to the address of the object being initialized, so
4742 we need to pass in the relevant VAR_DECL if we want to do the
4743 evaluation in a single pass. The evaluation will dynamically
4744 update ctx.values for the VAR_DECL. We use the same strategy
4745 for C++11 constexpr constructors that refer to the object being
4746 initialized. */
4747 ctx.ctor = build_constructor (type, NULL);
4748 CONSTRUCTOR_NO_IMPLICIT_ZERO (ctx.ctor) = true;
4749 if (!object)
4751 if (TREE_CODE (t) == TARGET_EXPR)
4752 object = TARGET_EXPR_SLOT (t);
4753 else if (TREE_CODE (t) == AGGR_INIT_EXPR)
4754 object = AGGR_INIT_EXPR_SLOT (t);
4756 ctx.object = object;
4757 if (object)
4758 gcc_assert (same_type_ignoring_top_level_qualifiers_p
4759 (type, TREE_TYPE (object)));
4760 if (object && DECL_P (object))
4761 map.put (object, ctx.ctor);
4762 if (TREE_CODE (r) == TARGET_EXPR)
4763 /* Avoid creating another CONSTRUCTOR when we expand the
4764 TARGET_EXPR. */
4765 r = TARGET_EXPR_INITIAL (r);
4768 r = cxx_eval_constant_expression (&ctx, r,
4769 false, &non_constant_p, &overflow_p);
4771 verify_constant (r, allow_non_constant, &non_constant_p, &overflow_p);
4773 /* Mutable logic is a bit tricky: we want to allow initialization of
4774 constexpr variables with mutable members, but we can't copy those
4775 members to another constexpr variable. */
4776 if (TREE_CODE (r) == CONSTRUCTOR
4777 && CONSTRUCTOR_MUTABLE_POISON (r))
4779 if (!allow_non_constant)
4780 error ("%qE is not a constant expression because it refers to "
4781 "mutable subobjects of %qT", t, type);
4782 non_constant_p = true;
4785 if (TREE_CODE (r) == CONSTRUCTOR
4786 && CONSTRUCTOR_NO_IMPLICIT_ZERO (r))
4788 if (!allow_non_constant)
4789 error ("%qE is not a constant expression because it refers to "
4790 "an incompletely initialized variable", t);
4791 TREE_CONSTANT (r) = false;
4792 non_constant_p = true;
4795 /* Technically we should check this for all subexpressions, but that
4796 runs into problems with our internal representation of pointer
4797 subtraction and the 5.19 rules are still in flux. */
4798 if (CONVERT_EXPR_CODE_P (TREE_CODE (r))
4799 && ARITHMETIC_TYPE_P (TREE_TYPE (r))
4800 && TREE_CODE (TREE_OPERAND (r, 0)) == ADDR_EXPR)
4802 if (!allow_non_constant)
4803 error ("conversion from pointer type %qT "
4804 "to arithmetic type %qT in a constant expression",
4805 TREE_TYPE (TREE_OPERAND (r, 0)), TREE_TYPE (r));
4806 non_constant_p = true;
4809 if (!non_constant_p && overflow_p)
4810 non_constant_p = true;
4812 /* Unshare the result unless it's a CONSTRUCTOR in which case it's already
4813 unshared. */
4814 bool should_unshare = true;
4815 if (r == t || TREE_CODE (r) == CONSTRUCTOR)
4816 should_unshare = false;
4818 if (non_constant_p && !allow_non_constant)
4819 return error_mark_node;
4820 else if (non_constant_p && TREE_CONSTANT (r))
4822 /* This isn't actually constant, so unset TREE_CONSTANT. */
4823 if (EXPR_P (r))
4824 r = copy_node (r);
4825 else if (TREE_CODE (r) == CONSTRUCTOR)
4826 r = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (r), r);
4827 else
4828 r = build_nop (TREE_TYPE (r), r);
4829 TREE_CONSTANT (r) = false;
4831 else if (non_constant_p || r == t)
4832 return t;
4834 if (should_unshare)
4835 r = unshare_expr (r);
4837 if (TREE_CODE (r) == CONSTRUCTOR && CLASS_TYPE_P (TREE_TYPE (r)))
4839 if (TREE_CODE (t) == TARGET_EXPR
4840 && TARGET_EXPR_INITIAL (t) == r)
4841 return t;
4842 else
4844 r = get_target_expr (r);
4845 TREE_CONSTANT (r) = true;
4846 return r;
4849 else
4850 return r;
4853 /* Returns true if T is a valid subexpression of a constant expression,
4854 even if it isn't itself a constant expression. */
4856 bool
4857 is_sub_constant_expr (tree t)
4859 bool non_constant_p = false;
4860 bool overflow_p = false;
4861 hash_map <tree, tree> map;
4863 constexpr_ctx ctx = { NULL, &map, NULL, NULL, NULL, NULL, true, true };
4865 cxx_eval_constant_expression (&ctx, t, false, &non_constant_p,
4866 &overflow_p);
4867 return !non_constant_p && !overflow_p;
4870 /* If T represents a constant expression returns its reduced value.
4871 Otherwise return error_mark_node. If T is dependent, then
4872 return NULL. */
4874 tree
4875 cxx_constant_value (tree t, tree decl)
4877 return cxx_eval_outermost_constant_expr (t, false, true, decl);
4880 /* Helper routine for fold_simple function. Either return simplified
4881 expression T, otherwise NULL_TREE.
4882 In contrast to cp_fully_fold, and to maybe_constant_value, we try to fold
4883 even if we are within template-declaration. So be careful on call, as in
4884 such case types can be undefined. */
4886 static tree
4887 fold_simple_1 (tree t)
4889 tree op1;
4890 enum tree_code code = TREE_CODE (t);
4892 switch (code)
4894 case INTEGER_CST:
4895 case REAL_CST:
4896 case VECTOR_CST:
4897 case FIXED_CST:
4898 case COMPLEX_CST:
4899 return t;
4901 case SIZEOF_EXPR:
4902 return fold_sizeof_expr (t);
4904 case ABS_EXPR:
4905 case CONJ_EXPR:
4906 case REALPART_EXPR:
4907 case IMAGPART_EXPR:
4908 case NEGATE_EXPR:
4909 case BIT_NOT_EXPR:
4910 case TRUTH_NOT_EXPR:
4911 case NOP_EXPR:
4912 case VIEW_CONVERT_EXPR:
4913 case CONVERT_EXPR:
4914 case FLOAT_EXPR:
4915 case FIX_TRUNC_EXPR:
4916 case FIXED_CONVERT_EXPR:
4917 case ADDR_SPACE_CONVERT_EXPR:
4919 op1 = TREE_OPERAND (t, 0);
4921 t = const_unop (code, TREE_TYPE (t), op1);
4922 if (!t)
4923 return NULL_TREE;
4925 if (CONVERT_EXPR_CODE_P (code)
4926 && TREE_OVERFLOW_P (t) && !TREE_OVERFLOW_P (op1))
4927 TREE_OVERFLOW (t) = false;
4928 return t;
4930 default:
4931 return NULL_TREE;
4935 /* If T is a simple constant expression, returns its simplified value.
4936 Otherwise returns T. In contrast to maybe_constant_value do we
4937 simplify only few operations on constant-expressions, and we don't
4938 try to simplify constexpressions. */
4940 tree
4941 fold_simple (tree t)
4943 tree r = NULL_TREE;
4944 if (processing_template_decl)
4945 return t;
4947 r = fold_simple_1 (t);
4948 if (!r)
4949 r = t;
4951 return r;
4954 /* If T is a constant expression, returns its reduced value.
4955 Otherwise, if T does not have TREE_CONSTANT set, returns T.
4956 Otherwise, returns a version of T without TREE_CONSTANT. */
4958 static GTY((deletable)) hash_map<tree, tree> *cv_cache;
4960 tree
4961 maybe_constant_value (tree t, tree decl)
4963 tree r;
4965 if (!is_nondependent_constant_expression (t))
4967 if (TREE_OVERFLOW_P (t))
4969 t = build_nop (TREE_TYPE (t), t);
4970 TREE_CONSTANT (t) = false;
4972 return t;
4974 else if (CONSTANT_CLASS_P (t))
4975 /* No caching or evaluation needed. */
4976 return t;
4978 if (cv_cache == NULL)
4979 cv_cache = hash_map<tree, tree>::create_ggc (101);
4980 if (tree *cached = cv_cache->get (t))
4981 return *cached;
4983 r = cxx_eval_outermost_constant_expr (t, true, true, decl);
4984 gcc_checking_assert (r == t
4985 || CONVERT_EXPR_P (t)
4986 || TREE_CODE (t) == VIEW_CONVERT_EXPR
4987 || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
4988 || !cp_tree_equal (r, t));
4989 cv_cache->put (t, r);
4990 return r;
4993 /* Dispose of the whole CV_CACHE. */
4995 static void
4996 clear_cv_cache (void)
4998 if (cv_cache != NULL)
4999 cv_cache->empty ();
5002 /* Dispose of the whole CV_CACHE and FOLD_CACHE. */
5004 void
5005 clear_cv_and_fold_caches (void)
5007 clear_cv_cache ();
5008 clear_fold_cache ();
5011 /* Like maybe_constant_value but first fully instantiate the argument.
5013 Note: this is equivalent to instantiate_non_dependent_expr_sfinae
5014 (t, tf_none) followed by maybe_constant_value but is more efficient,
5015 because calls instantiation_dependent_expression_p and
5016 potential_constant_expression at most once. */
5018 tree
5019 fold_non_dependent_expr (tree t)
5021 if (t == NULL_TREE)
5022 return NULL_TREE;
5024 /* If we're in a template, but T isn't value dependent, simplify
5025 it. We're supposed to treat:
5027 template <typename T> void f(T[1 + 1]);
5028 template <typename T> void f(T[2]);
5030 as two declarations of the same function, for example. */
5031 if (processing_template_decl)
5033 if (is_nondependent_constant_expression (t))
5035 processing_template_decl_sentinel s;
5036 t = instantiate_non_dependent_expr_internal (t, tf_none);
5038 if (type_unknown_p (t)
5039 || BRACE_ENCLOSED_INITIALIZER_P (t))
5041 if (TREE_OVERFLOW_P (t))
5043 t = build_nop (TREE_TYPE (t), t);
5044 TREE_CONSTANT (t) = false;
5046 return t;
5049 tree r = cxx_eval_outermost_constant_expr (t, true, true, NULL_TREE);
5050 /* cp_tree_equal looks through NOPs, so allow them. */
5051 gcc_checking_assert (r == t
5052 || CONVERT_EXPR_P (t)
5053 || TREE_CODE (t) == VIEW_CONVERT_EXPR
5054 || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
5055 || !cp_tree_equal (r, t));
5056 return r;
5058 else if (TREE_OVERFLOW_P (t))
5060 t = build_nop (TREE_TYPE (t), t);
5061 TREE_CONSTANT (t) = false;
5063 return t;
5066 return maybe_constant_value (t);
5069 /* Like maybe_constant_value, but returns a CONSTRUCTOR directly, rather
5070 than wrapped in a TARGET_EXPR. */
5072 tree
5073 maybe_constant_init (tree t, tree decl)
5075 if (!t)
5076 return t;
5077 if (TREE_CODE (t) == EXPR_STMT)
5078 t = TREE_OPERAND (t, 0);
5079 if (TREE_CODE (t) == CONVERT_EXPR
5080 && VOID_TYPE_P (TREE_TYPE (t)))
5081 t = TREE_OPERAND (t, 0);
5082 if (TREE_CODE (t) == INIT_EXPR)
5083 t = TREE_OPERAND (t, 1);
5084 if (TREE_CODE (t) == TARGET_EXPR)
5085 t = TARGET_EXPR_INITIAL (t);
5086 if (!is_nondependent_static_init_expression (t))
5087 /* Don't try to evaluate it. */;
5088 else if (CONSTANT_CLASS_P (t))
5089 /* No evaluation needed. */;
5090 else
5091 t = cxx_eval_outermost_constant_expr (t, true, false, decl);
5092 if (TREE_CODE (t) == TARGET_EXPR)
5094 tree init = TARGET_EXPR_INITIAL (t);
5095 if (TREE_CODE (init) == CONSTRUCTOR)
5096 t = init;
5098 return t;
5101 #if 0
5102 /* FIXME see ADDR_EXPR section in potential_constant_expression_1. */
5103 /* Return true if the object referred to by REF has automatic or thread
5104 local storage. */
5106 enum { ck_ok, ck_bad, ck_unknown };
5107 static int
5108 check_automatic_or_tls (tree ref)
5110 machine_mode mode;
5111 poly_int64 bitsize, bitpos;
5112 tree offset;
5113 int volatilep = 0, unsignedp = 0;
5114 tree decl = get_inner_reference (ref, &bitsize, &bitpos, &offset,
5115 &mode, &unsignedp, &volatilep, false);
5116 duration_kind dk;
5118 /* If there isn't a decl in the middle, we don't know the linkage here,
5119 and this isn't a constant expression anyway. */
5120 if (!DECL_P (decl))
5121 return ck_unknown;
5122 dk = decl_storage_duration (decl);
5123 return (dk == dk_auto || dk == dk_thread) ? ck_bad : ck_ok;
5125 #endif
5127 /* Return true if T denotes a potentially constant expression. Issue
5128 diagnostic as appropriate under control of FLAGS. If WANT_RVAL is true,
5129 an lvalue-rvalue conversion is implied. If NOW is true, we want to
5130 consider the expression in the current context, independent of constexpr
5131 substitution.
5133 C++0x [expr.const] used to say
5135 6 An expression is a potential constant expression if it is
5136 a constant expression where all occurrences of function
5137 parameters are replaced by arbitrary constant expressions
5138 of the appropriate type.
5140 2 A conditional expression is a constant expression unless it
5141 involves one of the following as a potentially evaluated
5142 subexpression (3.2), but subexpressions of logical AND (5.14),
5143 logical OR (5.15), and conditional (5.16) operations that are
5144 not evaluated are not considered. */
5146 static bool
5147 potential_constant_expression_1 (tree t, bool want_rval, bool strict, bool now,
5148 tsubst_flags_t flags)
5150 #define RECUR(T,RV) \
5151 potential_constant_expression_1 ((T), (RV), strict, now, flags)
5153 enum { any = false, rval = true };
5154 int i;
5155 tree tmp;
5157 if (t == error_mark_node)
5158 return false;
5159 if (t == NULL_TREE)
5160 return true;
5161 location_t loc = EXPR_LOC_OR_LOC (t, input_location);
5162 if (TREE_THIS_VOLATILE (t) && !DECL_P (t))
5164 if (flags & tf_error)
5165 error_at (loc, "expression %qE has side-effects", t);
5166 return false;
5168 if (CONSTANT_CLASS_P (t))
5169 return true;
5170 if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_TYPED)
5171 && TREE_TYPE (t) == error_mark_node)
5172 return false;
5174 switch (TREE_CODE (t))
5176 case FUNCTION_DECL:
5177 case BASELINK:
5178 case TEMPLATE_DECL:
5179 case OVERLOAD:
5180 case TEMPLATE_ID_EXPR:
5181 case LABEL_DECL:
5182 case LABEL_EXPR:
5183 case CASE_LABEL_EXPR:
5184 case CONST_DECL:
5185 case SIZEOF_EXPR:
5186 case ALIGNOF_EXPR:
5187 case OFFSETOF_EXPR:
5188 case NOEXCEPT_EXPR:
5189 case TEMPLATE_PARM_INDEX:
5190 case TRAIT_EXPR:
5191 case IDENTIFIER_NODE:
5192 case USERDEF_LITERAL:
5193 /* We can see a FIELD_DECL in a pointer-to-member expression. */
5194 case FIELD_DECL:
5195 case RESULT_DECL:
5196 case USING_DECL:
5197 case USING_STMT:
5198 case PLACEHOLDER_EXPR:
5199 case BREAK_STMT:
5200 case CONTINUE_STMT:
5201 case REQUIRES_EXPR:
5202 case STATIC_ASSERT:
5203 case DEBUG_BEGIN_STMT:
5204 return true;
5206 case PARM_DECL:
5207 if (now)
5209 if (flags & tf_error)
5210 error ("%qE is not a constant expression", t);
5211 return false;
5213 return true;
5215 case AGGR_INIT_EXPR:
5216 case CALL_EXPR:
5217 /* -- an invocation of a function other than a constexpr function
5218 or a constexpr constructor. */
5220 tree fun = get_function_named_in_call (t);
5221 const int nargs = call_expr_nargs (t);
5222 i = 0;
5224 if (fun == NULL_TREE)
5226 /* Reset to allow the function to continue past the end
5227 of the block below. Otherwise return early. */
5228 bool bail = true;
5230 if (TREE_CODE (t) == CALL_EXPR
5231 && CALL_EXPR_FN (t) == NULL_TREE)
5232 switch (CALL_EXPR_IFN (t))
5234 /* These should be ignored, they are optimized away from
5235 constexpr functions. */
5236 case IFN_UBSAN_NULL:
5237 case IFN_UBSAN_BOUNDS:
5238 case IFN_UBSAN_VPTR:
5239 case IFN_FALLTHROUGH:
5240 return true;
5242 case IFN_ADD_OVERFLOW:
5243 case IFN_SUB_OVERFLOW:
5244 case IFN_MUL_OVERFLOW:
5245 case IFN_LAUNDER:
5246 bail = false;
5248 default:
5249 break;
5252 if (bail)
5254 /* fold_call_expr can't do anything with IFN calls. */
5255 if (flags & tf_error)
5256 error_at (loc, "call to internal function %qE", t);
5257 return false;
5261 if (fun && is_overloaded_fn (fun))
5263 if (TREE_CODE (fun) == FUNCTION_DECL)
5265 if (builtin_valid_in_constant_expr_p (fun))
5266 return true;
5267 if (!DECL_DECLARED_CONSTEXPR_P (fun)
5268 /* Allow any built-in function; if the expansion
5269 isn't constant, we'll deal with that then. */
5270 && !is_builtin_fn (fun))
5272 if (flags & tf_error)
5274 error_at (loc, "call to non-%<constexpr%> function %qD",
5275 fun);
5276 explain_invalid_constexpr_fn (fun);
5278 return false;
5280 /* A call to a non-static member function takes the address
5281 of the object as the first argument. But in a constant
5282 expression the address will be folded away, so look
5283 through it now. */
5284 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fun)
5285 && !DECL_CONSTRUCTOR_P (fun))
5287 tree x = get_nth_callarg (t, 0);
5288 if (is_this_parameter (x))
5289 return true;
5290 /* Don't require an immediately constant value, as
5291 constexpr substitution might not use the value. */
5292 bool sub_now = false;
5293 if (!potential_constant_expression_1 (x, rval, strict,
5294 sub_now, flags))
5295 return false;
5296 i = 1;
5299 else
5301 if (!RECUR (fun, true))
5302 return false;
5303 fun = get_first_fn (fun);
5305 /* Skip initial arguments to base constructors. */
5306 if (DECL_BASE_CONSTRUCTOR_P (fun))
5307 i = num_artificial_parms_for (fun);
5308 fun = DECL_ORIGIN (fun);
5310 else if (fun)
5312 if (RECUR (fun, rval))
5313 /* Might end up being a constant function pointer. */;
5314 else
5315 return false;
5317 for (; i < nargs; ++i)
5319 tree x = get_nth_callarg (t, i);
5320 /* In a template, reference arguments haven't been converted to
5321 REFERENCE_TYPE and we might not even know if the parameter
5322 is a reference, so accept lvalue constants too. */
5323 bool rv = processing_template_decl ? any : rval;
5324 /* Don't require an immediately constant value, as constexpr
5325 substitution might not use the value of the argument. */
5326 bool sub_now = false;
5327 if (!potential_constant_expression_1 (x, rv, strict,
5328 sub_now, flags))
5329 return false;
5331 return true;
5334 case NON_LVALUE_EXPR:
5335 /* -- an lvalue-to-rvalue conversion (4.1) unless it is applied to
5336 -- an lvalue of integral type that refers to a non-volatile
5337 const variable or static data member initialized with
5338 constant expressions, or
5340 -- an lvalue of literal type that refers to non-volatile
5341 object defined with constexpr, or that refers to a
5342 sub-object of such an object; */
5343 return RECUR (TREE_OPERAND (t, 0), rval);
5345 case VAR_DECL:
5346 if (DECL_HAS_VALUE_EXPR_P (t))
5348 if (now && is_normal_capture_proxy (t))
5350 /* -- in a lambda-expression, a reference to this or to a
5351 variable with automatic storage duration defined outside that
5352 lambda-expression, where the reference would be an
5353 odr-use. */
5354 if (flags & tf_error)
5356 tree cap = DECL_CAPTURED_VARIABLE (t);
5357 error ("lambda capture of %qE is not a constant expression",
5358 cap);
5359 if (!want_rval && decl_constant_var_p (cap))
5360 inform (input_location, "because it is used as a glvalue");
5362 return false;
5364 return RECUR (DECL_VALUE_EXPR (t), rval);
5366 if (want_rval
5367 && !var_in_maybe_constexpr_fn (t)
5368 && !type_dependent_expression_p (t)
5369 && !decl_maybe_constant_var_p (t)
5370 && (strict
5371 || !CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (t))
5372 || (DECL_INITIAL (t)
5373 && !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t)))
5374 && COMPLETE_TYPE_P (TREE_TYPE (t))
5375 && !is_really_empty_class (TREE_TYPE (t)))
5377 if (flags & tf_error)
5378 non_const_var_error (t);
5379 return false;
5381 return true;
5383 case NOP_EXPR:
5384 case CONVERT_EXPR:
5385 case VIEW_CONVERT_EXPR:
5386 /* -- a reinterpret_cast. FIXME not implemented, and this rule
5387 may change to something more specific to type-punning (DR 1312). */
5389 tree from = TREE_OPERAND (t, 0);
5390 if (POINTER_TYPE_P (TREE_TYPE (t))
5391 && TREE_CODE (from) == INTEGER_CST
5392 && !integer_zerop (from))
5394 if (flags & tf_error)
5395 error_at (loc, "reinterpret_cast from integer to pointer");
5396 return false;
5398 return (RECUR (from, TREE_CODE (t) != VIEW_CONVERT_EXPR));
5401 case ADDRESSOF_EXPR:
5402 /* This is like ADDR_EXPR, except it won't form pointer-to-member. */
5403 t = TREE_OPERAND (t, 0);
5404 goto handle_addr_expr;
5406 case ADDR_EXPR:
5407 /* -- a unary operator & that is applied to an lvalue that
5408 designates an object with thread or automatic storage
5409 duration; */
5410 t = TREE_OPERAND (t, 0);
5412 if (TREE_CODE (t) == OFFSET_REF && PTRMEM_OK_P (t))
5413 /* A pointer-to-member constant. */
5414 return true;
5416 handle_addr_expr:
5417 #if 0
5418 /* FIXME adjust when issue 1197 is fully resolved. For now don't do
5419 any checking here, as we might dereference the pointer later. If
5420 we remove this code, also remove check_automatic_or_tls. */
5421 i = check_automatic_or_tls (t);
5422 if (i == ck_ok)
5423 return true;
5424 if (i == ck_bad)
5426 if (flags & tf_error)
5427 error ("address-of an object %qE with thread local or "
5428 "automatic storage is not a constant expression", t);
5429 return false;
5431 #endif
5432 return RECUR (t, any);
5434 case REALPART_EXPR:
5435 case IMAGPART_EXPR:
5436 case COMPONENT_REF:
5437 case BIT_FIELD_REF:
5438 case ARROW_EXPR:
5439 case OFFSET_REF:
5440 /* -- a class member access unless its postfix-expression is
5441 of literal type or of pointer to literal type. */
5442 /* This test would be redundant, as it follows from the
5443 postfix-expression being a potential constant expression. */
5444 if (type_unknown_p (t))
5445 return true;
5446 return RECUR (TREE_OPERAND (t, 0), want_rval);
5448 case EXPR_PACK_EXPANSION:
5449 return RECUR (PACK_EXPANSION_PATTERN (t), want_rval);
5451 case INDIRECT_REF:
5453 tree x = TREE_OPERAND (t, 0);
5454 STRIP_NOPS (x);
5455 if (is_this_parameter (x) && !is_capture_proxy (x))
5457 if (!var_in_maybe_constexpr_fn (x))
5459 if (flags & tf_error)
5460 error_at (loc, "use of %<this%> in a constant expression");
5461 return false;
5463 return true;
5465 return RECUR (x, rval);
5468 case STATEMENT_LIST:
5470 tree_stmt_iterator i;
5471 for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
5473 if (!RECUR (tsi_stmt (i), any))
5474 return false;
5476 return true;
5478 break;
5480 case MODIFY_EXPR:
5481 if (cxx_dialect < cxx14)
5482 goto fail;
5483 if (!RECUR (TREE_OPERAND (t, 0), any))
5484 return false;
5485 if (!RECUR (TREE_OPERAND (t, 1), rval))
5486 return false;
5487 return true;
5489 case MODOP_EXPR:
5490 if (cxx_dialect < cxx14)
5491 goto fail;
5492 if (!RECUR (TREE_OPERAND (t, 0), rval))
5493 return false;
5494 if (!RECUR (TREE_OPERAND (t, 2), rval))
5495 return false;
5496 return true;
5498 case DO_STMT:
5499 if (!RECUR (DO_COND (t), rval))
5500 return false;
5501 if (!RECUR (DO_BODY (t), any))
5502 return false;
5503 return true;
5505 case FOR_STMT:
5506 if (!RECUR (FOR_INIT_STMT (t), any))
5507 return false;
5508 if (!RECUR (FOR_COND (t), rval))
5509 return false;
5510 if (!RECUR (FOR_EXPR (t), any))
5511 return false;
5512 if (!RECUR (FOR_BODY (t), any))
5513 return false;
5514 return true;
5516 case RANGE_FOR_STMT:
5517 if (!RECUR (RANGE_FOR_EXPR (t), any))
5518 return false;
5519 if (!RECUR (RANGE_FOR_BODY (t), any))
5520 return false;
5521 return true;
5523 case WHILE_STMT:
5524 if (!RECUR (WHILE_COND (t), rval))
5525 return false;
5526 if (!RECUR (WHILE_BODY (t), any))
5527 return false;
5528 return true;
5530 case SWITCH_STMT:
5531 if (!RECUR (SWITCH_STMT_COND (t), rval))
5532 return false;
5533 /* FIXME we don't check SWITCH_STMT_BODY currently, because even
5534 unreachable labels would be checked. */
5535 return true;
5537 case STMT_EXPR:
5538 return RECUR (STMT_EXPR_STMT (t), rval);
5540 case LAMBDA_EXPR:
5541 if (cxx_dialect >= cxx17)
5542 /* In C++17 lambdas can be constexpr, don't give up yet. */
5543 return true;
5544 else if (flags & tf_error)
5545 error_at (loc, "lambda-expression is not a constant expression "
5546 "before C++17");
5547 return false;
5549 case DYNAMIC_CAST_EXPR:
5550 case PSEUDO_DTOR_EXPR:
5551 case NEW_EXPR:
5552 case VEC_NEW_EXPR:
5553 case DELETE_EXPR:
5554 case VEC_DELETE_EXPR:
5555 case THROW_EXPR:
5556 case OMP_PARALLEL:
5557 case OMP_TASK:
5558 case OMP_FOR:
5559 case OMP_DISTRIBUTE:
5560 case OMP_TASKLOOP:
5561 case OMP_TEAMS:
5562 case OMP_TARGET_DATA:
5563 case OMP_TARGET:
5564 case OMP_SECTIONS:
5565 case OMP_ORDERED:
5566 case OMP_CRITICAL:
5567 case OMP_SINGLE:
5568 case OMP_SECTION:
5569 case OMP_MASTER:
5570 case OMP_TASKGROUP:
5571 case OMP_TARGET_UPDATE:
5572 case OMP_TARGET_ENTER_DATA:
5573 case OMP_TARGET_EXIT_DATA:
5574 case OMP_ATOMIC:
5575 case OMP_ATOMIC_READ:
5576 case OMP_ATOMIC_CAPTURE_OLD:
5577 case OMP_ATOMIC_CAPTURE_NEW:
5578 case OACC_PARALLEL:
5579 case OACC_KERNELS:
5580 case OACC_DATA:
5581 case OACC_HOST_DATA:
5582 case OACC_LOOP:
5583 case OACC_CACHE:
5584 case OACC_DECLARE:
5585 case OACC_ENTER_DATA:
5586 case OACC_EXIT_DATA:
5587 case OACC_UPDATE:
5588 /* GCC internal stuff. */
5589 case VA_ARG_EXPR:
5590 case OBJ_TYPE_REF:
5591 case TRANSACTION_EXPR:
5592 case ASM_EXPR:
5593 case AT_ENCODE_EXPR:
5594 fail:
5595 if (flags & tf_error)
5596 error_at (loc, "expression %qE is not a constant expression", t);
5597 return false;
5599 case TYPEID_EXPR:
5600 /* -- a typeid expression whose operand is of polymorphic
5601 class type; */
5603 tree e = TREE_OPERAND (t, 0);
5604 if (!TYPE_P (e) && !type_dependent_expression_p (e)
5605 && TYPE_POLYMORPHIC_P (TREE_TYPE (e)))
5607 if (flags & tf_error)
5608 error_at (loc, "typeid-expression is not a constant expression "
5609 "because %qE is of polymorphic type", e);
5610 return false;
5612 return true;
5615 case POINTER_DIFF_EXPR:
5616 case MINUS_EXPR:
5617 want_rval = true;
5618 goto binary;
5620 case LT_EXPR:
5621 case LE_EXPR:
5622 case GT_EXPR:
5623 case GE_EXPR:
5624 case EQ_EXPR:
5625 case NE_EXPR:
5626 want_rval = true;
5627 goto binary;
5629 case PREINCREMENT_EXPR:
5630 case POSTINCREMENT_EXPR:
5631 case PREDECREMENT_EXPR:
5632 case POSTDECREMENT_EXPR:
5633 if (cxx_dialect < cxx14)
5634 goto fail;
5635 goto unary;
5637 case BIT_NOT_EXPR:
5638 /* A destructor. */
5639 if (TYPE_P (TREE_OPERAND (t, 0)))
5640 return true;
5641 /* fall through. */
5643 case CONJ_EXPR:
5644 case SAVE_EXPR:
5645 case FIX_TRUNC_EXPR:
5646 case FLOAT_EXPR:
5647 case NEGATE_EXPR:
5648 case ABS_EXPR:
5649 case TRUTH_NOT_EXPR:
5650 case FIXED_CONVERT_EXPR:
5651 case UNARY_PLUS_EXPR:
5652 case UNARY_LEFT_FOLD_EXPR:
5653 case UNARY_RIGHT_FOLD_EXPR:
5654 unary:
5655 return RECUR (TREE_OPERAND (t, 0), rval);
5657 case CAST_EXPR:
5658 case CONST_CAST_EXPR:
5659 case STATIC_CAST_EXPR:
5660 case REINTERPRET_CAST_EXPR:
5661 case IMPLICIT_CONV_EXPR:
5662 if (cxx_dialect < cxx11
5663 && !dependent_type_p (TREE_TYPE (t))
5664 && !INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t)))
5665 /* In C++98, a conversion to non-integral type can't be part of a
5666 constant expression. */
5668 if (flags & tf_error)
5669 error_at (loc,
5670 "cast to non-integral type %qT in a constant expression",
5671 TREE_TYPE (t));
5672 return false;
5675 return (RECUR (TREE_OPERAND (t, 0),
5676 TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE));
5678 case BIND_EXPR:
5679 return RECUR (BIND_EXPR_BODY (t), want_rval);
5681 case CLEANUP_POINT_EXPR:
5682 case MUST_NOT_THROW_EXPR:
5683 case TRY_CATCH_EXPR:
5684 case TRY_BLOCK:
5685 case EH_SPEC_BLOCK:
5686 case EXPR_STMT:
5687 case PAREN_EXPR:
5688 case NON_DEPENDENT_EXPR:
5689 /* For convenience. */
5690 case RETURN_EXPR:
5691 case LOOP_EXPR:
5692 case EXIT_EXPR:
5693 return RECUR (TREE_OPERAND (t, 0), want_rval);
5695 case DECL_EXPR:
5696 tmp = DECL_EXPR_DECL (t);
5697 if (VAR_P (tmp) && !DECL_ARTIFICIAL (tmp))
5699 if (TREE_STATIC (tmp))
5701 if (flags & tf_error)
5702 error_at (DECL_SOURCE_LOCATION (tmp), "%qD declared "
5703 "%<static%> in %<constexpr%> context", tmp);
5704 return false;
5706 else if (CP_DECL_THREAD_LOCAL_P (tmp))
5708 if (flags & tf_error)
5709 error_at (DECL_SOURCE_LOCATION (tmp), "%qD declared "
5710 "%<thread_local%> in %<constexpr%> context", tmp);
5711 return false;
5713 else if (!DECL_NONTRIVIALLY_INITIALIZED_P (tmp))
5715 if (flags & tf_error)
5716 error_at (DECL_SOURCE_LOCATION (tmp), "uninitialized "
5717 "variable %qD in %<constexpr%> context", tmp);
5718 return false;
5721 return RECUR (tmp, want_rval);
5723 case TRY_FINALLY_EXPR:
5724 return (RECUR (TREE_OPERAND (t, 0), want_rval)
5725 && RECUR (TREE_OPERAND (t, 1), any));
5727 case SCOPE_REF:
5728 return RECUR (TREE_OPERAND (t, 1), want_rval);
5730 case TARGET_EXPR:
5731 if (!literal_type_p (TREE_TYPE (t)))
5733 if (flags & tf_error)
5735 error_at (loc, "temporary of non-literal type %qT in a "
5736 "constant expression", TREE_TYPE (t));
5737 explain_non_literal_class (TREE_TYPE (t));
5739 return false;
5741 /* FALLTHRU */
5742 case INIT_EXPR:
5743 return RECUR (TREE_OPERAND (t, 1), rval);
5745 case CONSTRUCTOR:
5747 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
5748 constructor_elt *ce;
5749 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
5750 if (!RECUR (ce->value, want_rval))
5751 return false;
5752 return true;
5755 case TREE_LIST:
5757 gcc_assert (TREE_PURPOSE (t) == NULL_TREE
5758 || DECL_P (TREE_PURPOSE (t)));
5759 if (!RECUR (TREE_VALUE (t), want_rval))
5760 return false;
5761 if (TREE_CHAIN (t) == NULL_TREE)
5762 return true;
5763 return RECUR (TREE_CHAIN (t), want_rval);
5766 case TRUNC_DIV_EXPR:
5767 case CEIL_DIV_EXPR:
5768 case FLOOR_DIV_EXPR:
5769 case ROUND_DIV_EXPR:
5770 case TRUNC_MOD_EXPR:
5771 case CEIL_MOD_EXPR:
5772 case ROUND_MOD_EXPR:
5774 tree denom = TREE_OPERAND (t, 1);
5775 if (!RECUR (denom, rval))
5776 return false;
5777 /* We can't call cxx_eval_outermost_constant_expr on an expression
5778 that hasn't been through instantiate_non_dependent_expr yet. */
5779 if (!processing_template_decl)
5780 denom = cxx_eval_outermost_constant_expr (denom, true);
5781 if (integer_zerop (denom))
5783 if (flags & tf_error)
5784 error ("division by zero is not a constant expression");
5785 return false;
5787 else
5789 want_rval = true;
5790 return RECUR (TREE_OPERAND (t, 0), want_rval);
5794 case COMPOUND_EXPR:
5796 /* check_return_expr sometimes wraps a TARGET_EXPR in a
5797 COMPOUND_EXPR; don't get confused. Also handle EMPTY_CLASS_EXPR
5798 introduced by build_call_a. */
5799 tree op0 = TREE_OPERAND (t, 0);
5800 tree op1 = TREE_OPERAND (t, 1);
5801 STRIP_NOPS (op1);
5802 if ((TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
5803 || TREE_CODE (op1) == EMPTY_CLASS_EXPR)
5804 return RECUR (op0, want_rval);
5805 else
5806 goto binary;
5809 /* If the first operand is the non-short-circuit constant, look at
5810 the second operand; otherwise we only care about the first one for
5811 potentiality. */
5812 case TRUTH_AND_EXPR:
5813 case TRUTH_ANDIF_EXPR:
5814 tmp = boolean_true_node;
5815 goto truth;
5816 case TRUTH_OR_EXPR:
5817 case TRUTH_ORIF_EXPR:
5818 tmp = boolean_false_node;
5819 truth:
5821 tree op = TREE_OPERAND (t, 0);
5822 if (!RECUR (op, rval))
5823 return false;
5824 if (!processing_template_decl)
5825 op = cxx_eval_outermost_constant_expr (op, true);
5826 if (tree_int_cst_equal (op, tmp))
5827 return RECUR (TREE_OPERAND (t, 1), rval);
5828 else
5829 return true;
5832 case PLUS_EXPR:
5833 case MULT_EXPR:
5834 case POINTER_PLUS_EXPR:
5835 case RDIV_EXPR:
5836 case EXACT_DIV_EXPR:
5837 case MIN_EXPR:
5838 case MAX_EXPR:
5839 case LSHIFT_EXPR:
5840 case RSHIFT_EXPR:
5841 case LROTATE_EXPR:
5842 case RROTATE_EXPR:
5843 case BIT_IOR_EXPR:
5844 case BIT_XOR_EXPR:
5845 case BIT_AND_EXPR:
5846 case TRUTH_XOR_EXPR:
5847 case UNORDERED_EXPR:
5848 case ORDERED_EXPR:
5849 case UNLT_EXPR:
5850 case UNLE_EXPR:
5851 case UNGT_EXPR:
5852 case UNGE_EXPR:
5853 case UNEQ_EXPR:
5854 case LTGT_EXPR:
5855 case RANGE_EXPR:
5856 case COMPLEX_EXPR:
5857 want_rval = true;
5858 /* Fall through. */
5859 case ARRAY_REF:
5860 case ARRAY_RANGE_REF:
5861 case MEMBER_REF:
5862 case DOTSTAR_EXPR:
5863 case MEM_REF:
5864 case BINARY_LEFT_FOLD_EXPR:
5865 case BINARY_RIGHT_FOLD_EXPR:
5866 binary:
5867 for (i = 0; i < 2; ++i)
5868 if (!RECUR (TREE_OPERAND (t, i), want_rval))
5869 return false;
5870 return true;
5872 case FMA_EXPR:
5873 case VEC_PERM_EXPR:
5874 for (i = 0; i < 3; ++i)
5875 if (!RECUR (TREE_OPERAND (t, i), true))
5876 return false;
5877 return true;
5879 case COND_EXPR:
5880 if (COND_EXPR_IS_VEC_DELETE (t))
5882 if (flags & tf_error)
5883 error_at (loc, "%<delete[]%> is not a constant expression");
5884 return false;
5886 /* Fall through. */
5887 case IF_STMT:
5888 case VEC_COND_EXPR:
5889 /* If the condition is a known constant, we know which of the legs we
5890 care about; otherwise we only require that the condition and
5891 either of the legs be potentially constant. */
5892 tmp = TREE_OPERAND (t, 0);
5893 if (!RECUR (tmp, rval))
5894 return false;
5895 if (!processing_template_decl)
5896 tmp = cxx_eval_outermost_constant_expr (tmp, true);
5897 if (integer_zerop (tmp))
5898 return RECUR (TREE_OPERAND (t, 2), want_rval);
5899 else if (TREE_CODE (tmp) == INTEGER_CST)
5900 return RECUR (TREE_OPERAND (t, 1), want_rval);
5901 for (i = 1; i < 3; ++i)
5902 if (potential_constant_expression_1 (TREE_OPERAND (t, i),
5903 want_rval, strict, now, tf_none))
5904 return true;
5905 if (flags & tf_error)
5906 error_at (loc, "expression %qE is not a constant expression", t);
5907 return false;
5909 case VEC_INIT_EXPR:
5910 if (VEC_INIT_EXPR_IS_CONSTEXPR (t))
5911 return true;
5912 if (flags & tf_error)
5914 error_at (loc, "non-constant array initialization");
5915 diagnose_non_constexpr_vec_init (t);
5917 return false;
5919 case TYPE_DECL:
5920 case TAG_DEFN:
5921 /* We can see these in statement-expressions. */
5922 return true;
5924 case CLEANUP_STMT:
5925 case EMPTY_CLASS_EXPR:
5926 case PREDICT_EXPR:
5927 return false;
5929 case GOTO_EXPR:
5931 tree *target = &TREE_OPERAND (t, 0);
5932 /* Gotos representing break and continue are OK. */
5933 if (breaks (target) || continues (target))
5934 return true;
5935 if (flags & tf_error)
5936 error_at (loc, "%<goto%> is not a constant expression");
5937 return false;
5940 case ANNOTATE_EXPR:
5941 return RECUR (TREE_OPERAND (t, 0), rval);
5943 default:
5944 if (objc_is_property_ref (t))
5945 return false;
5947 sorry ("unexpected AST of kind %s", get_tree_code_name (TREE_CODE (t)));
5948 gcc_unreachable ();
5949 return false;
5951 #undef RECUR
5954 /* The main entry point to the above. */
5956 bool
5957 potential_constant_expression (tree t)
5959 return potential_constant_expression_1 (t, false, true, false, tf_none);
5962 /* As above, but require a constant rvalue. */
5964 bool
5965 potential_rvalue_constant_expression (tree t)
5967 return potential_constant_expression_1 (t, true, true, false, tf_none);
5970 /* Like above, but complain about non-constant expressions. */
5972 bool
5973 require_potential_constant_expression (tree t)
5975 return potential_constant_expression_1 (t, false, true, false, tf_warning_or_error);
5978 /* Cross product of the above. */
5980 bool
5981 require_potential_rvalue_constant_expression (tree t)
5983 return potential_constant_expression_1 (t, true, true, false, tf_warning_or_error);
5986 /* Like potential_constant_expression, but don't consider possible constexpr
5987 substitution of the current function. That is, PARM_DECL qualifies under
5988 potential_constant_expression, but not here.
5990 This is basically what you can check when any actual constant values might
5991 be value-dependent. */
5993 bool
5994 is_constant_expression (tree t)
5996 return potential_constant_expression_1 (t, false, true, true, tf_none);
5999 /* Like above, but complain about non-constant expressions. */
6001 bool
6002 require_constant_expression (tree t)
6004 return potential_constant_expression_1 (t, false, true, true,
6005 tf_warning_or_error);
6008 /* Like is_constant_expression, but allow const variables that are not allowed
6009 under constexpr rules. */
6011 bool
6012 is_static_init_expression (tree t)
6014 return potential_constant_expression_1 (t, false, false, true, tf_none);
6017 /* Returns true if T is a potential constant expression that is not
6018 instantiation-dependent, and therefore a candidate for constant folding even
6019 in a template. */
6021 bool
6022 is_nondependent_constant_expression (tree t)
6024 return (!type_unknown_p (t)
6025 && !BRACE_ENCLOSED_INITIALIZER_P (t)
6026 && is_constant_expression (t)
6027 && !instantiation_dependent_expression_p (t));
6030 /* Returns true if T is a potential static initializer expression that is not
6031 instantiation-dependent. */
6033 bool
6034 is_nondependent_static_init_expression (tree t)
6036 return (!type_unknown_p (t)
6037 && !BRACE_ENCLOSED_INITIALIZER_P (t)
6038 && is_static_init_expression (t)
6039 && !instantiation_dependent_expression_p (t));
6042 /* Finalize constexpr processing after parsing. */
6044 void
6045 fini_constexpr (void)
6047 /* The contexpr call and fundef copies tables are no longer needed. */
6048 constexpr_call_table = NULL;
6049 fundef_copies_table = NULL;
6052 #include "gt-cp-constexpr.h"