Various small C++ fixes.
[official-gcc.git] / gcc / cp / constexpr.c
blobf279f707676c2f3411d758082d7db58e3b7bc67e
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 is not literal",
98 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 return true;
460 default:
461 return false;
465 /* Make sure that there are no statements after LAST in the constructor
466 body represented by LIST. */
468 bool
469 check_constexpr_ctor_body (tree last, tree list, bool complain)
471 /* C++14 doesn't require a constexpr ctor to have an empty body. */
472 if (cxx_dialect >= cxx14)
473 return true;
475 bool ok = true;
476 if (TREE_CODE (list) == STATEMENT_LIST)
478 tree_stmt_iterator i = tsi_last (list);
479 for (; !tsi_end_p (i); tsi_prev (&i))
481 tree t = tsi_stmt (i);
482 if (t == last)
483 break;
484 if (!check_constexpr_ctor_body_1 (last, t))
486 ok = false;
487 break;
491 else if (list != last
492 && !check_constexpr_ctor_body_1 (last, list))
493 ok = false;
494 if (!ok)
496 if (complain)
497 error ("constexpr constructor does not have empty body");
498 DECL_DECLARED_CONSTEXPR_P (current_function_decl) = false;
500 return ok;
503 /* V is a vector of constructor elements built up for the base and member
504 initializers of a constructor for TYPE. They need to be in increasing
505 offset order, which they might not be yet if TYPE has a primary base
506 which is not first in the base-clause or a vptr and at least one base
507 all of which are non-primary. */
509 static vec<constructor_elt, va_gc> *
510 sort_constexpr_mem_initializers (tree type, vec<constructor_elt, va_gc> *v)
512 tree pri = CLASSTYPE_PRIMARY_BINFO (type);
513 tree field_type;
514 unsigned i;
515 constructor_elt *ce;
517 if (pri)
518 field_type = BINFO_TYPE (pri);
519 else if (TYPE_CONTAINS_VPTR_P (type))
520 field_type = vtbl_ptr_type_node;
521 else
522 return v;
524 /* Find the element for the primary base or vptr and move it to the
525 beginning of the vec. */
526 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
527 if (TREE_TYPE (ce->index) == field_type)
528 break;
530 if (i > 0 && i < vec_safe_length (v))
532 vec<constructor_elt, va_gc> &vref = *v;
533 constructor_elt elt = vref[i];
534 for (; i > 0; --i)
535 vref[i] = vref[i-1];
536 vref[0] = elt;
539 return v;
542 /* Build compile-time evalable representations of member-initializer list
543 for a constexpr constructor. */
545 static tree
546 build_constexpr_constructor_member_initializers (tree type, tree body)
548 vec<constructor_elt, va_gc> *vec = NULL;
549 bool ok = true;
550 while (true)
551 switch (TREE_CODE (body))
553 case MUST_NOT_THROW_EXPR:
554 case EH_SPEC_BLOCK:
555 body = TREE_OPERAND (body, 0);
556 break;
558 case STATEMENT_LIST:
559 for (tree_stmt_iterator i = tsi_start (body);
560 !tsi_end_p (i); tsi_next (&i))
562 body = tsi_stmt (i);
563 if (TREE_CODE (body) == BIND_EXPR)
564 break;
566 break;
568 case BIND_EXPR:
569 body = BIND_EXPR_BODY (body);
570 goto found;
572 default:
573 gcc_unreachable ();
575 found:
576 if (TREE_CODE (body) == CLEANUP_POINT_EXPR)
578 body = TREE_OPERAND (body, 0);
579 if (TREE_CODE (body) == EXPR_STMT)
580 body = TREE_OPERAND (body, 0);
581 if (TREE_CODE (body) == INIT_EXPR
582 && (same_type_ignoring_top_level_qualifiers_p
583 (TREE_TYPE (TREE_OPERAND (body, 0)),
584 current_class_type)))
586 /* Trivial copy. */
587 return TREE_OPERAND (body, 1);
589 ok = build_data_member_initialization (body, &vec);
591 else if (TREE_CODE (body) == STATEMENT_LIST)
593 tree_stmt_iterator i;
594 for (i = tsi_start (body); !tsi_end_p (i); tsi_next (&i))
596 ok = build_data_member_initialization (tsi_stmt (i), &vec);
597 if (!ok)
598 break;
601 else if (TREE_CODE (body) == TRY_BLOCK)
603 error ("body of %<constexpr%> constructor cannot be "
604 "a function-try-block");
605 return error_mark_node;
607 else if (EXPR_P (body))
608 ok = build_data_member_initialization (body, &vec);
609 else
610 gcc_assert (errorcount > 0);
611 if (ok)
613 if (vec_safe_length (vec) > 0)
615 /* In a delegating constructor, return the target. */
616 constructor_elt *ce = &(*vec)[0];
617 if (ce->index == current_class_ptr)
619 body = ce->value;
620 vec_free (vec);
621 return body;
624 vec = sort_constexpr_mem_initializers (type, vec);
625 return build_constructor (type, vec);
627 else
628 return error_mark_node;
631 /* Subroutine of register_constexpr_fundef. BODY is the body of a function
632 declared to be constexpr, or a sub-statement thereof. Returns the
633 return value if suitable, error_mark_node for a statement not allowed in
634 a constexpr function, or NULL_TREE if no return value was found. */
636 static tree
637 constexpr_fn_retval (tree body)
639 switch (TREE_CODE (body))
641 case STATEMENT_LIST:
643 tree_stmt_iterator i;
644 tree expr = NULL_TREE;
645 for (i = tsi_start (body); !tsi_end_p (i); tsi_next (&i))
647 tree s = constexpr_fn_retval (tsi_stmt (i));
648 if (s == error_mark_node)
649 return error_mark_node;
650 else if (s == NULL_TREE)
651 /* Keep iterating. */;
652 else if (expr)
653 /* Multiple return statements. */
654 return error_mark_node;
655 else
656 expr = s;
658 return expr;
661 case RETURN_EXPR:
662 return break_out_target_exprs (TREE_OPERAND (body, 0));
664 case DECL_EXPR:
666 tree decl = DECL_EXPR_DECL (body);
667 if (TREE_CODE (decl) == USING_DECL
668 /* Accept __func__, __FUNCTION__, and __PRETTY_FUNCTION__. */
669 || DECL_ARTIFICIAL (decl))
670 return NULL_TREE;
671 return error_mark_node;
674 case CLEANUP_POINT_EXPR:
675 return constexpr_fn_retval (TREE_OPERAND (body, 0));
677 case BIND_EXPR:
678 if (!check_constexpr_bind_expr_vars (body))
679 return error_mark_node;
680 return constexpr_fn_retval (BIND_EXPR_BODY (body));
682 case USING_STMT:
683 return NULL_TREE;
685 default:
686 return error_mark_node;
690 /* Subroutine of register_constexpr_fundef. BODY is the DECL_SAVED_TREE of
691 FUN; do the necessary transformations to turn it into a single expression
692 that we can store in the hash table. */
694 static tree
695 massage_constexpr_body (tree fun, tree body)
697 if (DECL_CONSTRUCTOR_P (fun))
698 body = build_constexpr_constructor_member_initializers
699 (DECL_CONTEXT (fun), body);
700 else if (cxx_dialect < cxx14)
702 if (TREE_CODE (body) == EH_SPEC_BLOCK)
703 body = EH_SPEC_STMTS (body);
704 if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
705 body = TREE_OPERAND (body, 0);
706 body = constexpr_fn_retval (body);
708 return body;
711 /* CTYPE is a type constructed from BODY. Return true if some
712 bases/fields are uninitialized, and complain if COMPLAIN. */
714 static bool
715 cx_check_missing_mem_inits (tree ctype, tree body, bool complain)
717 unsigned nelts = 0;
719 if (body)
721 if (TREE_CODE (body) != CONSTRUCTOR)
722 return false;
723 nelts = CONSTRUCTOR_NELTS (body);
725 tree field = TYPE_FIELDS (ctype);
727 if (TREE_CODE (ctype) == UNION_TYPE)
729 if (nelts == 0 && next_initializable_field (field))
731 if (complain)
732 error ("%<constexpr%> constructor for union %qT must "
733 "initialize exactly one non-static data member", ctype);
734 return true;
736 return false;
739 /* Iterate over the CONSTRUCTOR, checking any missing fields don't
740 need an explicit initialization. */
741 bool bad = false;
742 for (unsigned i = 0; i <= nelts; ++i)
744 tree index = NULL_TREE;
745 if (i < nelts)
747 index = CONSTRUCTOR_ELT (body, i)->index;
748 /* Skip base and vtable inits. */
749 if (TREE_CODE (index) != FIELD_DECL
750 || DECL_ARTIFICIAL (index))
751 continue;
754 for (; field != index; field = DECL_CHAIN (field))
756 tree ftype;
757 if (TREE_CODE (field) != FIELD_DECL)
758 continue;
759 if (DECL_C_BIT_FIELD (field) && !DECL_NAME (field))
760 continue;
761 if (DECL_ARTIFICIAL (field))
762 continue;
763 if (ANON_AGGR_TYPE_P (TREE_TYPE (field)))
765 /* Recurse to check the anonummous aggregate member. */
766 bad |= cx_check_missing_mem_inits
767 (TREE_TYPE (field), NULL_TREE, complain);
768 if (bad && !complain)
769 return true;
770 continue;
772 ftype = strip_array_types (TREE_TYPE (field));
773 if (type_has_constexpr_default_constructor (ftype))
775 /* It's OK to skip a member with a trivial constexpr ctor.
776 A constexpr ctor that isn't trivial should have been
777 added in by now. */
778 gcc_checking_assert (!TYPE_HAS_COMPLEX_DFLT (ftype)
779 || errorcount != 0);
780 continue;
782 if (!complain)
783 return true;
784 error ("member %qD must be initialized by mem-initializer "
785 "in %<constexpr%> constructor", field);
786 inform (DECL_SOURCE_LOCATION (field), "declared here");
787 bad = true;
789 if (field == NULL_TREE)
790 break;
792 if (ANON_AGGR_TYPE_P (TREE_TYPE (index)))
794 /* Check the anonymous aggregate initializer is valid. */
795 bad |= cx_check_missing_mem_inits
796 (TREE_TYPE (index), CONSTRUCTOR_ELT (body, i)->value, complain);
797 if (bad && !complain)
798 return true;
800 field = DECL_CHAIN (field);
803 return bad;
806 /* We are processing the definition of the constexpr function FUN.
807 Check that its BODY fulfills the propriate requirements and
808 enter it in the constexpr function definition table.
809 For constructor BODY is actually the TREE_LIST of the
810 member-initializer list. */
812 tree
813 register_constexpr_fundef (tree fun, tree body)
815 constexpr_fundef entry;
816 constexpr_fundef **slot;
818 if (!is_valid_constexpr_fn (fun, !DECL_GENERATED_P (fun)))
819 return NULL;
821 tree massaged = massage_constexpr_body (fun, body);
822 if (massaged == NULL_TREE || massaged == error_mark_node)
824 if (!DECL_CONSTRUCTOR_P (fun))
825 error ("body of constexpr function %qD not a return-statement", fun);
826 return NULL;
829 if (!potential_rvalue_constant_expression (massaged))
831 if (!DECL_GENERATED_P (fun))
832 require_potential_rvalue_constant_expression (massaged);
833 return NULL;
836 if (DECL_CONSTRUCTOR_P (fun)
837 && cx_check_missing_mem_inits (DECL_CONTEXT (fun),
838 massaged, !DECL_GENERATED_P (fun)))
839 return NULL;
841 /* Create the constexpr function table if necessary. */
842 if (constexpr_fundef_table == NULL)
843 constexpr_fundef_table
844 = hash_table<constexpr_fundef_hasher>::create_ggc (101);
846 entry.decl = fun;
847 entry.body = body;
848 slot = constexpr_fundef_table->find_slot (&entry, INSERT);
850 gcc_assert (*slot == NULL);
851 *slot = ggc_alloc<constexpr_fundef> ();
852 **slot = entry;
854 return fun;
857 /* FUN is a non-constexpr function called in a context that requires a
858 constant expression. If it comes from a constexpr template, explain why
859 the instantiation isn't constexpr. */
861 void
862 explain_invalid_constexpr_fn (tree fun)
864 static hash_set<tree> *diagnosed;
865 tree body;
866 location_t save_loc;
867 /* Only diagnose defaulted functions, lambdas, or instantiations. */
868 if (!DECL_DEFAULTED_FN (fun)
869 && !LAMBDA_TYPE_P (CP_DECL_CONTEXT (fun))
870 && !is_instantiation_of_constexpr (fun))
871 return;
872 if (diagnosed == NULL)
873 diagnosed = new hash_set<tree>;
874 if (diagnosed->add (fun))
875 /* Already explained. */
876 return;
878 save_loc = input_location;
879 if (!lambda_static_thunk_p (fun))
881 /* Diagnostics should completely ignore the static thunk, so leave
882 input_location set to our caller's location. */
883 input_location = DECL_SOURCE_LOCATION (fun);
884 inform (input_location,
885 "%qD is not usable as a constexpr function because:", fun);
887 /* First check the declaration. */
888 if (is_valid_constexpr_fn (fun, true))
890 /* Then if it's OK, the body. */
891 if (!DECL_DECLARED_CONSTEXPR_P (fun)
892 && !LAMBDA_TYPE_P (CP_DECL_CONTEXT (fun)))
893 explain_implicit_non_constexpr (fun);
894 else
896 body = massage_constexpr_body (fun, DECL_SAVED_TREE (fun));
897 require_potential_rvalue_constant_expression (body);
898 if (DECL_CONSTRUCTOR_P (fun))
899 cx_check_missing_mem_inits (DECL_CONTEXT (fun), body, true);
902 input_location = save_loc;
905 /* Objects of this type represent calls to constexpr functions
906 along with the bindings of parameters to their arguments, for
907 the purpose of compile time evaluation. */
909 struct GTY((for_user)) constexpr_call {
910 /* Description of the constexpr function definition. */
911 constexpr_fundef *fundef;
912 /* Parameter bindings environment. A TREE_LIST where each TREE_PURPOSE
913 is a parameter _DECL and the TREE_VALUE is the value of the parameter.
914 Note: This arrangement is made to accommodate the use of
915 iterative_hash_template_arg (see pt.c). If you change this
916 representation, also change the hash calculation in
917 cxx_eval_call_expression. */
918 tree bindings;
919 /* Result of the call.
920 NULL means the call is being evaluated.
921 error_mark_node means that the evaluation was erroneous;
922 otherwise, the actuall value of the call. */
923 tree result;
924 /* The hash of this call; we remember it here to avoid having to
925 recalculate it when expanding the hash table. */
926 hashval_t hash;
929 struct constexpr_call_hasher : ggc_ptr_hash<constexpr_call>
931 static hashval_t hash (constexpr_call *);
932 static bool equal (constexpr_call *, constexpr_call *);
935 enum constexpr_switch_state {
936 /* Used when processing a switch for the first time by cxx_eval_switch_expr
937 and default: label for that switch has not been seen yet. */
938 css_default_not_seen,
939 /* Used when processing a switch for the first time by cxx_eval_switch_expr
940 and default: label for that switch has been seen already. */
941 css_default_seen,
942 /* Used when processing a switch for the second time by
943 cxx_eval_switch_expr, where default: label should match. */
944 css_default_processing
947 /* The constexpr expansion context. CALL is the current function
948 expansion, CTOR is the current aggregate initializer, OBJECT is the
949 object being initialized by CTOR, either a VAR_DECL or a _REF. VALUES
950 is a map of values of variables initialized within the expression. */
952 struct constexpr_ctx {
953 /* The innermost call we're evaluating. */
954 constexpr_call *call;
955 /* Values for any temporaries or local variables within the
956 constant-expression. */
957 hash_map<tree,tree> *values;
958 /* SAVE_EXPRs that we've seen within the current LOOP_EXPR. NULL if we
959 aren't inside a loop. */
960 hash_set<tree> *save_exprs;
961 /* The CONSTRUCTOR we're currently building up for an aggregate
962 initializer. */
963 tree ctor;
964 /* The object we're building the CONSTRUCTOR for. */
965 tree object;
966 /* If inside SWITCH_EXPR. */
967 constexpr_switch_state *css_state;
968 /* Whether we should error on a non-constant expression or fail quietly. */
969 bool quiet;
970 /* Whether we are strictly conforming to constant expression rules or
971 trying harder to get a constant value. */
972 bool strict;
975 /* A table of all constexpr calls that have been evaluated by the
976 compiler in this translation unit. */
978 static GTY (()) hash_table<constexpr_call_hasher> *constexpr_call_table;
980 static tree cxx_eval_constant_expression (const constexpr_ctx *, tree,
981 bool, bool *, bool *, tree * = NULL);
983 /* Compute a hash value for a constexpr call representation. */
985 inline hashval_t
986 constexpr_call_hasher::hash (constexpr_call *info)
988 return info->hash;
991 /* Return true if the objects pointed to by P and Q represent calls
992 to the same constexpr function with the same arguments.
993 Otherwise, return false. */
995 bool
996 constexpr_call_hasher::equal (constexpr_call *lhs, constexpr_call *rhs)
998 tree lhs_bindings;
999 tree rhs_bindings;
1000 if (lhs == rhs)
1001 return 1;
1002 if (!constexpr_fundef_hasher::equal (lhs->fundef, rhs->fundef))
1003 return 0;
1004 lhs_bindings = lhs->bindings;
1005 rhs_bindings = rhs->bindings;
1006 while (lhs_bindings != NULL && rhs_bindings != NULL)
1008 tree lhs_arg = TREE_VALUE (lhs_bindings);
1009 tree rhs_arg = TREE_VALUE (rhs_bindings);
1010 gcc_assert (TREE_TYPE (lhs_arg) == TREE_TYPE (rhs_arg));
1011 if (!cp_tree_equal (lhs_arg, rhs_arg))
1012 return 0;
1013 lhs_bindings = TREE_CHAIN (lhs_bindings);
1014 rhs_bindings = TREE_CHAIN (rhs_bindings);
1016 return lhs_bindings == rhs_bindings;
1019 /* Initialize the constexpr call table, if needed. */
1021 static void
1022 maybe_initialize_constexpr_call_table (void)
1024 if (constexpr_call_table == NULL)
1025 constexpr_call_table = hash_table<constexpr_call_hasher>::create_ggc (101);
1028 /* During constexpr CALL_EXPR evaluation, to avoid issues with sharing when
1029 a function happens to get called recursively, we unshare the callee
1030 function's body and evaluate this unshared copy instead of evaluating the
1031 original body.
1033 FUNDEF_COPIES_TABLE is a per-function freelist of these unshared function
1034 copies. The underlying data structure of FUNDEF_COPIES_TABLE is a hash_map
1035 that's keyed off of the original FUNCTION_DECL and whose value is a
1036 TREE_LIST of this function's unused copies awaiting reuse.
1038 This is not GC-deletable to avoid GC affecting UID generation. */
1040 static GTY(()) hash_map<tree, tree> *fundef_copies_table;
1042 /* Initialize FUNDEF_COPIES_TABLE if it's not initialized. */
1044 static void
1045 maybe_initialize_fundef_copies_table ()
1047 if (fundef_copies_table == NULL)
1048 fundef_copies_table = hash_map<tree,tree>::create_ggc (101);
1051 /* Reuse a copy or create a new unshared copy of the function FUN.
1052 Return this copy. We use a TREE_LIST whose PURPOSE is body, VALUE
1053 is parms, TYPE is result. */
1055 static tree
1056 get_fundef_copy (tree fun)
1058 maybe_initialize_fundef_copies_table ();
1060 tree copy;
1061 bool existed;
1062 tree *slot = &fundef_copies_table->get_or_insert (fun, &existed);
1064 if (!existed)
1066 /* There is no cached function available, or in use. We can use
1067 the function directly. That the slot is now created records
1068 that this function is now in use. */
1069 copy = build_tree_list (DECL_SAVED_TREE (fun), DECL_ARGUMENTS (fun));
1070 TREE_TYPE (copy) = DECL_RESULT (fun);
1072 else if (*slot == NULL_TREE)
1074 /* We've already used the function itself, so make a copy. */
1075 copy = build_tree_list (NULL, NULL);
1076 TREE_PURPOSE (copy) = copy_fn (fun, TREE_VALUE (copy), TREE_TYPE (copy));
1078 else
1080 /* We have a cached function available. */
1081 copy = *slot;
1082 *slot = TREE_CHAIN (copy);
1085 return copy;
1088 /* Save the copy COPY of function FUN for later reuse by
1089 get_fundef_copy(). By construction, there will always be an entry
1090 to find. */
1092 static void
1093 save_fundef_copy (tree fun, tree copy)
1095 tree *slot = fundef_copies_table->get (fun);
1096 TREE_CHAIN (copy) = *slot;
1097 *slot = copy;
1100 /* We have an expression tree T that represents a call, either CALL_EXPR
1101 or AGGR_INIT_EXPR. If the call is lexically to a named function,
1102 retrun the _DECL for that function. */
1104 static tree
1105 get_function_named_in_call (tree t)
1107 tree fun = cp_get_callee (t);
1108 if (fun && TREE_CODE (fun) == ADDR_EXPR
1109 && TREE_CODE (TREE_OPERAND (fun, 0)) == FUNCTION_DECL)
1110 fun = TREE_OPERAND (fun, 0);
1111 return fun;
1114 /* We have an expression tree T that represents a call, either CALL_EXPR
1115 or AGGR_INIT_EXPR. Return the Nth argument. */
1117 static inline tree
1118 get_nth_callarg (tree t, int n)
1120 switch (TREE_CODE (t))
1122 case CALL_EXPR:
1123 return CALL_EXPR_ARG (t, n);
1125 case AGGR_INIT_EXPR:
1126 return AGGR_INIT_EXPR_ARG (t, n);
1128 default:
1129 gcc_unreachable ();
1130 return NULL;
1134 /* Attempt to evaluate T which represents a call to a builtin function.
1135 We assume here that all builtin functions evaluate to scalar types
1136 represented by _CST nodes. */
1138 static tree
1139 cxx_eval_builtin_function_call (const constexpr_ctx *ctx, tree t, tree fun,
1140 bool lval,
1141 bool *non_constant_p, bool *overflow_p)
1143 const int nargs = call_expr_nargs (t);
1144 tree *args = (tree *) alloca (nargs * sizeof (tree));
1145 tree new_call;
1146 int i;
1148 /* Don't fold __builtin_constant_p within a constexpr function. */
1149 bool bi_const_p = (DECL_FUNCTION_CODE (fun) == BUILT_IN_CONSTANT_P);
1151 if (bi_const_p
1152 && current_function_decl
1153 && DECL_DECLARED_CONSTEXPR_P (current_function_decl))
1155 *non_constant_p = true;
1156 return t;
1159 /* Be permissive for arguments to built-ins; __builtin_constant_p should
1160 return constant false for a non-constant argument. */
1161 constexpr_ctx new_ctx = *ctx;
1162 new_ctx.quiet = true;
1163 bool dummy1 = false, dummy2 = false;
1164 for (i = 0; i < nargs; ++i)
1166 args[i] = cxx_eval_constant_expression (&new_ctx, CALL_EXPR_ARG (t, i),
1167 false, &dummy1, &dummy2);
1168 if (bi_const_p)
1169 /* For __built_in_constant_p, fold all expressions with constant values
1170 even if they aren't C++ constant-expressions. */
1171 args[i] = cp_fully_fold (args[i]);
1174 bool save_ffbcp = force_folding_builtin_constant_p;
1175 force_folding_builtin_constant_p = true;
1176 new_call = fold_builtin_call_array (EXPR_LOCATION (t), TREE_TYPE (t),
1177 CALL_EXPR_FN (t), nargs, args);
1178 force_folding_builtin_constant_p = save_ffbcp;
1179 if (new_call == NULL)
1181 if (!*non_constant_p && !ctx->quiet)
1183 new_call = build_call_array_loc (EXPR_LOCATION (t), TREE_TYPE (t),
1184 CALL_EXPR_FN (t), nargs, args);
1185 error ("%q+E is not a constant expression", new_call);
1187 *non_constant_p = true;
1188 return t;
1191 if (!is_constant_expression (new_call))
1193 if (!*non_constant_p && !ctx->quiet)
1194 error ("%q+E is not a constant expression", new_call);
1195 *non_constant_p = true;
1196 return t;
1199 return cxx_eval_constant_expression (&new_ctx, new_call, lval,
1200 non_constant_p, overflow_p);
1203 /* TEMP is the constant value of a temporary object of type TYPE. Adjust
1204 the type of the value to match. */
1206 static tree
1207 adjust_temp_type (tree type, tree temp)
1209 if (TREE_TYPE (temp) == type)
1210 return temp;
1211 /* Avoid wrapping an aggregate value in a NOP_EXPR. */
1212 if (TREE_CODE (temp) == CONSTRUCTOR)
1213 return build_constructor (type, CONSTRUCTOR_ELTS (temp));
1214 gcc_assert (scalarish_type_p (type));
1215 return cp_fold_convert (type, temp);
1218 /* Callback for walk_tree used by unshare_constructor. */
1220 static tree
1221 find_constructor (tree *tp, int *walk_subtrees, void *)
1223 if (TYPE_P (*tp))
1224 *walk_subtrees = 0;
1225 if (TREE_CODE (*tp) == CONSTRUCTOR)
1226 return *tp;
1227 return NULL_TREE;
1230 /* If T is a CONSTRUCTOR or an expression that has a CONSTRUCTOR node as a
1231 subexpression, return an unshared copy of T. Otherwise return T. */
1233 static tree
1234 unshare_constructor (tree t)
1236 tree ctor = walk_tree (&t, find_constructor, NULL, NULL);
1237 if (ctor != NULL_TREE)
1238 return unshare_expr (t);
1239 return t;
1242 /* Subroutine of cxx_eval_call_expression.
1243 We are processing a call expression (either CALL_EXPR or
1244 AGGR_INIT_EXPR) in the context of CTX. Evaluate
1245 all arguments and bind their values to correspondings
1246 parameters, making up the NEW_CALL context. */
1248 static void
1249 cxx_bind_parameters_in_call (const constexpr_ctx *ctx, tree t,
1250 constexpr_call *new_call,
1251 bool *non_constant_p, bool *overflow_p,
1252 bool *non_constant_args)
1254 const int nargs = call_expr_nargs (t);
1255 tree fun = new_call->fundef->decl;
1256 tree parms = DECL_ARGUMENTS (fun);
1257 int i;
1258 tree *p = &new_call->bindings;
1259 for (i = 0; i < nargs; ++i)
1261 tree x, arg;
1262 tree type = parms ? TREE_TYPE (parms) : void_type_node;
1263 x = get_nth_callarg (t, i);
1264 /* For member function, the first argument is a pointer to the implied
1265 object. For a constructor, it might still be a dummy object, in
1266 which case we get the real argument from ctx. */
1267 if (i == 0 && DECL_CONSTRUCTOR_P (fun)
1268 && is_dummy_object (x))
1270 x = ctx->object;
1271 x = cp_build_addr_expr (x, tf_warning_or_error);
1273 bool lval = false;
1274 arg = cxx_eval_constant_expression (ctx, x, lval,
1275 non_constant_p, overflow_p);
1276 /* Don't VERIFY_CONSTANT here. */
1277 if (*non_constant_p && ctx->quiet)
1278 return;
1279 /* Just discard ellipsis args after checking their constantitude. */
1280 if (!parms)
1281 continue;
1283 if (!*non_constant_p)
1285 /* Make sure the binding has the same type as the parm. But
1286 only for constant args. */
1287 if (TREE_CODE (type) != REFERENCE_TYPE)
1288 arg = adjust_temp_type (type, arg);
1289 if (!TREE_CONSTANT (arg))
1290 *non_constant_args = true;
1291 *p = build_tree_list (parms, arg);
1292 p = &TREE_CHAIN (*p);
1294 parms = TREE_CHAIN (parms);
1298 /* Variables and functions to manage constexpr call expansion context.
1299 These do not need to be marked for PCH or GC. */
1301 /* FIXME remember and print actual constant arguments. */
1302 static vec<tree> call_stack;
1303 static int call_stack_tick;
1304 static int last_cx_error_tick;
1306 static bool
1307 push_cx_call_context (tree call)
1309 ++call_stack_tick;
1310 if (!EXPR_HAS_LOCATION (call))
1311 SET_EXPR_LOCATION (call, input_location);
1312 call_stack.safe_push (call);
1313 if (call_stack.length () > (unsigned) max_constexpr_depth)
1314 return false;
1315 return true;
1318 static void
1319 pop_cx_call_context (void)
1321 ++call_stack_tick;
1322 call_stack.pop ();
1325 vec<tree>
1326 cx_error_context (void)
1328 vec<tree> r = vNULL;
1329 if (call_stack_tick != last_cx_error_tick
1330 && !call_stack.is_empty ())
1331 r = call_stack;
1332 last_cx_error_tick = call_stack_tick;
1333 return r;
1336 /* Evaluate a call T to a GCC internal function when possible and return
1337 the evaluated result or, under the control of CTX, give an error, set
1338 NON_CONSTANT_P, and return the unevaluated call T otherwise. */
1340 static tree
1341 cxx_eval_internal_function (const constexpr_ctx *ctx, tree t,
1342 bool lval,
1343 bool *non_constant_p, bool *overflow_p)
1345 enum tree_code opcode = ERROR_MARK;
1347 switch (CALL_EXPR_IFN (t))
1349 case IFN_UBSAN_NULL:
1350 case IFN_UBSAN_BOUNDS:
1351 case IFN_UBSAN_VPTR:
1352 case IFN_FALLTHROUGH:
1353 return void_node;
1355 case IFN_ADD_OVERFLOW:
1356 opcode = PLUS_EXPR;
1357 break;
1358 case IFN_SUB_OVERFLOW:
1359 opcode = MINUS_EXPR;
1360 break;
1361 case IFN_MUL_OVERFLOW:
1362 opcode = MULT_EXPR;
1363 break;
1365 case IFN_LAUNDER:
1366 return cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0),
1367 false, non_constant_p, overflow_p);
1369 default:
1370 if (!ctx->quiet)
1371 error_at (EXPR_LOC_OR_LOC (t, input_location),
1372 "call to internal function %qE", t);
1373 *non_constant_p = true;
1374 return t;
1377 /* Evaluate constant arguments using OPCODE and return a complex
1378 number containing the result and the overflow bit. */
1379 tree arg0 = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 0), lval,
1380 non_constant_p, overflow_p);
1381 tree arg1 = cxx_eval_constant_expression (ctx, CALL_EXPR_ARG (t, 1), lval,
1382 non_constant_p, overflow_p);
1384 if (TREE_CODE (arg0) == INTEGER_CST && TREE_CODE (arg1) == INTEGER_CST)
1386 location_t loc = EXPR_LOC_OR_LOC (t, input_location);
1387 tree type = TREE_TYPE (TREE_TYPE (t));
1388 tree result = fold_binary_loc (loc, opcode, type,
1389 fold_convert_loc (loc, type, arg0),
1390 fold_convert_loc (loc, type, arg1));
1391 tree ovf
1392 = build_int_cst (type, arith_overflowed_p (opcode, type, arg0, arg1));
1393 /* Reset TREE_OVERFLOW to avoid warnings for the overflow. */
1394 if (TREE_OVERFLOW (result))
1395 TREE_OVERFLOW (result) = 0;
1397 return build_complex (TREE_TYPE (t), result, ovf);
1400 *non_constant_p = true;
1401 return t;
1404 /* Clean CONSTRUCTOR_NO_IMPLICIT_ZERO from CTOR and its sub-aggregates. */
1406 static void
1407 clear_no_implicit_zero (tree ctor)
1409 if (CONSTRUCTOR_NO_IMPLICIT_ZERO (ctor))
1411 CONSTRUCTOR_NO_IMPLICIT_ZERO (ctor) = false;
1412 tree elt; unsigned HOST_WIDE_INT idx;
1413 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (ctor), idx, elt)
1414 if (TREE_CODE (elt) == CONSTRUCTOR)
1415 clear_no_implicit_zero (elt);
1419 /* Subroutine of cxx_eval_constant_expression.
1420 Evaluate the call expression tree T in the context of OLD_CALL expression
1421 evaluation. */
1423 static tree
1424 cxx_eval_call_expression (const constexpr_ctx *ctx, tree t,
1425 bool lval,
1426 bool *non_constant_p, bool *overflow_p)
1428 location_t loc = EXPR_LOC_OR_LOC (t, input_location);
1429 tree fun = get_function_named_in_call (t);
1430 constexpr_call new_call = { NULL, NULL, NULL, 0 };
1431 bool depth_ok;
1433 if (fun == NULL_TREE)
1434 return cxx_eval_internal_function (ctx, t, lval,
1435 non_constant_p, overflow_p);
1437 if (TREE_CODE (fun) != FUNCTION_DECL)
1439 /* Might be a constexpr function pointer. */
1440 fun = cxx_eval_constant_expression (ctx, fun,
1441 /*lval*/false, non_constant_p,
1442 overflow_p);
1443 STRIP_NOPS (fun);
1444 if (TREE_CODE (fun) == ADDR_EXPR)
1445 fun = TREE_OPERAND (fun, 0);
1447 if (TREE_CODE (fun) != FUNCTION_DECL)
1449 if (!ctx->quiet && !*non_constant_p)
1450 error_at (loc, "expression %qE does not designate a constexpr "
1451 "function", fun);
1452 *non_constant_p = true;
1453 return t;
1455 if (DECL_CLONED_FUNCTION_P (fun))
1456 fun = DECL_CLONED_FUNCTION (fun);
1458 if (is_ubsan_builtin_p (fun))
1459 return void_node;
1461 if (is_builtin_fn (fun))
1462 return cxx_eval_builtin_function_call (ctx, t, fun,
1463 lval, non_constant_p, overflow_p);
1464 if (!DECL_DECLARED_CONSTEXPR_P (fun))
1466 if (!ctx->quiet)
1468 if (!lambda_static_thunk_p (fun))
1469 error_at (loc, "call to non-constexpr function %qD", fun);
1470 explain_invalid_constexpr_fn (fun);
1472 *non_constant_p = true;
1473 return t;
1476 constexpr_ctx new_ctx = *ctx;
1477 if (DECL_CONSTRUCTOR_P (fun) && !ctx->object
1478 && TREE_CODE (t) == AGGR_INIT_EXPR)
1480 /* We want to have an initialization target for an AGGR_INIT_EXPR.
1481 If we don't already have one in CTX, use the AGGR_INIT_EXPR_SLOT. */
1482 new_ctx.object = AGGR_INIT_EXPR_SLOT (t);
1483 tree ctor = new_ctx.ctor = build_constructor (DECL_CONTEXT (fun), NULL);
1484 CONSTRUCTOR_NO_IMPLICIT_ZERO (ctor) = true;
1485 ctx->values->put (new_ctx.object, ctor);
1486 ctx = &new_ctx;
1489 /* Shortcut trivial constructor/op=. */
1490 if (trivial_fn_p (fun))
1492 tree init = NULL_TREE;
1493 if (call_expr_nargs (t) == 2)
1494 init = convert_from_reference (get_nth_callarg (t, 1));
1495 else if (TREE_CODE (t) == AGGR_INIT_EXPR
1496 && AGGR_INIT_ZERO_FIRST (t))
1497 init = build_zero_init (DECL_CONTEXT (fun), NULL_TREE, false);
1498 if (init)
1500 tree op = get_nth_callarg (t, 0);
1501 if (is_dummy_object (op))
1502 op = ctx->object;
1503 else
1504 op = build1 (INDIRECT_REF, TREE_TYPE (TREE_TYPE (op)), op);
1505 tree set = build2 (MODIFY_EXPR, TREE_TYPE (op), op, init);
1506 new_ctx.call = &new_call;
1507 return cxx_eval_constant_expression (&new_ctx, set, lval,
1508 non_constant_p, overflow_p);
1512 /* We can't defer instantiating the function any longer. */
1513 if (!DECL_INITIAL (fun)
1514 && DECL_TEMPLOID_INSTANTIATION (fun))
1516 location_t save_loc = input_location;
1517 input_location = loc;
1518 ++function_depth;
1519 instantiate_decl (fun, /*defer_ok*/false, /*expl_inst*/false);
1520 --function_depth;
1521 input_location = save_loc;
1524 /* If in direct recursive call, optimize definition search. */
1525 if (ctx && ctx->call && ctx->call->fundef && ctx->call->fundef->decl == fun)
1526 new_call.fundef = ctx->call->fundef;
1527 else
1529 new_call.fundef = retrieve_constexpr_fundef (fun);
1530 if (new_call.fundef == NULL || new_call.fundef->body == NULL
1531 || fun == current_function_decl)
1533 if (!ctx->quiet)
1535 /* We need to check for current_function_decl here in case we're
1536 being called during cp_fold_function, because at that point
1537 DECL_INITIAL is set properly and we have a fundef but we
1538 haven't lowered invisirefs yet (c++/70344). */
1539 if (DECL_INITIAL (fun) == error_mark_node
1540 || fun == current_function_decl)
1541 error_at (loc, "%qD called in a constant expression before its "
1542 "definition is complete", fun);
1543 else if (DECL_INITIAL (fun))
1545 /* The definition of fun was somehow unsuitable. But pretend
1546 that lambda static thunks don't exist. */
1547 if (!lambda_static_thunk_p (fun))
1548 error_at (loc, "%qD called in a constant expression", fun);
1549 explain_invalid_constexpr_fn (fun);
1551 else
1552 error_at (loc, "%qD used before its definition", fun);
1554 *non_constant_p = true;
1555 return t;
1559 bool non_constant_args = false;
1560 cxx_bind_parameters_in_call (ctx, t, &new_call,
1561 non_constant_p, overflow_p, &non_constant_args);
1562 if (*non_constant_p)
1563 return t;
1565 depth_ok = push_cx_call_context (t);
1567 tree result = NULL_TREE;
1569 constexpr_call *entry = NULL;
1570 if (depth_ok && !non_constant_args)
1572 new_call.hash = iterative_hash_template_arg
1573 (new_call.bindings, constexpr_fundef_hasher::hash (new_call.fundef));
1575 /* If we have seen this call before, we are done. */
1576 maybe_initialize_constexpr_call_table ();
1577 constexpr_call **slot
1578 = constexpr_call_table->find_slot (&new_call, INSERT);
1579 entry = *slot;
1580 if (entry == NULL)
1582 /* We need to keep a pointer to the entry, not just the slot, as the
1583 slot can move in the call to cxx_eval_builtin_function_call. */
1584 *slot = entry = ggc_alloc<constexpr_call> ();
1585 *entry = new_call;
1587 /* Calls that are in progress have their result set to NULL,
1588 so that we can detect circular dependencies. */
1589 else if (entry->result == NULL)
1591 if (!ctx->quiet)
1592 error ("call has circular dependency");
1593 *non_constant_p = true;
1594 entry->result = result = error_mark_node;
1596 else
1597 result = entry->result;
1600 if (!depth_ok)
1602 if (!ctx->quiet)
1603 error ("constexpr evaluation depth exceeds maximum of %d (use "
1604 "-fconstexpr-depth= to increase the maximum)",
1605 max_constexpr_depth);
1606 *non_constant_p = true;
1607 result = error_mark_node;
1609 else
1611 if (result && result != error_mark_node)
1612 /* OK */;
1613 else if (!DECL_SAVED_TREE (fun))
1615 /* When at_eof >= 2, cgraph has started throwing away
1616 DECL_SAVED_TREE, so fail quietly. FIXME we get here because of
1617 late code generation for VEC_INIT_EXPR, which needs to be
1618 completely reconsidered. */
1619 gcc_assert (at_eof >= 2 && ctx->quiet);
1620 *non_constant_p = true;
1622 else
1624 tree body, parms, res;
1626 /* Reuse or create a new unshared copy of this function's body. */
1627 tree copy = get_fundef_copy (fun);
1628 body = TREE_PURPOSE (copy);
1629 parms = TREE_VALUE (copy);
1630 res = TREE_TYPE (copy);
1632 /* Associate the bindings with the remapped parms. */
1633 tree bound = new_call.bindings;
1634 tree remapped = parms;
1635 while (bound)
1637 tree oparm = TREE_PURPOSE (bound);
1638 tree arg = TREE_VALUE (bound);
1639 gcc_assert (DECL_NAME (remapped) == DECL_NAME (oparm));
1640 /* Don't share a CONSTRUCTOR that might be changed. */
1641 arg = unshare_constructor (arg);
1642 ctx->values->put (remapped, arg);
1643 bound = TREE_CHAIN (bound);
1644 remapped = DECL_CHAIN (remapped);
1646 /* Add the RESULT_DECL to the values map, too. */
1647 tree slot = NULL_TREE;
1648 if (DECL_BY_REFERENCE (res))
1650 slot = AGGR_INIT_EXPR_SLOT (t);
1651 tree addr = build_address (slot);
1652 addr = build_nop (TREE_TYPE (res), addr);
1653 ctx->values->put (res, addr);
1654 ctx->values->put (slot, NULL_TREE);
1656 else
1657 ctx->values->put (res, NULL_TREE);
1659 /* Track the callee's evaluated SAVE_EXPRs so that we can forget
1660 their values after the call. */
1661 constexpr_ctx ctx_with_save_exprs = *ctx;
1662 hash_set<tree> save_exprs;
1663 ctx_with_save_exprs.save_exprs = &save_exprs;
1664 ctx_with_save_exprs.call = &new_call;
1666 tree jump_target = NULL_TREE;
1667 cxx_eval_constant_expression (&ctx_with_save_exprs, body,
1668 lval, non_constant_p, overflow_p,
1669 &jump_target);
1671 if (DECL_CONSTRUCTOR_P (fun))
1672 /* This can be null for a subobject constructor call, in
1673 which case what we care about is the initialization
1674 side-effects rather than the value. We could get at the
1675 value by evaluating *this, but we don't bother; there's
1676 no need to put such a call in the hash table. */
1677 result = lval ? ctx->object : ctx->ctor;
1678 else if (VOID_TYPE_P (TREE_TYPE (res)))
1679 result = void_node;
1680 else
1682 result = *ctx->values->get (slot ? slot : res);
1683 if (result == NULL_TREE && !*non_constant_p)
1685 if (!ctx->quiet)
1686 error ("constexpr call flows off the end "
1687 "of the function");
1688 *non_constant_p = true;
1692 /* Forget the saved values of the callee's SAVE_EXPRs. */
1693 for (hash_set<tree>::iterator iter = save_exprs.begin();
1694 iter != save_exprs.end(); ++iter)
1695 ctx_with_save_exprs.values->remove (*iter);
1697 /* Remove the parms/result from the values map. Is it worth
1698 bothering to do this when the map itself is only live for
1699 one constexpr evaluation? If so, maybe also clear out
1700 other vars from call, maybe in BIND_EXPR handling? */
1701 ctx->values->remove (res);
1702 if (slot)
1703 ctx->values->remove (slot);
1704 for (tree parm = parms; parm; parm = TREE_CHAIN (parm))
1705 ctx->values->remove (parm);
1707 /* Make the unshared function copy we used available for re-use. */
1708 save_fundef_copy (fun, copy);
1711 if (result == error_mark_node)
1712 *non_constant_p = true;
1713 if (*non_constant_p || *overflow_p)
1714 result = error_mark_node;
1715 else if (!result)
1716 result = void_node;
1717 if (entry)
1718 entry->result = result;
1721 /* The result of a constexpr function must be completely initialized. */
1722 if (TREE_CODE (result) == CONSTRUCTOR)
1723 clear_no_implicit_zero (result);
1725 pop_cx_call_context ();
1726 return unshare_constructor (result);
1729 /* FIXME speed this up, it's taking 16% of compile time on sieve testcase. */
1731 bool
1732 reduced_constant_expression_p (tree t)
1734 switch (TREE_CODE (t))
1736 case PTRMEM_CST:
1737 /* Even if we can't lower this yet, it's constant. */
1738 return true;
1740 case CONSTRUCTOR:
1741 /* And we need to handle PTRMEM_CST wrapped in a CONSTRUCTOR. */
1742 tree idx, val, field; unsigned HOST_WIDE_INT i;
1743 if (CONSTRUCTOR_NO_IMPLICIT_ZERO (t))
1744 field = next_initializable_field (TYPE_FIELDS (TREE_TYPE (t)));
1745 else
1746 field = NULL_TREE;
1747 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (t), i, idx, val)
1749 if (!val)
1750 /* We're in the middle of initializing this element. */
1751 return false;
1752 if (!reduced_constant_expression_p (val))
1753 return false;
1754 if (field)
1756 if (idx != field)
1757 return false;
1758 field = next_initializable_field (DECL_CHAIN (field));
1761 if (field)
1762 return false;
1763 else if (CONSTRUCTOR_NO_IMPLICIT_ZERO (t))
1764 /* All the fields are initialized. */
1765 CONSTRUCTOR_NO_IMPLICIT_ZERO (t) = false;
1766 return true;
1768 default:
1769 /* FIXME are we calling this too much? */
1770 return initializer_constant_valid_p (t, TREE_TYPE (t)) != NULL_TREE;
1774 /* Some expressions may have constant operands but are not constant
1775 themselves, such as 1/0. Call this function (or rather, the macro
1776 following it) to check for that condition.
1778 We only call this in places that require an arithmetic constant, not in
1779 places where we might have a non-constant expression that can be a
1780 component of a constant expression, such as the address of a constexpr
1781 variable that might be dereferenced later. */
1783 static bool
1784 verify_constant (tree t, bool allow_non_constant, bool *non_constant_p,
1785 bool *overflow_p)
1787 if (!*non_constant_p && !reduced_constant_expression_p (t))
1789 if (!allow_non_constant)
1790 error ("%q+E is not a constant expression", t);
1791 *non_constant_p = true;
1793 if (TREE_OVERFLOW_P (t))
1795 if (!allow_non_constant)
1797 permerror (input_location, "overflow in constant expression");
1798 /* If we're being permissive (and are in an enforcing
1799 context), ignore the overflow. */
1800 if (flag_permissive)
1801 return *non_constant_p;
1803 *overflow_p = true;
1805 return *non_constant_p;
1808 /* Check whether the shift operation with code CODE and type TYPE on LHS
1809 and RHS is undefined. If it is, give an error with an explanation,
1810 and return true; return false otherwise. */
1812 static bool
1813 cxx_eval_check_shift_p (location_t loc, const constexpr_ctx *ctx,
1814 enum tree_code code, tree type, tree lhs, tree rhs)
1816 if ((code != LSHIFT_EXPR && code != RSHIFT_EXPR)
1817 || TREE_CODE (lhs) != INTEGER_CST
1818 || TREE_CODE (rhs) != INTEGER_CST)
1819 return false;
1821 tree lhstype = TREE_TYPE (lhs);
1822 unsigned HOST_WIDE_INT uprec = TYPE_PRECISION (TREE_TYPE (lhs));
1824 /* [expr.shift] The behavior is undefined if the right operand
1825 is negative, or greater than or equal to the length in bits
1826 of the promoted left operand. */
1827 if (tree_int_cst_sgn (rhs) == -1)
1829 if (!ctx->quiet)
1830 permerror (loc, "right operand of shift expression %q+E is negative",
1831 build2_loc (loc, code, type, lhs, rhs));
1832 return (!flag_permissive || ctx->quiet);
1834 if (compare_tree_int (rhs, uprec) >= 0)
1836 if (!ctx->quiet)
1837 permerror (loc, "right operand of shift expression %q+E is >= than "
1838 "the precision of the left operand",
1839 build2_loc (loc, code, type, lhs, rhs));
1840 return (!flag_permissive || ctx->quiet);
1843 /* The value of E1 << E2 is E1 left-shifted E2 bit positions; [...]
1844 if E1 has a signed type and non-negative value, and E1x2^E2 is
1845 representable in the corresponding unsigned type of the result type,
1846 then that value, converted to the result type, is the resulting value;
1847 otherwise, the behavior is undefined. */
1848 if (code == LSHIFT_EXPR && !TYPE_UNSIGNED (lhstype)
1849 && (cxx_dialect >= cxx11))
1851 if (tree_int_cst_sgn (lhs) == -1)
1853 if (!ctx->quiet)
1854 permerror (loc,
1855 "left operand of shift expression %q+E is negative",
1856 build2_loc (loc, code, type, lhs, rhs));
1857 return (!flag_permissive || ctx->quiet);
1859 /* For signed x << y the following:
1860 (unsigned) x >> ((prec (lhs) - 1) - y)
1861 if > 1, is undefined. The right-hand side of this formula
1862 is the highest bit of the LHS that can be set (starting from 0),
1863 so that the shift doesn't overflow. We then right-shift the LHS
1864 to see whether any other bit is set making the original shift
1865 undefined -- the result is not representable in the corresponding
1866 unsigned type. */
1867 tree t = build_int_cst (unsigned_type_node, uprec - 1);
1868 t = fold_build2 (MINUS_EXPR, unsigned_type_node, t, rhs);
1869 tree ulhs = fold_convert (unsigned_type_for (lhstype), lhs);
1870 t = fold_build2 (RSHIFT_EXPR, TREE_TYPE (ulhs), ulhs, t);
1871 if (tree_int_cst_lt (integer_one_node, t))
1873 if (!ctx->quiet)
1874 permerror (loc, "shift expression %q+E overflows",
1875 build2_loc (loc, code, type, lhs, rhs));
1876 return (!flag_permissive || ctx->quiet);
1879 return false;
1882 /* Subroutine of cxx_eval_constant_expression.
1883 Attempt to reduce the unary expression tree T to a compile time value.
1884 If successful, return the value. Otherwise issue a diagnostic
1885 and return error_mark_node. */
1887 static tree
1888 cxx_eval_unary_expression (const constexpr_ctx *ctx, tree t,
1889 bool /*lval*/,
1890 bool *non_constant_p, bool *overflow_p)
1892 tree r;
1893 tree orig_arg = TREE_OPERAND (t, 0);
1894 tree arg = cxx_eval_constant_expression (ctx, orig_arg, /*lval*/false,
1895 non_constant_p, overflow_p);
1896 VERIFY_CONSTANT (arg);
1897 location_t loc = EXPR_LOCATION (t);
1898 enum tree_code code = TREE_CODE (t);
1899 tree type = TREE_TYPE (t);
1900 r = fold_unary_loc (loc, code, type, arg);
1901 if (r == NULL_TREE)
1903 if (arg == orig_arg)
1904 r = t;
1905 else
1906 r = build1_loc (loc, code, type, arg);
1908 VERIFY_CONSTANT (r);
1909 return r;
1912 /* Helper function for cxx_eval_binary_expression. Try to optimize
1913 original POINTER_PLUS_EXPR T, LHS p+ RHS, return NULL_TREE if the
1914 generic folding should be used. */
1916 static tree
1917 cxx_fold_pointer_plus_expression (const constexpr_ctx *ctx, tree t,
1918 tree lhs, tree rhs, bool *non_constant_p,
1919 bool *overflow_p)
1921 STRIP_NOPS (lhs);
1922 if (TREE_CODE (lhs) != ADDR_EXPR)
1923 return NULL_TREE;
1925 lhs = TREE_OPERAND (lhs, 0);
1927 /* &A[i] p+ j => &A[i + j] */
1928 if (TREE_CODE (lhs) == ARRAY_REF
1929 && TREE_CODE (TREE_OPERAND (lhs, 1)) == INTEGER_CST
1930 && TREE_CODE (rhs) == INTEGER_CST
1931 && TYPE_SIZE_UNIT (TREE_TYPE (lhs))
1932 && TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (lhs))) == INTEGER_CST)
1934 tree orig_type = TREE_TYPE (t);
1935 location_t loc = EXPR_LOCATION (t);
1936 tree type = TREE_TYPE (lhs);
1938 t = fold_convert_loc (loc, ssizetype, TREE_OPERAND (lhs, 1));
1939 tree nelts = array_type_nelts_top (TREE_TYPE (TREE_OPERAND (lhs, 0)));
1940 nelts = cxx_eval_constant_expression (ctx, nelts, false, non_constant_p,
1941 overflow_p);
1942 if (*non_constant_p)
1943 return NULL_TREE;
1944 /* Don't fold an out-of-bound access. */
1945 if (!tree_int_cst_le (t, nelts))
1946 return NULL_TREE;
1947 rhs = cp_fold_convert (ssizetype, rhs);
1948 /* Don't fold if rhs can't be divided exactly by TYPE_SIZE_UNIT.
1949 constexpr int A[1]; ... (char *)&A[0] + 1 */
1950 if (!integer_zerop (fold_build2_loc (loc, TRUNC_MOD_EXPR, sizetype,
1951 rhs, TYPE_SIZE_UNIT (type))))
1952 return NULL_TREE;
1953 /* Make sure to treat the second operand of POINTER_PLUS_EXPR
1954 as signed. */
1955 rhs = fold_build2_loc (loc, EXACT_DIV_EXPR, ssizetype, rhs,
1956 TYPE_SIZE_UNIT (type));
1957 t = size_binop_loc (loc, PLUS_EXPR, rhs, t);
1958 t = build4_loc (loc, ARRAY_REF, type, TREE_OPERAND (lhs, 0),
1959 t, NULL_TREE, NULL_TREE);
1960 t = cp_build_addr_expr (t, tf_warning_or_error);
1961 t = cp_fold_convert (orig_type, t);
1962 return cxx_eval_constant_expression (ctx, t, /*lval*/false,
1963 non_constant_p, overflow_p);
1966 return NULL_TREE;
1969 /* Subroutine of cxx_eval_constant_expression.
1970 Like cxx_eval_unary_expression, except for binary expressions. */
1972 static tree
1973 cxx_eval_binary_expression (const constexpr_ctx *ctx, tree t,
1974 bool /*lval*/,
1975 bool *non_constant_p, bool *overflow_p)
1977 tree r = NULL_TREE;
1978 tree orig_lhs = TREE_OPERAND (t, 0);
1979 tree orig_rhs = TREE_OPERAND (t, 1);
1980 tree lhs, rhs;
1981 lhs = cxx_eval_constant_expression (ctx, orig_lhs, /*lval*/false,
1982 non_constant_p, overflow_p);
1983 /* Don't VERIFY_CONSTANT here, it's unnecessary and will break pointer
1984 subtraction. */
1985 if (*non_constant_p)
1986 return t;
1987 rhs = cxx_eval_constant_expression (ctx, orig_rhs, /*lval*/false,
1988 non_constant_p, overflow_p);
1989 if (*non_constant_p)
1990 return t;
1992 location_t loc = EXPR_LOCATION (t);
1993 enum tree_code code = TREE_CODE (t);
1994 tree type = TREE_TYPE (t);
1996 if (code == EQ_EXPR || code == NE_EXPR)
1998 bool is_code_eq = (code == EQ_EXPR);
2000 if (TREE_CODE (lhs) == PTRMEM_CST
2001 && TREE_CODE (rhs) == PTRMEM_CST)
2002 r = constant_boolean_node (cp_tree_equal (lhs, rhs) == is_code_eq,
2003 type);
2004 else if ((TREE_CODE (lhs) == PTRMEM_CST
2005 || TREE_CODE (rhs) == PTRMEM_CST)
2006 && (null_member_pointer_value_p (lhs)
2007 || null_member_pointer_value_p (rhs)))
2008 r = constant_boolean_node (!is_code_eq, type);
2009 else if (TREE_CODE (lhs) == PTRMEM_CST)
2010 lhs = cplus_expand_constant (lhs);
2011 else if (TREE_CODE (rhs) == PTRMEM_CST)
2012 rhs = cplus_expand_constant (rhs);
2014 if (code == POINTER_PLUS_EXPR && !*non_constant_p
2015 && integer_zerop (lhs) && !integer_zerop (rhs))
2017 if (!ctx->quiet)
2018 error ("arithmetic involving a null pointer in %qE", lhs);
2019 return t;
2021 else if (code == POINTER_PLUS_EXPR)
2022 r = cxx_fold_pointer_plus_expression (ctx, t, lhs, rhs, non_constant_p,
2023 overflow_p);
2025 if (r == NULL_TREE)
2026 r = fold_binary_loc (loc, code, type, lhs, rhs);
2028 if (r == NULL_TREE)
2030 if (lhs == orig_lhs && rhs == orig_rhs)
2031 r = t;
2032 else
2033 r = build2_loc (loc, code, type, lhs, rhs);
2035 else if (cxx_eval_check_shift_p (loc, ctx, code, type, lhs, rhs))
2036 *non_constant_p = true;
2037 /* Don't VERIFY_CONSTANT if this might be dealing with a pointer to
2038 a local array in a constexpr function. */
2039 bool ptr = POINTER_TYPE_P (TREE_TYPE (lhs));
2040 if (!ptr)
2041 VERIFY_CONSTANT (r);
2042 return r;
2045 /* Subroutine of cxx_eval_constant_expression.
2046 Attempt to evaluate condition expressions. Dead branches are not
2047 looked into. */
2049 static tree
2050 cxx_eval_conditional_expression (const constexpr_ctx *ctx, tree t,
2051 bool lval,
2052 bool *non_constant_p, bool *overflow_p,
2053 tree *jump_target)
2055 tree val = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
2056 /*lval*/false,
2057 non_constant_p, overflow_p);
2058 VERIFY_CONSTANT (val);
2059 /* Don't VERIFY_CONSTANT the other operands. */
2060 if (integer_zerop (val))
2061 return cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 2),
2062 lval,
2063 non_constant_p, overflow_p,
2064 jump_target);
2065 return cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
2066 lval,
2067 non_constant_p, overflow_p,
2068 jump_target);
2071 /* Returns less than, equal to, or greater than zero if KEY is found to be
2072 less than, to match, or to be greater than the constructor_elt's INDEX. */
2074 static int
2075 array_index_cmp (tree key, tree index)
2077 gcc_assert (TREE_CODE (key) == INTEGER_CST);
2079 switch (TREE_CODE (index))
2081 case INTEGER_CST:
2082 return tree_int_cst_compare (key, index);
2083 case RANGE_EXPR:
2085 tree lo = TREE_OPERAND (index, 0);
2086 tree hi = TREE_OPERAND (index, 1);
2087 if (tree_int_cst_lt (key, lo))
2088 return -1;
2089 else if (tree_int_cst_lt (hi, key))
2090 return 1;
2091 else
2092 return 0;
2094 default:
2095 gcc_unreachable ();
2099 /* Returns the index of the constructor_elt of ARY which matches DINDEX, or -1
2100 if none. If INSERT is true, insert a matching element rather than fail. */
2102 static HOST_WIDE_INT
2103 find_array_ctor_elt (tree ary, tree dindex, bool insert = false)
2105 if (tree_int_cst_sgn (dindex) < 0)
2106 return -1;
2108 unsigned HOST_WIDE_INT i = tree_to_uhwi (dindex);
2109 vec<constructor_elt, va_gc> *elts = CONSTRUCTOR_ELTS (ary);
2110 unsigned HOST_WIDE_INT len = vec_safe_length (elts);
2112 unsigned HOST_WIDE_INT end = len;
2113 unsigned HOST_WIDE_INT begin = 0;
2115 /* If the last element of the CONSTRUCTOR has its own index, we can assume
2116 that the same is true of the other elements and index directly. */
2117 if (end > 0)
2119 tree cindex = (*elts)[end-1].index;
2120 if (TREE_CODE (cindex) == INTEGER_CST
2121 && compare_tree_int (cindex, end-1) == 0)
2123 if (i < end)
2124 return i;
2125 else
2126 begin = end;
2130 /* Otherwise, find a matching index by means of a binary search. */
2131 while (begin != end)
2133 unsigned HOST_WIDE_INT middle = (begin + end) / 2;
2134 constructor_elt &elt = (*elts)[middle];
2135 tree idx = elt.index;
2137 int cmp = array_index_cmp (dindex, idx);
2138 if (cmp < 0)
2139 end = middle;
2140 else if (cmp > 0)
2141 begin = middle + 1;
2142 else
2144 if (insert && TREE_CODE (idx) == RANGE_EXPR)
2146 /* We need to split the range. */
2147 constructor_elt e;
2148 tree lo = TREE_OPERAND (idx, 0);
2149 tree hi = TREE_OPERAND (idx, 1);
2150 if (tree_int_cst_lt (lo, dindex))
2152 /* There are still some lower elts; shorten the range. */
2153 tree new_hi = int_const_binop (MINUS_EXPR, dindex,
2154 size_one_node);
2155 if (tree_int_cst_equal (lo, new_hi))
2156 /* Only one element left, no longer a range. */
2157 elt.index = lo;
2158 else
2159 TREE_OPERAND (idx, 1) = new_hi;
2160 /* Append the element we want to insert. */
2161 ++middle;
2162 e.index = dindex;
2163 e.value = unshare_constructor (elt.value);
2164 vec_safe_insert (CONSTRUCTOR_ELTS (ary), middle, e);
2166 else
2167 /* No lower elts, the range elt is now ours. */
2168 elt.index = dindex;
2170 if (tree_int_cst_lt (dindex, hi))
2172 /* There are still some higher elts; append a range. */
2173 tree new_lo = int_const_binop (PLUS_EXPR, dindex,
2174 size_one_node);
2175 if (tree_int_cst_equal (new_lo, hi))
2176 e.index = hi;
2177 else
2178 e.index = build2 (RANGE_EXPR, sizetype, new_lo, hi);
2179 e.value = unshare_constructor (elt.value);
2180 vec_safe_insert (CONSTRUCTOR_ELTS (ary), middle+1, e);
2183 return middle;
2187 if (insert)
2189 constructor_elt e = { dindex, NULL_TREE };
2190 vec_safe_insert (CONSTRUCTOR_ELTS (ary), end, e);
2191 return end;
2194 return -1;
2197 /* Under the control of CTX, issue a detailed diagnostic for
2198 an out-of-bounds subscript INDEX into the expression ARRAY. */
2200 static void
2201 diag_array_subscript (const constexpr_ctx *ctx, tree array, tree index)
2203 if (!ctx->quiet)
2205 tree arraytype = TREE_TYPE (array);
2207 /* Convert the unsigned array subscript to a signed integer to avoid
2208 printing huge numbers for small negative values. */
2209 tree sidx = fold_convert (ssizetype, index);
2210 if (DECL_P (array))
2212 error ("array subscript value %qE is outside the bounds "
2213 "of array %qD of type %qT", sidx, array, arraytype);
2214 inform (DECL_SOURCE_LOCATION (array), "declared here");
2216 else
2217 error ("array subscript value %qE is outside the bounds "
2218 "of array type %qT", sidx, arraytype);
2222 /* Extract element INDEX consisting of CHARS_PER_ELT chars from
2223 STRING_CST STRING. */
2225 static tree
2226 extract_string_elt (tree string, unsigned chars_per_elt, unsigned index)
2228 tree type = cv_unqualified (TREE_TYPE (TREE_TYPE (string)));
2229 tree r;
2231 if (chars_per_elt == 1)
2232 r = build_int_cst (type, TREE_STRING_POINTER (string)[index]);
2233 else
2235 const unsigned char *ptr
2236 = ((const unsigned char *)TREE_STRING_POINTER (string)
2237 + index * chars_per_elt);
2238 r = native_interpret_expr (type, ptr, chars_per_elt);
2240 return r;
2243 /* Subroutine of cxx_eval_constant_expression.
2244 Attempt to reduce a reference to an array slot. */
2246 static tree
2247 cxx_eval_array_reference (const constexpr_ctx *ctx, tree t,
2248 bool lval,
2249 bool *non_constant_p, bool *overflow_p)
2251 tree oldary = TREE_OPERAND (t, 0);
2252 tree ary = cxx_eval_constant_expression (ctx, oldary,
2253 lval,
2254 non_constant_p, overflow_p);
2255 tree index, oldidx;
2256 HOST_WIDE_INT i = 0;
2257 tree elem_type = NULL_TREE;
2258 unsigned len = 0, elem_nchars = 1;
2259 if (*non_constant_p)
2260 return t;
2261 oldidx = TREE_OPERAND (t, 1);
2262 index = cxx_eval_constant_expression (ctx, oldidx,
2263 false,
2264 non_constant_p, overflow_p);
2265 VERIFY_CONSTANT (index);
2266 if (!lval)
2268 elem_type = TREE_TYPE (TREE_TYPE (ary));
2269 if (TREE_CODE (ary) == VIEW_CONVERT_EXPR
2270 && VECTOR_TYPE_P (TREE_TYPE (TREE_OPERAND (ary, 0)))
2271 && TREE_TYPE (t) == TREE_TYPE (TREE_TYPE (TREE_OPERAND (ary, 0))))
2272 ary = TREE_OPERAND (ary, 0);
2273 if (TREE_CODE (ary) == CONSTRUCTOR)
2274 len = CONSTRUCTOR_NELTS (ary);
2275 else if (TREE_CODE (ary) == STRING_CST)
2277 elem_nchars = (TYPE_PRECISION (elem_type)
2278 / TYPE_PRECISION (char_type_node));
2279 len = (unsigned) TREE_STRING_LENGTH (ary) / elem_nchars;
2281 else if (TREE_CODE (ary) == VECTOR_CST)
2282 len = VECTOR_CST_NELTS (ary);
2283 else
2285 /* We can't do anything with other tree codes, so use
2286 VERIFY_CONSTANT to complain and fail. */
2287 VERIFY_CONSTANT (ary);
2288 gcc_unreachable ();
2291 if (!tree_fits_shwi_p (index)
2292 || (i = tree_to_shwi (index)) < 0)
2294 diag_array_subscript (ctx, ary, index);
2295 *non_constant_p = true;
2296 return t;
2300 tree nelts;
2301 if (TREE_CODE (TREE_TYPE (ary)) == ARRAY_TYPE)
2302 nelts = array_type_nelts_top (TREE_TYPE (ary));
2303 else if (VECTOR_TYPE_P (TREE_TYPE (ary)))
2304 nelts = size_int (TYPE_VECTOR_SUBPARTS (TREE_TYPE (ary)));
2305 else
2306 gcc_unreachable ();
2308 /* For VLAs, the number of elements won't be an integer constant. */
2309 nelts = cxx_eval_constant_expression (ctx, nelts, false, non_constant_p,
2310 overflow_p);
2311 VERIFY_CONSTANT (nelts);
2312 if ((lval
2313 ? !tree_int_cst_le (index, nelts)
2314 : !tree_int_cst_lt (index, nelts))
2315 || tree_int_cst_sgn (index) < 0)
2317 diag_array_subscript (ctx, ary, index);
2318 *non_constant_p = true;
2319 return t;
2322 if (lval && ary == oldary && index == oldidx)
2323 return t;
2324 else if (lval)
2325 return build4 (ARRAY_REF, TREE_TYPE (t), ary, index, NULL, NULL);
2327 bool found;
2328 if (TREE_CODE (ary) == CONSTRUCTOR)
2330 HOST_WIDE_INT ix = find_array_ctor_elt (ary, index);
2331 found = (ix >= 0);
2332 if (found)
2333 i = ix;
2335 else
2336 found = (i < len);
2338 if (found)
2340 tree r;
2341 if (TREE_CODE (ary) == CONSTRUCTOR)
2342 r = (*CONSTRUCTOR_ELTS (ary))[i].value;
2343 else if (TREE_CODE (ary) == VECTOR_CST)
2344 r = VECTOR_CST_ELT (ary, i);
2345 else
2346 r = extract_string_elt (ary, elem_nchars, i);
2348 if (r)
2349 /* Don't VERIFY_CONSTANT here. */
2350 return r;
2352 /* Otherwise the element doesn't have a value yet. */
2355 /* Not found. */
2357 if (TREE_CODE (ary) == CONSTRUCTOR
2358 && CONSTRUCTOR_NO_IMPLICIT_ZERO (ary))
2360 /* 'ary' is part of the aggregate initializer we're currently
2361 building; if there's no initializer for this element yet,
2362 that's an error. */
2363 if (!ctx->quiet)
2364 error ("accessing uninitialized array element");
2365 *non_constant_p = true;
2366 return t;
2369 /* If it's within the array bounds but doesn't have an explicit
2370 initializer, it's value-initialized. */
2371 tree val = build_value_init (elem_type, tf_warning_or_error);
2372 return cxx_eval_constant_expression (ctx, val, lval, non_constant_p,
2373 overflow_p);
2376 /* Subroutine of cxx_eval_constant_expression.
2377 Attempt to reduce a field access of a value of class type. */
2379 static tree
2380 cxx_eval_component_reference (const constexpr_ctx *ctx, tree t,
2381 bool lval,
2382 bool *non_constant_p, bool *overflow_p)
2384 unsigned HOST_WIDE_INT i;
2385 tree field;
2386 tree value;
2387 tree part = TREE_OPERAND (t, 1);
2388 tree orig_whole = TREE_OPERAND (t, 0);
2389 tree whole = cxx_eval_constant_expression (ctx, orig_whole,
2390 lval,
2391 non_constant_p, overflow_p);
2392 if (TREE_CODE (whole) == INDIRECT_REF
2393 && integer_zerop (TREE_OPERAND (whole, 0))
2394 && !ctx->quiet)
2395 error ("dereferencing a null pointer in %qE", orig_whole);
2397 if (TREE_CODE (whole) == PTRMEM_CST)
2398 whole = cplus_expand_constant (whole);
2399 if (whole == orig_whole)
2400 return t;
2401 if (lval)
2402 return fold_build3 (COMPONENT_REF, TREE_TYPE (t),
2403 whole, part, NULL_TREE);
2404 /* Don't VERIFY_CONSTANT here; we only want to check that we got a
2405 CONSTRUCTOR. */
2406 if (!*non_constant_p && TREE_CODE (whole) != CONSTRUCTOR)
2408 if (!ctx->quiet)
2409 error ("%qE is not a constant expression", orig_whole);
2410 *non_constant_p = true;
2412 if (DECL_MUTABLE_P (part))
2414 if (!ctx->quiet)
2415 error ("mutable %qD is not usable in a constant expression", part);
2416 *non_constant_p = true;
2418 if (*non_constant_p)
2419 return t;
2420 bool pmf = TYPE_PTRMEMFUNC_P (TREE_TYPE (whole));
2421 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
2423 /* Use name match for PMF fields, as a variant will have a
2424 different FIELD_DECL with a different type. */
2425 if (pmf ? DECL_NAME (field) == DECL_NAME (part)
2426 : field == part)
2428 if (value)
2429 return value;
2430 else
2431 /* We're in the middle of initializing it. */
2432 break;
2435 if (TREE_CODE (TREE_TYPE (whole)) == UNION_TYPE
2436 && CONSTRUCTOR_NELTS (whole) > 0)
2438 /* DR 1188 says we don't have to deal with this. */
2439 if (!ctx->quiet)
2440 error ("accessing %qD member instead of initialized %qD member in "
2441 "constant expression", part, CONSTRUCTOR_ELT (whole, 0)->index);
2442 *non_constant_p = true;
2443 return t;
2446 /* We only create a CONSTRUCTOR for a subobject when we modify it, so empty
2447 classes never get represented; throw together a value now. */
2448 if (is_really_empty_class (TREE_TYPE (t)))
2449 return build_constructor (TREE_TYPE (t), NULL);
2451 gcc_assert (DECL_CONTEXT (part) == TYPE_MAIN_VARIANT (TREE_TYPE (whole)));
2453 if (CONSTRUCTOR_NO_IMPLICIT_ZERO (whole))
2455 /* 'whole' is part of the aggregate initializer we're currently
2456 building; if there's no initializer for this member yet, that's an
2457 error. */
2458 if (!ctx->quiet)
2459 error ("accessing uninitialized member %qD", part);
2460 *non_constant_p = true;
2461 return t;
2464 /* If there's no explicit init for this field, it's value-initialized. */
2465 value = build_value_init (TREE_TYPE (t), tf_warning_or_error);
2466 return cxx_eval_constant_expression (ctx, value,
2467 lval,
2468 non_constant_p, overflow_p);
2471 /* Subroutine of cxx_eval_constant_expression.
2472 Attempt to reduce a field access of a value of class type that is
2473 expressed as a BIT_FIELD_REF. */
2475 static tree
2476 cxx_eval_bit_field_ref (const constexpr_ctx *ctx, tree t,
2477 bool lval,
2478 bool *non_constant_p, bool *overflow_p)
2480 tree orig_whole = TREE_OPERAND (t, 0);
2481 tree retval, fldval, utype, mask;
2482 bool fld_seen = false;
2483 HOST_WIDE_INT istart, isize;
2484 tree whole = cxx_eval_constant_expression (ctx, orig_whole,
2485 lval,
2486 non_constant_p, overflow_p);
2487 tree start, field, value;
2488 unsigned HOST_WIDE_INT i;
2490 if (whole == orig_whole)
2491 return t;
2492 /* Don't VERIFY_CONSTANT here; we only want to check that we got a
2493 CONSTRUCTOR. */
2494 if (!*non_constant_p
2495 && TREE_CODE (whole) != VECTOR_CST
2496 && TREE_CODE (whole) != CONSTRUCTOR)
2498 if (!ctx->quiet)
2499 error ("%qE is not a constant expression", orig_whole);
2500 *non_constant_p = true;
2502 if (*non_constant_p)
2503 return t;
2505 if (TREE_CODE (whole) == VECTOR_CST)
2506 return fold_ternary (BIT_FIELD_REF, TREE_TYPE (t), whole,
2507 TREE_OPERAND (t, 1), TREE_OPERAND (t, 2));
2509 start = TREE_OPERAND (t, 2);
2510 istart = tree_to_shwi (start);
2511 isize = tree_to_shwi (TREE_OPERAND (t, 1));
2512 utype = TREE_TYPE (t);
2513 if (!TYPE_UNSIGNED (utype))
2514 utype = build_nonstandard_integer_type (TYPE_PRECISION (utype), 1);
2515 retval = build_int_cst (utype, 0);
2516 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (whole), i, field, value)
2518 tree bitpos = bit_position (field);
2519 if (bitpos == start && DECL_SIZE (field) == TREE_OPERAND (t, 1))
2520 return value;
2521 if (TREE_CODE (TREE_TYPE (field)) == INTEGER_TYPE
2522 && TREE_CODE (value) == INTEGER_CST
2523 && tree_fits_shwi_p (bitpos)
2524 && tree_fits_shwi_p (DECL_SIZE (field)))
2526 HOST_WIDE_INT bit = tree_to_shwi (bitpos);
2527 HOST_WIDE_INT sz = tree_to_shwi (DECL_SIZE (field));
2528 HOST_WIDE_INT shift;
2529 if (bit >= istart && bit + sz <= istart + isize)
2531 fldval = fold_convert (utype, value);
2532 mask = build_int_cst_type (utype, -1);
2533 mask = fold_build2 (LSHIFT_EXPR, utype, mask,
2534 size_int (TYPE_PRECISION (utype) - sz));
2535 mask = fold_build2 (RSHIFT_EXPR, utype, mask,
2536 size_int (TYPE_PRECISION (utype) - sz));
2537 fldval = fold_build2 (BIT_AND_EXPR, utype, fldval, mask);
2538 shift = bit - istart;
2539 if (BYTES_BIG_ENDIAN)
2540 shift = TYPE_PRECISION (utype) - shift - sz;
2541 fldval = fold_build2 (LSHIFT_EXPR, utype, fldval,
2542 size_int (shift));
2543 retval = fold_build2 (BIT_IOR_EXPR, utype, retval, fldval);
2544 fld_seen = true;
2548 if (fld_seen)
2549 return fold_convert (TREE_TYPE (t), retval);
2550 gcc_unreachable ();
2551 return error_mark_node;
2554 /* Subroutine of cxx_eval_constant_expression.
2555 Evaluate a short-circuited logical expression T in the context
2556 of a given constexpr CALL. BAILOUT_VALUE is the value for
2557 early return. CONTINUE_VALUE is used here purely for
2558 sanity check purposes. */
2560 static tree
2561 cxx_eval_logical_expression (const constexpr_ctx *ctx, tree t,
2562 tree bailout_value, tree continue_value,
2563 bool lval,
2564 bool *non_constant_p, bool *overflow_p)
2566 tree r;
2567 tree lhs = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
2568 lval,
2569 non_constant_p, overflow_p);
2570 VERIFY_CONSTANT (lhs);
2571 if (tree_int_cst_equal (lhs, bailout_value))
2572 return lhs;
2573 gcc_assert (tree_int_cst_equal (lhs, continue_value));
2574 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
2575 lval, non_constant_p,
2576 overflow_p);
2577 VERIFY_CONSTANT (r);
2578 return r;
2581 /* REF is a COMPONENT_REF designating a particular field. V is a vector of
2582 CONSTRUCTOR elements to initialize (part of) an object containing that
2583 field. Return a pointer to the constructor_elt corresponding to the
2584 initialization of the field. */
2586 static constructor_elt *
2587 base_field_constructor_elt (vec<constructor_elt, va_gc> *v, tree ref)
2589 tree aggr = TREE_OPERAND (ref, 0);
2590 tree field = TREE_OPERAND (ref, 1);
2591 HOST_WIDE_INT i;
2592 constructor_elt *ce;
2594 gcc_assert (TREE_CODE (ref) == COMPONENT_REF);
2596 if (TREE_CODE (aggr) == COMPONENT_REF)
2598 constructor_elt *base_ce
2599 = base_field_constructor_elt (v, aggr);
2600 v = CONSTRUCTOR_ELTS (base_ce->value);
2603 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
2604 if (ce->index == field)
2605 return ce;
2607 gcc_unreachable ();
2608 return NULL;
2611 /* Some of the expressions fed to the constexpr mechanism are calls to
2612 constructors, which have type void. In that case, return the type being
2613 initialized by the constructor. */
2615 static tree
2616 initialized_type (tree t)
2618 if (TYPE_P (t))
2619 return t;
2620 tree type = cv_unqualified (TREE_TYPE (t));
2621 if (TREE_CODE (t) == CALL_EXPR || TREE_CODE (t) == AGGR_INIT_EXPR)
2623 /* A constructor call has void type, so we need to look deeper. */
2624 tree fn = get_function_named_in_call (t);
2625 if (fn && TREE_CODE (fn) == FUNCTION_DECL
2626 && DECL_CXX_CONSTRUCTOR_P (fn))
2627 type = DECL_CONTEXT (fn);
2629 return type;
2632 /* We're about to initialize element INDEX of an array or class from VALUE.
2633 Set up NEW_CTX appropriately by adjusting .object to refer to the
2634 subobject and creating a new CONSTRUCTOR if the element is itself
2635 a class or array. */
2637 static void
2638 init_subob_ctx (const constexpr_ctx *ctx, constexpr_ctx &new_ctx,
2639 tree index, tree &value)
2641 new_ctx = *ctx;
2643 if (index && TREE_CODE (index) != INTEGER_CST
2644 && TREE_CODE (index) != FIELD_DECL)
2645 /* This won't have an element in the new CONSTRUCTOR. */
2646 return;
2648 tree type = initialized_type (value);
2649 if (!AGGREGATE_TYPE_P (type) && !VECTOR_TYPE_P (type))
2650 /* A non-aggregate member doesn't get its own CONSTRUCTOR. */
2651 return;
2653 /* The sub-aggregate initializer might contain a placeholder;
2654 update object to refer to the subobject and ctor to refer to
2655 the (newly created) sub-initializer. */
2656 if (ctx->object)
2657 new_ctx.object = build_ctor_subob_ref (index, type, ctx->object);
2658 tree elt = build_constructor (type, NULL);
2659 CONSTRUCTOR_NO_IMPLICIT_ZERO (elt) = true;
2660 new_ctx.ctor = elt;
2662 if (TREE_CODE (value) == TARGET_EXPR)
2663 /* Avoid creating another CONSTRUCTOR when we expand the TARGET_EXPR. */
2664 value = TARGET_EXPR_INITIAL (value);
2667 /* We're about to process an initializer for a class or array TYPE. Make
2668 sure that CTX is set up appropriately. */
2670 static void
2671 verify_ctor_sanity (const constexpr_ctx *ctx, tree type)
2673 /* We don't bother building a ctor for an empty base subobject. */
2674 if (is_empty_class (type))
2675 return;
2677 /* We're in the middle of an initializer that might involve placeholders;
2678 our caller should have created a CONSTRUCTOR for us to put the
2679 initializer into. We will either return that constructor or T. */
2680 gcc_assert (ctx->ctor);
2681 gcc_assert (same_type_ignoring_top_level_qualifiers_p
2682 (type, TREE_TYPE (ctx->ctor)));
2683 /* We used to check that ctx->ctor was empty, but that isn't the case when
2684 the object is zero-initialized before calling the constructor. */
2685 if (ctx->object)
2687 tree otype = TREE_TYPE (ctx->object);
2688 gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, otype)
2689 /* Handle flexible array members. */
2690 || (TREE_CODE (otype) == ARRAY_TYPE
2691 && TYPE_DOMAIN (otype) == NULL_TREE
2692 && TREE_CODE (type) == ARRAY_TYPE
2693 && (same_type_ignoring_top_level_qualifiers_p
2694 (TREE_TYPE (type), TREE_TYPE (otype)))));
2696 gcc_assert (!ctx->object || !DECL_P (ctx->object)
2697 || *(ctx->values->get (ctx->object)) == ctx->ctor);
2700 /* Subroutine of cxx_eval_constant_expression.
2701 The expression tree T denotes a C-style array or a C-style
2702 aggregate. Reduce it to a constant expression. */
2704 static tree
2705 cxx_eval_bare_aggregate (const constexpr_ctx *ctx, tree t,
2706 bool lval,
2707 bool *non_constant_p, bool *overflow_p)
2709 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
2710 bool changed = false;
2711 gcc_assert (!BRACE_ENCLOSED_INITIALIZER_P (t));
2712 tree type = TREE_TYPE (t);
2714 constexpr_ctx new_ctx;
2715 if (TYPE_PTRMEMFUNC_P (type) || VECTOR_TYPE_P (type))
2717 /* We don't really need the ctx->ctor business for a PMF or
2718 vector, but it's simpler to use the same code. */
2719 new_ctx = *ctx;
2720 new_ctx.ctor = build_constructor (type, NULL);
2721 new_ctx.object = NULL_TREE;
2722 ctx = &new_ctx;
2724 verify_ctor_sanity (ctx, type);
2725 vec<constructor_elt, va_gc> **p = &CONSTRUCTOR_ELTS (ctx->ctor);
2726 vec_alloc (*p, vec_safe_length (v));
2728 unsigned i;
2729 tree index, value;
2730 bool constant_p = true;
2731 bool side_effects_p = false;
2732 FOR_EACH_CONSTRUCTOR_ELT (v, i, index, value)
2734 tree orig_value = value;
2735 init_subob_ctx (ctx, new_ctx, index, value);
2736 if (new_ctx.ctor != ctx->ctor)
2737 /* If we built a new CONSTRUCTOR, attach it now so that other
2738 initializers can refer to it. */
2739 CONSTRUCTOR_APPEND_ELT (*p, index, new_ctx.ctor);
2740 tree elt = cxx_eval_constant_expression (&new_ctx, value,
2741 lval,
2742 non_constant_p, overflow_p);
2743 /* Don't VERIFY_CONSTANT here. */
2744 if (ctx->quiet && *non_constant_p)
2745 break;
2746 if (elt != orig_value)
2747 changed = true;
2749 if (!TREE_CONSTANT (elt))
2750 constant_p = false;
2751 if (TREE_SIDE_EFFECTS (elt))
2752 side_effects_p = true;
2753 if (index && TREE_CODE (index) == COMPONENT_REF)
2755 /* This is an initialization of a vfield inside a base
2756 subaggregate that we already initialized; push this
2757 initialization into the previous initialization. */
2758 constructor_elt *inner = base_field_constructor_elt (*p, index);
2759 inner->value = elt;
2760 changed = true;
2762 else if (index
2763 && (TREE_CODE (index) == NOP_EXPR
2764 || TREE_CODE (index) == POINTER_PLUS_EXPR))
2766 /* This is an initializer for an empty base; now that we've
2767 checked that it's constant, we can ignore it. */
2768 gcc_assert (is_empty_class (TREE_TYPE (TREE_TYPE (index))));
2769 changed = true;
2771 else if (new_ctx.ctor != ctx->ctor)
2773 /* We appended this element above; update the value. */
2774 gcc_assert ((*p)->last().index == index);
2775 (*p)->last().value = elt;
2777 else
2778 CONSTRUCTOR_APPEND_ELT (*p, index, elt);
2780 if (*non_constant_p || !changed)
2781 return t;
2782 t = ctx->ctor;
2783 /* We're done building this CONSTRUCTOR, so now we can interpret an
2784 element without an explicit initializer as value-initialized. */
2785 CONSTRUCTOR_NO_IMPLICIT_ZERO (t) = false;
2786 TREE_CONSTANT (t) = constant_p;
2787 TREE_SIDE_EFFECTS (t) = side_effects_p;
2788 if (VECTOR_TYPE_P (type))
2789 t = fold (t);
2790 return t;
2793 /* Subroutine of cxx_eval_constant_expression.
2794 The expression tree T is a VEC_INIT_EXPR which denotes the desired
2795 initialization of a non-static data member of array type. Reduce it to a
2796 CONSTRUCTOR.
2798 Note that apart from value-initialization (when VALUE_INIT is true),
2799 this is only intended to support value-initialization and the
2800 initializations done by defaulted constructors for classes with
2801 non-static data members of array type. In this case, VEC_INIT_EXPR_INIT
2802 will either be NULL_TREE for the default constructor, or a COMPONENT_REF
2803 for the copy/move constructor. */
2805 static tree
2806 cxx_eval_vec_init_1 (const constexpr_ctx *ctx, tree atype, tree init,
2807 bool value_init, bool lval,
2808 bool *non_constant_p, bool *overflow_p)
2810 tree elttype = TREE_TYPE (atype);
2811 unsigned HOST_WIDE_INT max = tree_to_uhwi (array_type_nelts_top (atype));
2812 verify_ctor_sanity (ctx, atype);
2813 vec<constructor_elt, va_gc> **p = &CONSTRUCTOR_ELTS (ctx->ctor);
2814 vec_alloc (*p, max + 1);
2815 bool pre_init = false;
2816 unsigned HOST_WIDE_INT i;
2818 /* For the default constructor, build up a call to the default
2819 constructor of the element type. We only need to handle class types
2820 here, as for a constructor to be constexpr, all members must be
2821 initialized, which for a defaulted default constructor means they must
2822 be of a class type with a constexpr default constructor. */
2823 if (TREE_CODE (elttype) == ARRAY_TYPE)
2824 /* We only do this at the lowest level. */;
2825 else if (value_init)
2827 init = build_value_init (elttype, tf_warning_or_error);
2828 pre_init = true;
2830 else if (!init)
2832 vec<tree, va_gc> *argvec = make_tree_vector ();
2833 init = build_special_member_call (NULL_TREE, complete_ctor_identifier,
2834 &argvec, elttype, LOOKUP_NORMAL,
2835 tf_warning_or_error);
2836 release_tree_vector (argvec);
2837 init = build_aggr_init_expr (TREE_TYPE (init), init);
2838 pre_init = true;
2841 for (i = 0; i < max; ++i)
2843 tree idx = build_int_cst (size_type_node, i);
2844 tree eltinit;
2845 bool reuse = false;
2846 constexpr_ctx new_ctx;
2847 init_subob_ctx (ctx, new_ctx, idx, pre_init ? init : elttype);
2848 if (new_ctx.ctor != ctx->ctor)
2849 CONSTRUCTOR_APPEND_ELT (*p, idx, new_ctx.ctor);
2850 if (TREE_CODE (elttype) == ARRAY_TYPE)
2852 /* A multidimensional array; recurse. */
2853 if (value_init || init == NULL_TREE)
2855 eltinit = NULL_TREE;
2856 reuse = i == 0;
2858 else
2859 eltinit = cp_build_array_ref (input_location, init, idx,
2860 tf_warning_or_error);
2861 eltinit = cxx_eval_vec_init_1 (&new_ctx, elttype, eltinit, value_init,
2862 lval,
2863 non_constant_p, overflow_p);
2865 else if (pre_init)
2867 /* Initializing an element using value or default initialization
2868 we just pre-built above. */
2869 eltinit = cxx_eval_constant_expression (&new_ctx, init, lval,
2870 non_constant_p, overflow_p);
2871 reuse = i == 0;
2873 else
2875 /* Copying an element. */
2876 gcc_assert (same_type_ignoring_top_level_qualifiers_p
2877 (atype, TREE_TYPE (init)));
2878 eltinit = cp_build_array_ref (input_location, init, idx,
2879 tf_warning_or_error);
2880 if (!lvalue_p (init))
2881 eltinit = move (eltinit);
2882 eltinit = force_rvalue (eltinit, tf_warning_or_error);
2883 eltinit = (cxx_eval_constant_expression
2884 (&new_ctx, eltinit, lval,
2885 non_constant_p, overflow_p));
2887 if (*non_constant_p && !ctx->quiet)
2888 break;
2889 if (new_ctx.ctor != ctx->ctor)
2891 /* We appended this element above; update the value. */
2892 gcc_assert ((*p)->last().index == idx);
2893 (*p)->last().value = eltinit;
2895 else
2896 CONSTRUCTOR_APPEND_ELT (*p, idx, eltinit);
2897 /* Reuse the result of cxx_eval_constant_expression call
2898 from the first iteration to all others if it is a constant
2899 initializer that doesn't require relocations. */
2900 if (reuse
2901 && max > 1
2902 && (initializer_constant_valid_p (eltinit, TREE_TYPE (eltinit))
2903 == null_pointer_node))
2905 if (new_ctx.ctor != ctx->ctor)
2906 eltinit = new_ctx.ctor;
2907 for (i = 1; i < max; ++i)
2909 idx = build_int_cst (size_type_node, i);
2910 CONSTRUCTOR_APPEND_ELT (*p, idx, unshare_constructor (eltinit));
2912 break;
2916 if (!*non_constant_p)
2918 init = ctx->ctor;
2919 CONSTRUCTOR_NO_IMPLICIT_ZERO (init) = false;
2921 return init;
2924 static tree
2925 cxx_eval_vec_init (const constexpr_ctx *ctx, tree t,
2926 bool lval,
2927 bool *non_constant_p, bool *overflow_p)
2929 tree atype = TREE_TYPE (t);
2930 tree init = VEC_INIT_EXPR_INIT (t);
2931 tree r = cxx_eval_vec_init_1 (ctx, atype, init,
2932 VEC_INIT_EXPR_VALUE_INIT (t),
2933 lval, non_constant_p, overflow_p);
2934 if (*non_constant_p)
2935 return t;
2936 else
2937 return r;
2940 /* A less strict version of fold_indirect_ref_1, which requires cv-quals to
2941 match. We want to be less strict for simple *& folding; if we have a
2942 non-const temporary that we access through a const pointer, that should
2943 work. We handle this here rather than change fold_indirect_ref_1
2944 because we're dealing with things like ADDR_EXPR of INTEGER_CST which
2945 don't really make sense outside of constant expression evaluation. Also
2946 we want to allow folding to COMPONENT_REF, which could cause trouble
2947 with TBAA in fold_indirect_ref_1.
2949 Try to keep this function synced with fold_indirect_ref_1. */
2951 static tree
2952 cxx_fold_indirect_ref (location_t loc, tree type, tree op0, bool *empty_base)
2954 tree sub, subtype;
2956 sub = op0;
2957 STRIP_NOPS (sub);
2958 subtype = TREE_TYPE (sub);
2959 if (!POINTER_TYPE_P (subtype))
2960 return NULL_TREE;
2962 if (TREE_CODE (sub) == ADDR_EXPR)
2964 tree op = TREE_OPERAND (sub, 0);
2965 tree optype = TREE_TYPE (op);
2967 /* *&CONST_DECL -> to the value of the const decl. */
2968 if (TREE_CODE (op) == CONST_DECL)
2969 return DECL_INITIAL (op);
2970 /* *&p => p; make sure to handle *&"str"[cst] here. */
2971 if (same_type_ignoring_top_level_qualifiers_p (optype, type)
2972 /* Also handle the case where the desired type is an array of unknown
2973 bounds because the variable has had its bounds deduced since the
2974 ADDR_EXPR was created. */
2975 || (TREE_CODE (type) == ARRAY_TYPE
2976 && TREE_CODE (optype) == ARRAY_TYPE
2977 && TYPE_DOMAIN (type) == NULL_TREE
2978 && same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (optype),
2979 TREE_TYPE (type))))
2981 tree fop = fold_read_from_constant_string (op);
2982 if (fop)
2983 return fop;
2984 else
2985 return op;
2987 /* *(foo *)&fooarray => fooarray[0] */
2988 else if (TREE_CODE (optype) == ARRAY_TYPE
2989 && (same_type_ignoring_top_level_qualifiers_p
2990 (type, TREE_TYPE (optype))))
2992 tree type_domain = TYPE_DOMAIN (optype);
2993 tree min_val = size_zero_node;
2994 if (type_domain && TYPE_MIN_VALUE (type_domain))
2995 min_val = TYPE_MIN_VALUE (type_domain);
2996 return build4_loc (loc, ARRAY_REF, type, op, min_val,
2997 NULL_TREE, NULL_TREE);
2999 /* *(foo *)&complexfoo => __real__ complexfoo */
3000 else if (TREE_CODE (optype) == COMPLEX_TYPE
3001 && (same_type_ignoring_top_level_qualifiers_p
3002 (type, TREE_TYPE (optype))))
3003 return fold_build1_loc (loc, REALPART_EXPR, type, op);
3004 /* *(foo *)&vectorfoo => BIT_FIELD_REF<vectorfoo,...> */
3005 else if (VECTOR_TYPE_P (optype)
3006 && (same_type_ignoring_top_level_qualifiers_p
3007 (type, TREE_TYPE (optype))))
3009 tree part_width = TYPE_SIZE (type);
3010 tree index = bitsize_int (0);
3011 return fold_build3_loc (loc, BIT_FIELD_REF, type, op, part_width, index);
3013 /* Also handle conversion to an empty base class, which
3014 is represented with a NOP_EXPR. */
3015 else if (is_empty_class (type)
3016 && CLASS_TYPE_P (optype)
3017 && DERIVED_FROM_P (type, optype))
3019 *empty_base = true;
3020 return op;
3022 /* *(foo *)&struct_with_foo_field => COMPONENT_REF */
3023 else if (RECORD_OR_UNION_TYPE_P (optype))
3025 tree field = TYPE_FIELDS (optype);
3026 for (; field; field = DECL_CHAIN (field))
3027 if (TREE_CODE (field) == FIELD_DECL
3028 && TREE_TYPE (field) != error_mark_node
3029 && integer_zerop (byte_position (field))
3030 && (same_type_ignoring_top_level_qualifiers_p
3031 (TREE_TYPE (field), type)))
3032 return fold_build3 (COMPONENT_REF, type, op, field, NULL_TREE);
3035 else if (TREE_CODE (sub) == POINTER_PLUS_EXPR
3036 && TREE_CODE (TREE_OPERAND (sub, 1)) == INTEGER_CST)
3038 tree op00 = TREE_OPERAND (sub, 0);
3039 tree op01 = TREE_OPERAND (sub, 1);
3041 STRIP_NOPS (op00);
3042 if (TREE_CODE (op00) == ADDR_EXPR)
3044 tree op00type;
3045 op00 = TREE_OPERAND (op00, 0);
3046 op00type = TREE_TYPE (op00);
3048 /* ((foo*)&vectorfoo)[1] => BIT_FIELD_REF<vectorfoo,...> */
3049 if (VECTOR_TYPE_P (op00type)
3050 && (same_type_ignoring_top_level_qualifiers_p
3051 (type, TREE_TYPE (op00type))))
3053 HOST_WIDE_INT offset = tree_to_shwi (op01);
3054 tree part_width = TYPE_SIZE (type);
3055 unsigned HOST_WIDE_INT part_widthi = tree_to_shwi (part_width)/BITS_PER_UNIT;
3056 unsigned HOST_WIDE_INT indexi = offset * BITS_PER_UNIT;
3057 tree index = bitsize_int (indexi);
3059 if (offset / part_widthi < TYPE_VECTOR_SUBPARTS (op00type))
3060 return fold_build3_loc (loc,
3061 BIT_FIELD_REF, type, op00,
3062 part_width, index);
3065 /* ((foo*)&complexfoo)[1] => __imag__ complexfoo */
3066 else if (TREE_CODE (op00type) == COMPLEX_TYPE
3067 && (same_type_ignoring_top_level_qualifiers_p
3068 (type, TREE_TYPE (op00type))))
3070 tree size = TYPE_SIZE_UNIT (type);
3071 if (tree_int_cst_equal (size, op01))
3072 return fold_build1_loc (loc, IMAGPART_EXPR, type, op00);
3074 /* ((foo *)&fooarray)[1] => fooarray[1] */
3075 else if (TREE_CODE (op00type) == ARRAY_TYPE
3076 && (same_type_ignoring_top_level_qualifiers_p
3077 (type, TREE_TYPE (op00type))))
3079 tree type_domain = TYPE_DOMAIN (op00type);
3080 tree min_val = size_zero_node;
3081 if (type_domain && TYPE_MIN_VALUE (type_domain))
3082 min_val = TYPE_MIN_VALUE (type_domain);
3083 op01 = size_binop_loc (loc, EXACT_DIV_EXPR, op01,
3084 TYPE_SIZE_UNIT (type));
3085 op01 = size_binop_loc (loc, PLUS_EXPR, op01, min_val);
3086 return build4_loc (loc, ARRAY_REF, type, op00, op01,
3087 NULL_TREE, NULL_TREE);
3089 /* Also handle conversion to an empty base class, which
3090 is represented with a NOP_EXPR. */
3091 else if (is_empty_class (type)
3092 && CLASS_TYPE_P (op00type)
3093 && DERIVED_FROM_P (type, op00type))
3095 *empty_base = true;
3096 return op00;
3098 /* ((foo *)&struct_with_foo_field)[1] => COMPONENT_REF */
3099 else if (RECORD_OR_UNION_TYPE_P (op00type))
3101 tree field = TYPE_FIELDS (op00type);
3102 for (; field; field = DECL_CHAIN (field))
3103 if (TREE_CODE (field) == FIELD_DECL
3104 && TREE_TYPE (field) != error_mark_node
3105 && tree_int_cst_equal (byte_position (field), op01)
3106 && (same_type_ignoring_top_level_qualifiers_p
3107 (TREE_TYPE (field), type)))
3108 return fold_build3 (COMPONENT_REF, type, op00,
3109 field, NULL_TREE);
3113 /* *(foo *)fooarrptr => (*fooarrptr)[0] */
3114 else if (TREE_CODE (TREE_TYPE (subtype)) == ARRAY_TYPE
3115 && (same_type_ignoring_top_level_qualifiers_p
3116 (type, TREE_TYPE (TREE_TYPE (subtype)))))
3118 tree type_domain;
3119 tree min_val = size_zero_node;
3120 tree newsub = cxx_fold_indirect_ref (loc, TREE_TYPE (subtype), sub, NULL);
3121 if (newsub)
3122 sub = newsub;
3123 else
3124 sub = build1_loc (loc, INDIRECT_REF, TREE_TYPE (subtype), sub);
3125 type_domain = TYPE_DOMAIN (TREE_TYPE (sub));
3126 if (type_domain && TYPE_MIN_VALUE (type_domain))
3127 min_val = TYPE_MIN_VALUE (type_domain);
3128 return build4_loc (loc, ARRAY_REF, type, sub, min_val, NULL_TREE,
3129 NULL_TREE);
3132 return NULL_TREE;
3135 static tree
3136 cxx_eval_indirect_ref (const constexpr_ctx *ctx, tree t,
3137 bool lval,
3138 bool *non_constant_p, bool *overflow_p)
3140 tree orig_op0 = TREE_OPERAND (t, 0);
3141 bool empty_base = false;
3143 /* We can handle a MEM_REF like an INDIRECT_REF, if MEM_REF's second
3144 operand is an integer-zero. Otherwise reject the MEM_REF for now. */
3146 if (TREE_CODE (t) == MEM_REF
3147 && (!TREE_OPERAND (t, 1) || !integer_zerop (TREE_OPERAND (t, 1))))
3149 gcc_assert (ctx->quiet);
3150 *non_constant_p = true;
3151 return t;
3154 /* First try to simplify it directly. */
3155 tree r = cxx_fold_indirect_ref (EXPR_LOCATION (t), TREE_TYPE (t), orig_op0,
3156 &empty_base);
3157 if (!r)
3159 /* If that didn't work, evaluate the operand first. */
3160 tree op0 = cxx_eval_constant_expression (ctx, orig_op0,
3161 /*lval*/false, non_constant_p,
3162 overflow_p);
3163 /* Don't VERIFY_CONSTANT here. */
3164 if (*non_constant_p)
3165 return t;
3167 if (!lval && integer_zerop (op0))
3169 if (!ctx->quiet)
3170 error ("dereferencing a null pointer");
3171 *non_constant_p = true;
3172 return t;
3175 r = cxx_fold_indirect_ref (EXPR_LOCATION (t), TREE_TYPE (t), op0,
3176 &empty_base);
3177 if (r == NULL_TREE)
3179 /* We couldn't fold to a constant value. Make sure it's not
3180 something we should have been able to fold. */
3181 tree sub = op0;
3182 STRIP_NOPS (sub);
3183 if (TREE_CODE (sub) == ADDR_EXPR)
3185 gcc_assert (!same_type_ignoring_top_level_qualifiers_p
3186 (TREE_TYPE (TREE_TYPE (sub)), TREE_TYPE (t)));
3187 /* DR 1188 says we don't have to deal with this. */
3188 if (!ctx->quiet)
3189 error ("accessing value of %qE through a %qT glvalue in a "
3190 "constant expression", build_fold_indirect_ref (sub),
3191 TREE_TYPE (t));
3192 *non_constant_p = true;
3193 return t;
3196 if (lval && op0 != orig_op0)
3197 return build1 (INDIRECT_REF, TREE_TYPE (t), op0);
3198 if (!lval)
3199 VERIFY_CONSTANT (t);
3200 return t;
3204 r = cxx_eval_constant_expression (ctx, r,
3205 lval, non_constant_p, overflow_p);
3206 if (*non_constant_p)
3207 return t;
3209 /* If we're pulling out the value of an empty base, just return an empty
3210 CONSTRUCTOR. */
3211 if (empty_base && !lval)
3213 r = build_constructor (TREE_TYPE (t), NULL);
3214 TREE_CONSTANT (r) = true;
3217 return r;
3220 /* Complain about R, a VAR_DECL, not being usable in a constant expression.
3221 Shared between potential_constant_expression and
3222 cxx_eval_constant_expression. */
3224 static void
3225 non_const_var_error (tree r)
3227 tree type = TREE_TYPE (r);
3228 error ("the value of %qD is not usable in a constant "
3229 "expression", r);
3230 /* Avoid error cascade. */
3231 if (DECL_INITIAL (r) == error_mark_node)
3232 return;
3233 if (DECL_DECLARED_CONSTEXPR_P (r))
3234 inform (DECL_SOURCE_LOCATION (r),
3235 "%qD used in its own initializer", r);
3236 else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
3238 if (!CP_TYPE_CONST_P (type))
3239 inform (DECL_SOURCE_LOCATION (r),
3240 "%q#D is not const", r);
3241 else if (CP_TYPE_VOLATILE_P (type))
3242 inform (DECL_SOURCE_LOCATION (r),
3243 "%q#D is volatile", r);
3244 else if (!DECL_INITIAL (r)
3245 || !TREE_CONSTANT (DECL_INITIAL (r))
3246 || !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r))
3247 inform (DECL_SOURCE_LOCATION (r),
3248 "%qD was not initialized with a constant "
3249 "expression", r);
3250 else
3251 gcc_unreachable ();
3253 else if (TREE_CODE (type) == REFERENCE_TYPE)
3254 inform (DECL_SOURCE_LOCATION (r),
3255 "%qD was not initialized with a constant "
3256 "expression", r);
3257 else
3259 if (cxx_dialect >= cxx11 && !DECL_DECLARED_CONSTEXPR_P (r))
3260 inform (DECL_SOURCE_LOCATION (r),
3261 "%qD was not declared %<constexpr%>", r);
3262 else
3263 inform (DECL_SOURCE_LOCATION (r),
3264 "%qD does not have integral or enumeration type",
3269 /* Subroutine of cxx_eval_constant_expression.
3270 Like cxx_eval_unary_expression, except for trinary expressions. */
3272 static tree
3273 cxx_eval_trinary_expression (const constexpr_ctx *ctx, tree t,
3274 bool lval,
3275 bool *non_constant_p, bool *overflow_p)
3277 int i;
3278 tree args[3];
3279 tree val;
3281 for (i = 0; i < 3; i++)
3283 args[i] = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, i),
3284 lval,
3285 non_constant_p, overflow_p);
3286 VERIFY_CONSTANT (args[i]);
3289 val = fold_ternary_loc (EXPR_LOCATION (t), TREE_CODE (t), TREE_TYPE (t),
3290 args[0], args[1], args[2]);
3291 if (val == NULL_TREE)
3292 return t;
3293 VERIFY_CONSTANT (val);
3294 return val;
3297 /* True if T was declared in a function declared to be constexpr, and
3298 therefore potentially constant in C++14. */
3300 bool
3301 var_in_constexpr_fn (tree t)
3303 tree ctx = DECL_CONTEXT (t);
3304 return (ctx && TREE_CODE (ctx) == FUNCTION_DECL
3305 && DECL_DECLARED_CONSTEXPR_P (ctx));
3308 /* True if T was declared in a function that might be constexpr: either a
3309 function that was declared constexpr, or a C++17 lambda op(). */
3311 bool
3312 var_in_maybe_constexpr_fn (tree t)
3314 if (cxx_dialect >= cxx17
3315 && DECL_FUNCTION_SCOPE_P (t)
3316 && LAMBDA_FUNCTION_P (DECL_CONTEXT (t)))
3317 return true;
3318 return var_in_constexpr_fn (t);
3321 /* We're assigning INIT to TARGET. In do_build_copy_constructor and
3322 build_over_call we implement trivial copy of a class with tail padding using
3323 assignment of character arrays, which is valid in normal code, but not in
3324 constexpr evaluation. We don't need to worry about clobbering tail padding
3325 in constexpr evaluation, so strip the type punning. */
3327 static void
3328 maybe_simplify_trivial_copy (tree &target, tree &init)
3330 if (TREE_CODE (target) == MEM_REF
3331 && TREE_CODE (init) == MEM_REF
3332 && TREE_TYPE (target) == TREE_TYPE (init)
3333 && TREE_CODE (TREE_TYPE (target)) == ARRAY_TYPE
3334 && TREE_TYPE (TREE_TYPE (target)) == unsigned_char_type_node)
3336 target = build_fold_indirect_ref (TREE_OPERAND (target, 0));
3337 init = build_fold_indirect_ref (TREE_OPERAND (init, 0));
3341 /* Evaluate an INIT_EXPR or MODIFY_EXPR. */
3343 static tree
3344 cxx_eval_store_expression (const constexpr_ctx *ctx, tree t,
3345 bool lval,
3346 bool *non_constant_p, bool *overflow_p)
3348 constexpr_ctx new_ctx = *ctx;
3350 tree init = TREE_OPERAND (t, 1);
3351 if (TREE_CLOBBER_P (init))
3352 /* Just ignore clobbers. */
3353 return void_node;
3355 /* First we figure out where we're storing to. */
3356 tree target = TREE_OPERAND (t, 0);
3358 maybe_simplify_trivial_copy (target, init);
3360 tree type = TREE_TYPE (target);
3361 target = cxx_eval_constant_expression (ctx, target,
3362 true,
3363 non_constant_p, overflow_p);
3364 if (*non_constant_p)
3365 return t;
3367 /* cxx_eval_array_reference for lval = true allows references one past
3368 end of array, because it does not know if it is just taking address
3369 (which is valid), or actual dereference. Here we know it is
3370 a dereference, so diagnose it here. */
3371 for (tree probe = target; probe; )
3373 switch (TREE_CODE (probe))
3375 case ARRAY_REF:
3376 tree nelts, ary;
3377 ary = TREE_OPERAND (probe, 0);
3378 if (TREE_CODE (TREE_TYPE (ary)) == ARRAY_TYPE)
3379 nelts = array_type_nelts_top (TREE_TYPE (ary));
3380 else if (VECTOR_TYPE_P (TREE_TYPE (ary)))
3381 nelts = size_int (TYPE_VECTOR_SUBPARTS (TREE_TYPE (ary)));
3382 else
3383 gcc_unreachable ();
3384 nelts = cxx_eval_constant_expression (ctx, nelts, false,
3385 non_constant_p, overflow_p);
3386 VERIFY_CONSTANT (nelts);
3387 gcc_assert (TREE_CODE (nelts) == INTEGER_CST
3388 && TREE_CODE (TREE_OPERAND (probe, 1)) == INTEGER_CST);
3389 if (wi::to_widest (TREE_OPERAND (probe, 1)) == wi::to_widest (nelts))
3391 diag_array_subscript (ctx, ary, TREE_OPERAND (probe, 1));
3392 *non_constant_p = true;
3393 return t;
3395 /* FALLTHRU */
3397 case BIT_FIELD_REF:
3398 case COMPONENT_REF:
3399 probe = TREE_OPERAND (probe, 0);
3400 continue;
3402 default:
3403 probe = NULL_TREE;
3404 continue;
3408 if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (target), type))
3410 /* For initialization of an empty base, the original target will be
3411 *(base*)this, which the above evaluation resolves to the object
3412 argument, which has the derived type rather than the base type. In
3413 this situation, just evaluate the initializer and return, since
3414 there's no actual data to store. */
3415 gcc_assert (is_empty_class (type));
3416 return cxx_eval_constant_expression (ctx, init, false,
3417 non_constant_p, overflow_p);
3420 /* And then find the underlying variable. */
3421 vec<tree,va_gc> *refs = make_tree_vector();
3422 tree object = NULL_TREE;
3423 for (tree probe = target; object == NULL_TREE; )
3425 switch (TREE_CODE (probe))
3427 case BIT_FIELD_REF:
3428 case COMPONENT_REF:
3429 case ARRAY_REF:
3430 vec_safe_push (refs, TREE_OPERAND (probe, 1));
3431 vec_safe_push (refs, TREE_TYPE (probe));
3432 probe = TREE_OPERAND (probe, 0);
3433 break;
3435 default:
3436 object = probe;
3440 /* And then find/build up our initializer for the path to the subobject
3441 we're initializing. */
3442 tree *valp;
3443 if (object == ctx->object && VAR_P (object)
3444 && DECL_NAME (object) && ctx->call == NULL)
3445 /* The variable we're building up an aggregate initializer for is outside
3446 the constant-expression, so don't evaluate the store. We check
3447 DECL_NAME to handle TARGET_EXPR temporaries, which are fair game. */
3448 valp = NULL;
3449 else if (DECL_P (object))
3450 valp = ctx->values->get (object);
3451 else
3452 valp = NULL;
3453 if (!valp)
3455 /* A constant-expression cannot modify objects from outside the
3456 constant-expression. */
3457 if (!ctx->quiet)
3458 error ("modification of %qE is not a constant expression", object);
3459 *non_constant_p = true;
3460 return t;
3462 type = TREE_TYPE (object);
3463 bool no_zero_init = true;
3465 vec<tree,va_gc> *ctors = make_tree_vector ();
3466 while (!refs->is_empty())
3468 if (*valp == NULL_TREE)
3470 *valp = build_constructor (type, NULL);
3471 CONSTRUCTOR_NO_IMPLICIT_ZERO (*valp) = no_zero_init;
3473 else if (TREE_CODE (*valp) == STRING_CST)
3475 /* An array was initialized with a string constant, and now
3476 we're writing into one of its elements. Explode the
3477 single initialization into a set of element
3478 initializations. */
3479 gcc_assert (TREE_CODE (type) == ARRAY_TYPE);
3481 tree string = *valp;
3482 tree elt_type = TREE_TYPE (type);
3483 unsigned chars_per_elt = (TYPE_PRECISION (elt_type)
3484 / TYPE_PRECISION (char_type_node));
3485 unsigned num_elts = TREE_STRING_LENGTH (string) / chars_per_elt;
3486 tree ary_ctor = build_constructor (type, NULL);
3488 vec_safe_reserve (CONSTRUCTOR_ELTS (ary_ctor), num_elts);
3489 for (unsigned ix = 0; ix != num_elts; ix++)
3491 constructor_elt elt =
3493 build_int_cst (size_type_node, ix),
3494 extract_string_elt (string, chars_per_elt, ix)
3496 CONSTRUCTOR_ELTS (ary_ctor)->quick_push (elt);
3499 *valp = ary_ctor;
3502 /* If the value of object is already zero-initialized, any new ctors for
3503 subobjects will also be zero-initialized. */
3504 no_zero_init = CONSTRUCTOR_NO_IMPLICIT_ZERO (*valp);
3506 vec_safe_push (ctors, *valp);
3508 enum tree_code code = TREE_CODE (type);
3509 type = refs->pop();
3510 tree index = refs->pop();
3512 constructor_elt *cep = NULL;
3513 if (code == ARRAY_TYPE)
3515 HOST_WIDE_INT i
3516 = find_array_ctor_elt (*valp, index, /*insert*/true);
3517 gcc_assert (i >= 0);
3518 cep = CONSTRUCTOR_ELT (*valp, i);
3519 gcc_assert (TREE_CODE (cep->index) != RANGE_EXPR);
3521 else
3523 gcc_assert (TREE_CODE (index) == FIELD_DECL);
3525 /* We must keep the CONSTRUCTOR's ELTS in FIELD order.
3526 Usually we meet initializers in that order, but it is
3527 possible for base types to be placed not in program
3528 order. */
3529 tree fields = TYPE_FIELDS (DECL_CONTEXT (index));
3530 unsigned HOST_WIDE_INT idx;
3532 if (code == UNION_TYPE && CONSTRUCTOR_NELTS (*valp)
3533 && CONSTRUCTOR_ELT (*valp, 0)->index != index)
3534 /* Changing active member. */
3535 vec_safe_truncate (CONSTRUCTOR_ELTS (*valp), 0);
3537 for (idx = 0;
3538 vec_safe_iterate (CONSTRUCTOR_ELTS (*valp), idx, &cep);
3539 idx++, fields = DECL_CHAIN (fields))
3541 if (index == cep->index)
3542 goto found;
3544 /* The field we're initializing must be on the field
3545 list. Look to see if it is present before the
3546 field the current ELT initializes. */
3547 for (; fields != cep->index; fields = DECL_CHAIN (fields))
3548 if (index == fields)
3549 goto insert;
3552 /* We fell off the end of the CONSTRUCTOR, so insert a new
3553 entry at the end. */
3554 insert:
3556 constructor_elt ce = { index, NULL_TREE };
3558 vec_safe_insert (CONSTRUCTOR_ELTS (*valp), idx, ce);
3559 cep = CONSTRUCTOR_ELT (*valp, idx);
3561 found:;
3563 valp = &cep->value;
3565 release_tree_vector (refs);
3567 if (AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type))
3569 /* Create a new CONSTRUCTOR in case evaluation of the initializer
3570 wants to modify it. */
3571 if (*valp == NULL_TREE)
3573 *valp = build_constructor (type, NULL);
3574 CONSTRUCTOR_NO_IMPLICIT_ZERO (*valp) = no_zero_init;
3576 else if (TREE_CODE (*valp) == PTRMEM_CST)
3577 *valp = cplus_expand_constant (*valp);
3578 new_ctx.ctor = *valp;
3579 new_ctx.object = target;
3582 init = cxx_eval_constant_expression (&new_ctx, init, false,
3583 non_constant_p, overflow_p);
3584 /* Don't share a CONSTRUCTOR that might be changed later. */
3585 init = unshare_constructor (init);
3586 if (target == object)
3587 /* The hash table might have moved since the get earlier. */
3588 valp = ctx->values->get (object);
3590 if (TREE_CODE (init) == CONSTRUCTOR)
3592 /* An outer ctx->ctor might be pointing to *valp, so replace
3593 its contents. */
3594 CONSTRUCTOR_ELTS (*valp) = CONSTRUCTOR_ELTS (init);
3595 TREE_CONSTANT (*valp) = TREE_CONSTANT (init);
3596 TREE_SIDE_EFFECTS (*valp) = TREE_SIDE_EFFECTS (init);
3597 CONSTRUCTOR_NO_IMPLICIT_ZERO (*valp)
3598 = CONSTRUCTOR_NO_IMPLICIT_ZERO (init);
3600 else
3601 *valp = init;
3603 /* Update TREE_CONSTANT and TREE_SIDE_EFFECTS on enclosing
3604 CONSTRUCTORs, if any. */
3605 tree elt;
3606 unsigned i;
3607 bool c = TREE_CONSTANT (init);
3608 bool s = TREE_SIDE_EFFECTS (init);
3609 if (!c || s)
3610 FOR_EACH_VEC_SAFE_ELT (ctors, i, elt)
3612 if (!c)
3613 TREE_CONSTANT (elt) = false;
3614 if (s)
3615 TREE_SIDE_EFFECTS (elt) = true;
3617 release_tree_vector (ctors);
3619 if (*non_constant_p)
3620 return t;
3621 else if (lval)
3622 return target;
3623 else
3624 return init;
3627 /* Evaluate a ++ or -- expression. */
3629 static tree
3630 cxx_eval_increment_expression (const constexpr_ctx *ctx, tree t,
3631 bool lval,
3632 bool *non_constant_p, bool *overflow_p)
3634 enum tree_code code = TREE_CODE (t);
3635 tree type = TREE_TYPE (t);
3636 tree op = TREE_OPERAND (t, 0);
3637 tree offset = TREE_OPERAND (t, 1);
3638 gcc_assert (TREE_CONSTANT (offset));
3640 /* The operand as an lvalue. */
3641 op = cxx_eval_constant_expression (ctx, op, true,
3642 non_constant_p, overflow_p);
3644 /* The operand as an rvalue. */
3645 tree val = rvalue (op);
3646 val = cxx_eval_constant_expression (ctx, val, false,
3647 non_constant_p, overflow_p);
3648 /* Don't VERIFY_CONSTANT if this might be dealing with a pointer to
3649 a local array in a constexpr function. */
3650 bool ptr = POINTER_TYPE_P (TREE_TYPE (val));
3651 if (!ptr)
3652 VERIFY_CONSTANT (val);
3654 /* The modified value. */
3655 bool inc = (code == PREINCREMENT_EXPR || code == POSTINCREMENT_EXPR);
3656 tree mod;
3657 if (POINTER_TYPE_P (type))
3659 /* The middle end requires pointers to use POINTER_PLUS_EXPR. */
3660 offset = convert_to_ptrofftype (offset);
3661 if (!inc)
3662 offset = fold_build1 (NEGATE_EXPR, TREE_TYPE (offset), offset);
3663 mod = fold_build2 (POINTER_PLUS_EXPR, type, val, offset);
3665 else
3666 mod = fold_build2 (inc ? PLUS_EXPR : MINUS_EXPR, type, val, offset);
3667 if (!ptr)
3668 VERIFY_CONSTANT (mod);
3670 /* Storing the modified value. */
3671 tree store = build2 (MODIFY_EXPR, type, op, mod);
3672 cxx_eval_constant_expression (ctx, store,
3673 true, non_constant_p, overflow_p);
3675 /* And the value of the expression. */
3676 if (code == PREINCREMENT_EXPR || code == PREDECREMENT_EXPR)
3678 /* Prefix ops are lvalues. */
3679 if (lval)
3680 return op;
3681 else
3682 /* But we optimize when the caller wants an rvalue. */
3683 return mod;
3685 else
3686 /* Postfix ops are rvalues. */
3687 return val;
3690 /* Predicates for the meaning of *jump_target. */
3692 static bool
3693 returns (tree *jump_target)
3695 return *jump_target
3696 && (TREE_CODE (*jump_target) == RETURN_EXPR
3697 || (TREE_CODE (*jump_target) == LABEL_DECL
3698 && LABEL_DECL_CDTOR (*jump_target)));
3701 static bool
3702 breaks (tree *jump_target)
3704 return *jump_target
3705 && ((TREE_CODE (*jump_target) == LABEL_DECL
3706 && LABEL_DECL_BREAK (*jump_target))
3707 || TREE_CODE (*jump_target) == EXIT_EXPR);
3710 static bool
3711 continues (tree *jump_target)
3713 return *jump_target
3714 && TREE_CODE (*jump_target) == LABEL_DECL
3715 && LABEL_DECL_CONTINUE (*jump_target);
3718 static bool
3719 switches (tree *jump_target)
3721 return *jump_target
3722 && TREE_CODE (*jump_target) == INTEGER_CST;
3725 /* Subroutine of cxx_eval_statement_list. Determine whether the statement
3726 STMT matches *jump_target. If we're looking for a case label and we see
3727 the default label, note it in ctx->css_state. */
3729 static bool
3730 label_matches (const constexpr_ctx *ctx, tree *jump_target, tree stmt)
3732 switch (TREE_CODE (*jump_target))
3734 case LABEL_DECL:
3735 if (TREE_CODE (stmt) == LABEL_EXPR
3736 && LABEL_EXPR_LABEL (stmt) == *jump_target)
3737 return true;
3738 break;
3740 case INTEGER_CST:
3741 if (TREE_CODE (stmt) == CASE_LABEL_EXPR)
3743 gcc_assert (ctx->css_state != NULL);
3744 if (!CASE_LOW (stmt))
3746 /* default: should appear just once in a SWITCH_EXPR
3747 body (excluding nested SWITCH_EXPR). */
3748 gcc_assert (*ctx->css_state != css_default_seen);
3749 /* When evaluating SWITCH_EXPR body for the second time,
3750 return true for the default: label. */
3751 if (*ctx->css_state == css_default_processing)
3752 return true;
3753 *ctx->css_state = css_default_seen;
3755 else if (CASE_HIGH (stmt))
3757 if (tree_int_cst_le (CASE_LOW (stmt), *jump_target)
3758 && tree_int_cst_le (*jump_target, CASE_HIGH (stmt)))
3759 return true;
3761 else if (tree_int_cst_equal (*jump_target, CASE_LOW (stmt)))
3762 return true;
3764 break;
3766 default:
3767 gcc_unreachable ();
3769 return false;
3772 /* Evaluate a STATEMENT_LIST for side-effects. Handles various jump
3773 semantics, for switch, break, continue, and return. */
3775 static tree
3776 cxx_eval_statement_list (const constexpr_ctx *ctx, tree t,
3777 bool *non_constant_p, bool *overflow_p,
3778 tree *jump_target)
3780 tree_stmt_iterator i;
3781 tree local_target;
3782 /* In a statement-expression we want to return the last value.
3783 For empty statement expression return void_node. */
3784 tree r = void_node;
3785 if (!jump_target)
3787 local_target = NULL_TREE;
3788 jump_target = &local_target;
3790 for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
3792 tree stmt = tsi_stmt (i);
3793 r = cxx_eval_constant_expression (ctx, stmt, false,
3794 non_constant_p, overflow_p,
3795 jump_target);
3796 if (*non_constant_p)
3797 break;
3798 if (returns (jump_target) || breaks (jump_target))
3799 break;
3801 return r;
3804 /* Evaluate a LOOP_EXPR for side-effects. Handles break and return
3805 semantics; continue semantics are covered by cxx_eval_statement_list. */
3807 static tree
3808 cxx_eval_loop_expr (const constexpr_ctx *ctx, tree t,
3809 bool *non_constant_p, bool *overflow_p,
3810 tree *jump_target)
3812 constexpr_ctx new_ctx = *ctx;
3814 tree body = TREE_OPERAND (t, 0);
3815 int count = 0;
3818 hash_set<tree> save_exprs;
3819 new_ctx.save_exprs = &save_exprs;
3821 cxx_eval_constant_expression (&new_ctx, body, /*lval*/false,
3822 non_constant_p, overflow_p, jump_target);
3824 /* Forget saved values of SAVE_EXPRs. */
3825 for (hash_set<tree>::iterator iter = save_exprs.begin();
3826 iter != save_exprs.end(); ++iter)
3827 new_ctx.values->remove (*iter);
3828 if (++count >= constexpr_loop_limit)
3830 if (!ctx->quiet)
3831 error_at (EXPR_LOC_OR_LOC (t, input_location),
3832 "constexpr loop iteration count exceeds limit of %d "
3833 "(use -fconstexpr-loop-limit= to increase the limit)",
3834 constexpr_loop_limit);
3835 *non_constant_p = true;
3836 break;
3839 while (!returns (jump_target)
3840 && !breaks (jump_target)
3841 && !switches (jump_target)
3842 && !*non_constant_p);
3844 if (breaks (jump_target))
3845 *jump_target = NULL_TREE;
3847 return NULL_TREE;
3850 /* Evaluate a SWITCH_EXPR for side-effects. Handles switch and break jump
3851 semantics. */
3853 static tree
3854 cxx_eval_switch_expr (const constexpr_ctx *ctx, tree t,
3855 bool *non_constant_p, bool *overflow_p,
3856 tree *jump_target)
3858 tree cond = TREE_OPERAND (t, 0);
3859 cond = cxx_eval_constant_expression (ctx, cond, false,
3860 non_constant_p, overflow_p);
3861 VERIFY_CONSTANT (cond);
3862 *jump_target = cond;
3864 tree body = TREE_OPERAND (t, 1);
3865 constexpr_ctx new_ctx = *ctx;
3866 constexpr_switch_state css = css_default_not_seen;
3867 new_ctx.css_state = &css;
3868 cxx_eval_constant_expression (&new_ctx, body, false,
3869 non_constant_p, overflow_p, jump_target);
3870 if (switches (jump_target) && css == css_default_seen)
3872 /* If the SWITCH_EXPR body has default: label, process it once again,
3873 this time instructing label_matches to return true for default:
3874 label on switches (jump_target). */
3875 css = css_default_processing;
3876 cxx_eval_constant_expression (&new_ctx, body, false,
3877 non_constant_p, overflow_p, jump_target);
3879 if (breaks (jump_target) || switches (jump_target))
3880 *jump_target = NULL_TREE;
3881 return NULL_TREE;
3884 /* Find the object of TYPE under initialization in CTX. */
3886 static tree
3887 lookup_placeholder (const constexpr_ctx *ctx, bool lval, tree type)
3889 if (!ctx)
3890 return NULL_TREE;
3892 /* We could use ctx->object unconditionally, but using ctx->ctor when we
3893 can is a minor optimization. */
3894 if (!lval && ctx->ctor && same_type_p (TREE_TYPE (ctx->ctor), type))
3895 return ctx->ctor;
3897 if (!ctx->object)
3898 return NULL_TREE;
3900 /* Since an object cannot have a field of its own type, we can search outward
3901 from ctx->object to find the unique containing object of TYPE. */
3902 tree ob = ctx->object;
3903 while (ob)
3905 if (same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (ob), type))
3906 break;
3907 if (handled_component_p (ob))
3908 ob = TREE_OPERAND (ob, 0);
3909 else
3910 ob = NULL_TREE;
3913 return ob;
3916 /* Attempt to reduce the expression T to a constant value.
3917 On failure, issue diagnostic and return error_mark_node. */
3918 /* FIXME unify with c_fully_fold */
3919 /* FIXME overflow_p is too global */
3921 static tree
3922 cxx_eval_constant_expression (const constexpr_ctx *ctx, tree t,
3923 bool lval,
3924 bool *non_constant_p, bool *overflow_p,
3925 tree *jump_target)
3927 constexpr_ctx new_ctx;
3928 tree r = t;
3930 if (jump_target && *jump_target)
3932 /* If we are jumping, ignore all statements/expressions except those
3933 that could have LABEL_EXPR or CASE_LABEL_EXPR in their bodies. */
3934 switch (TREE_CODE (t))
3936 case BIND_EXPR:
3937 case STATEMENT_LIST:
3938 case LOOP_EXPR:
3939 case COND_EXPR:
3940 break;
3941 case LABEL_EXPR:
3942 case CASE_LABEL_EXPR:
3943 if (label_matches (ctx, jump_target, t))
3944 /* Found it. */
3945 *jump_target = NULL_TREE;
3946 return NULL_TREE;
3947 default:
3948 return NULL_TREE;
3951 if (t == error_mark_node)
3953 *non_constant_p = true;
3954 return t;
3956 if (CONSTANT_CLASS_P (t))
3958 if (TREE_OVERFLOW (t))
3960 if (!ctx->quiet)
3961 permerror (input_location, "overflow in constant expression");
3962 if (!flag_permissive || ctx->quiet)
3963 *overflow_p = true;
3966 if (TREE_CODE (t) == INTEGER_CST
3967 && TREE_CODE (TREE_TYPE (t)) == POINTER_TYPE
3968 && !integer_zerop (t))
3970 if (!ctx->quiet)
3971 error ("value %qE of type %qT is not a constant expression",
3972 t, TREE_TYPE (t));
3973 *non_constant_p = true;
3976 return t;
3979 tree_code tcode = TREE_CODE (t);
3980 switch (tcode)
3982 case RESULT_DECL:
3983 if (lval)
3984 return t;
3985 /* We ask for an rvalue for the RESULT_DECL when indirecting
3986 through an invisible reference, or in named return value
3987 optimization. */
3988 return (*ctx->values->get (t));
3990 case VAR_DECL:
3991 if (DECL_HAS_VALUE_EXPR_P (t))
3992 return cxx_eval_constant_expression (ctx, DECL_VALUE_EXPR (t),
3993 lval, non_constant_p, overflow_p);
3994 /* fall through */
3995 case CONST_DECL:
3996 /* We used to not check lval for CONST_DECL, but darwin.c uses
3997 CONST_DECL for aggregate constants. */
3998 if (lval)
3999 return t;
4000 if (COMPLETE_TYPE_P (TREE_TYPE (t))
4001 && is_really_empty_class (TREE_TYPE (t)))
4003 /* If the class is empty, we aren't actually loading anything. */
4004 r = build_constructor (TREE_TYPE (t), NULL);
4005 TREE_CONSTANT (r) = true;
4007 else if (ctx->strict)
4008 r = decl_really_constant_value (t);
4009 else
4010 r = decl_constant_value (t);
4011 if (TREE_CODE (r) == TARGET_EXPR
4012 && TREE_CODE (TARGET_EXPR_INITIAL (r)) == CONSTRUCTOR)
4013 r = TARGET_EXPR_INITIAL (r);
4014 if (VAR_P (r))
4015 if (tree *p = ctx->values->get (r))
4016 if (*p != NULL_TREE)
4017 r = *p;
4018 if (DECL_P (r))
4020 if (!ctx->quiet)
4021 non_const_var_error (r);
4022 *non_constant_p = true;
4024 break;
4026 case FUNCTION_DECL:
4027 case TEMPLATE_DECL:
4028 case LABEL_DECL:
4029 case LABEL_EXPR:
4030 case CASE_LABEL_EXPR:
4031 case PREDICT_EXPR:
4032 return t;
4034 case PARM_DECL:
4035 if (lval && TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
4036 /* glvalue use. */;
4037 else if (tree *p = ctx->values->get (r))
4038 r = *p;
4039 else if (lval)
4040 /* Defer in case this is only used for its type. */;
4041 else if (TREE_CODE (TREE_TYPE (t)) == REFERENCE_TYPE)
4042 /* Defer, there's no lvalue->rvalue conversion. */;
4043 else if (COMPLETE_TYPE_P (TREE_TYPE (t))
4044 && is_really_empty_class (TREE_TYPE (t)))
4046 /* If the class is empty, we aren't actually loading anything. */
4047 r = build_constructor (TREE_TYPE (t), NULL);
4048 TREE_CONSTANT (r) = true;
4050 else
4052 if (!ctx->quiet)
4053 error ("%qE is not a constant expression", t);
4054 *non_constant_p = true;
4056 break;
4058 case CALL_EXPR:
4059 case AGGR_INIT_EXPR:
4060 r = cxx_eval_call_expression (ctx, t, lval,
4061 non_constant_p, overflow_p);
4062 break;
4064 case DECL_EXPR:
4066 r = DECL_EXPR_DECL (t);
4067 if (AGGREGATE_TYPE_P (TREE_TYPE (r))
4068 || VECTOR_TYPE_P (TREE_TYPE (r)))
4070 new_ctx = *ctx;
4071 new_ctx.object = r;
4072 new_ctx.ctor = build_constructor (TREE_TYPE (r), NULL);
4073 CONSTRUCTOR_NO_IMPLICIT_ZERO (new_ctx.ctor) = true;
4074 new_ctx.values->put (r, new_ctx.ctor);
4075 ctx = &new_ctx;
4078 if (tree init = DECL_INITIAL (r))
4080 init = cxx_eval_constant_expression (ctx, init,
4081 false,
4082 non_constant_p, overflow_p);
4083 /* Don't share a CONSTRUCTOR that might be changed. */
4084 init = unshare_constructor (init);
4085 ctx->values->put (r, init);
4087 else if (ctx == &new_ctx)
4088 /* We gave it a CONSTRUCTOR above. */;
4089 else
4090 ctx->values->put (r, NULL_TREE);
4092 break;
4094 case TARGET_EXPR:
4095 if (!literal_type_p (TREE_TYPE (t)))
4097 if (!ctx->quiet)
4099 error ("temporary of non-literal type %qT in a "
4100 "constant expression", TREE_TYPE (t));
4101 explain_non_literal_class (TREE_TYPE (t));
4103 *non_constant_p = true;
4104 break;
4106 if ((AGGREGATE_TYPE_P (TREE_TYPE (t)) || VECTOR_TYPE_P (TREE_TYPE (t))))
4108 /* We're being expanded without an explicit target, so start
4109 initializing a new object; expansion with an explicit target
4110 strips the TARGET_EXPR before we get here. */
4111 new_ctx = *ctx;
4112 new_ctx.ctor = build_constructor (TREE_TYPE (t), NULL);
4113 CONSTRUCTOR_NO_IMPLICIT_ZERO (new_ctx.ctor) = true;
4114 new_ctx.object = TARGET_EXPR_SLOT (t);
4115 ctx->values->put (new_ctx.object, new_ctx.ctor);
4116 ctx = &new_ctx;
4118 /* Pass false for 'lval' because this indicates
4119 initialization of a temporary. */
4120 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
4121 false,
4122 non_constant_p, overflow_p);
4123 if (!*non_constant_p)
4124 /* Adjust the type of the result to the type of the temporary. */
4125 r = adjust_temp_type (TREE_TYPE (t), r);
4126 if (lval)
4128 tree slot = TARGET_EXPR_SLOT (t);
4129 r = unshare_constructor (r);
4130 ctx->values->put (slot, r);
4131 return slot;
4133 break;
4135 case INIT_EXPR:
4136 case MODIFY_EXPR:
4137 gcc_assert (jump_target == NULL || *jump_target == NULL_TREE);
4138 r = cxx_eval_store_expression (ctx, t, lval,
4139 non_constant_p, overflow_p);
4140 break;
4142 case SCOPE_REF:
4143 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
4144 lval,
4145 non_constant_p, overflow_p);
4146 break;
4148 case RETURN_EXPR:
4149 if (TREE_OPERAND (t, 0) != NULL_TREE)
4150 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
4151 lval,
4152 non_constant_p, overflow_p);
4153 *jump_target = t;
4154 break;
4156 case SAVE_EXPR:
4157 /* Avoid evaluating a SAVE_EXPR more than once. */
4158 if (tree *p = ctx->values->get (t))
4159 r = *p;
4160 else
4162 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), false,
4163 non_constant_p, overflow_p);
4164 ctx->values->put (t, r);
4165 if (ctx->save_exprs)
4166 ctx->save_exprs->add (t);
4168 break;
4170 case NON_LVALUE_EXPR:
4171 case TRY_CATCH_EXPR:
4172 case TRY_BLOCK:
4173 case CLEANUP_POINT_EXPR:
4174 case MUST_NOT_THROW_EXPR:
4175 case EXPR_STMT:
4176 case EH_SPEC_BLOCK:
4177 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
4178 lval,
4179 non_constant_p, overflow_p,
4180 jump_target);
4181 break;
4183 case TRY_FINALLY_EXPR:
4184 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
4185 non_constant_p, overflow_p,
4186 jump_target);
4187 if (!*non_constant_p)
4188 /* Also evaluate the cleanup. */
4189 cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1), true,
4190 non_constant_p, overflow_p,
4191 jump_target);
4192 break;
4194 /* These differ from cxx_eval_unary_expression in that this doesn't
4195 check for a constant operand or result; an address can be
4196 constant without its operand being, and vice versa. */
4197 case MEM_REF:
4198 case INDIRECT_REF:
4199 r = cxx_eval_indirect_ref (ctx, t, lval,
4200 non_constant_p, overflow_p);
4201 break;
4203 case ADDR_EXPR:
4205 tree oldop = TREE_OPERAND (t, 0);
4206 tree op = cxx_eval_constant_expression (ctx, oldop,
4207 /*lval*/true,
4208 non_constant_p, overflow_p);
4209 /* Don't VERIFY_CONSTANT here. */
4210 if (*non_constant_p)
4211 return t;
4212 gcc_checking_assert (TREE_CODE (op) != CONSTRUCTOR);
4213 /* This function does more aggressive folding than fold itself. */
4214 r = build_fold_addr_expr_with_type (op, TREE_TYPE (t));
4215 if (TREE_CODE (r) == ADDR_EXPR && TREE_OPERAND (r, 0) == oldop)
4216 return t;
4217 break;
4220 case REALPART_EXPR:
4221 case IMAGPART_EXPR:
4222 if (lval)
4224 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0), lval,
4225 non_constant_p, overflow_p);
4226 if (r == error_mark_node)
4228 else if (r == TREE_OPERAND (t, 0))
4229 r = t;
4230 else
4231 r = fold_build1 (TREE_CODE (t), TREE_TYPE (t), r);
4232 break;
4234 /* FALLTHRU */
4235 case CONJ_EXPR:
4236 case FIX_TRUNC_EXPR:
4237 case FLOAT_EXPR:
4238 case NEGATE_EXPR:
4239 case ABS_EXPR:
4240 case BIT_NOT_EXPR:
4241 case TRUTH_NOT_EXPR:
4242 case FIXED_CONVERT_EXPR:
4243 r = cxx_eval_unary_expression (ctx, t, lval,
4244 non_constant_p, overflow_p);
4245 break;
4247 case SIZEOF_EXPR:
4248 r = fold_sizeof_expr (t);
4249 VERIFY_CONSTANT (r);
4250 break;
4252 case COMPOUND_EXPR:
4254 /* check_return_expr sometimes wraps a TARGET_EXPR in a
4255 COMPOUND_EXPR; don't get confused. Also handle EMPTY_CLASS_EXPR
4256 introduced by build_call_a. */
4257 tree op0 = TREE_OPERAND (t, 0);
4258 tree op1 = TREE_OPERAND (t, 1);
4259 STRIP_NOPS (op1);
4260 if ((TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
4261 || TREE_CODE (op1) == EMPTY_CLASS_EXPR)
4262 r = cxx_eval_constant_expression (ctx, op0,
4263 lval, non_constant_p, overflow_p,
4264 jump_target);
4265 else
4267 /* Check that the LHS is constant and then discard it. */
4268 cxx_eval_constant_expression (ctx, op0,
4269 true, non_constant_p, overflow_p,
4270 jump_target);
4271 if (*non_constant_p)
4272 return t;
4273 op1 = TREE_OPERAND (t, 1);
4274 r = cxx_eval_constant_expression (ctx, op1,
4275 lval, non_constant_p, overflow_p,
4276 jump_target);
4279 break;
4281 case POINTER_PLUS_EXPR:
4282 case PLUS_EXPR:
4283 case MINUS_EXPR:
4284 case MULT_EXPR:
4285 case TRUNC_DIV_EXPR:
4286 case CEIL_DIV_EXPR:
4287 case FLOOR_DIV_EXPR:
4288 case ROUND_DIV_EXPR:
4289 case TRUNC_MOD_EXPR:
4290 case CEIL_MOD_EXPR:
4291 case ROUND_MOD_EXPR:
4292 case RDIV_EXPR:
4293 case EXACT_DIV_EXPR:
4294 case MIN_EXPR:
4295 case MAX_EXPR:
4296 case LSHIFT_EXPR:
4297 case RSHIFT_EXPR:
4298 case LROTATE_EXPR:
4299 case RROTATE_EXPR:
4300 case BIT_IOR_EXPR:
4301 case BIT_XOR_EXPR:
4302 case BIT_AND_EXPR:
4303 case TRUTH_XOR_EXPR:
4304 case LT_EXPR:
4305 case LE_EXPR:
4306 case GT_EXPR:
4307 case GE_EXPR:
4308 case EQ_EXPR:
4309 case NE_EXPR:
4310 case UNORDERED_EXPR:
4311 case ORDERED_EXPR:
4312 case UNLT_EXPR:
4313 case UNLE_EXPR:
4314 case UNGT_EXPR:
4315 case UNGE_EXPR:
4316 case UNEQ_EXPR:
4317 case LTGT_EXPR:
4318 case RANGE_EXPR:
4319 case COMPLEX_EXPR:
4320 r = cxx_eval_binary_expression (ctx, t, lval,
4321 non_constant_p, overflow_p);
4322 break;
4324 /* fold can introduce non-IF versions of these; still treat them as
4325 short-circuiting. */
4326 case TRUTH_AND_EXPR:
4327 case TRUTH_ANDIF_EXPR:
4328 r = cxx_eval_logical_expression (ctx, t, boolean_false_node,
4329 boolean_true_node,
4330 lval,
4331 non_constant_p, overflow_p);
4332 break;
4334 case TRUTH_OR_EXPR:
4335 case TRUTH_ORIF_EXPR:
4336 r = cxx_eval_logical_expression (ctx, t, boolean_true_node,
4337 boolean_false_node,
4338 lval,
4339 non_constant_p, overflow_p);
4340 break;
4342 case ARRAY_REF:
4343 r = cxx_eval_array_reference (ctx, t, lval,
4344 non_constant_p, overflow_p);
4345 break;
4347 case COMPONENT_REF:
4348 if (is_overloaded_fn (t))
4350 /* We can only get here in checking mode via
4351 build_non_dependent_expr, because any expression that
4352 calls or takes the address of the function will have
4353 pulled a FUNCTION_DECL out of the COMPONENT_REF. */
4354 gcc_checking_assert (ctx->quiet || errorcount);
4355 *non_constant_p = true;
4356 return t;
4358 r = cxx_eval_component_reference (ctx, t, lval,
4359 non_constant_p, overflow_p);
4360 break;
4362 case BIT_FIELD_REF:
4363 r = cxx_eval_bit_field_ref (ctx, t, lval,
4364 non_constant_p, overflow_p);
4365 break;
4367 case COND_EXPR:
4368 if (jump_target && *jump_target)
4370 /* When jumping to a label, the label might be either in the
4371 then or else blocks, so process then block first in skipping
4372 mode first, and if we are still in the skipping mode at its end,
4373 process the else block too. */
4374 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 1),
4375 lval, non_constant_p, overflow_p,
4376 jump_target);
4377 if (*jump_target)
4378 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 2),
4379 lval, non_constant_p, overflow_p,
4380 jump_target);
4381 break;
4383 /* FALLTHRU */
4384 case VEC_COND_EXPR:
4385 r = cxx_eval_conditional_expression (ctx, t, lval,
4386 non_constant_p, overflow_p,
4387 jump_target);
4388 break;
4390 case CONSTRUCTOR:
4391 if (TREE_CONSTANT (t))
4393 /* Don't re-process a constant CONSTRUCTOR, but do fold it to
4394 VECTOR_CST if applicable. */
4395 /* FIXME after GCC 6 branches, make the verify unconditional. */
4396 if (CHECKING_P)
4397 verify_constructor_flags (t);
4398 else
4399 recompute_constructor_flags (t);
4400 if (TREE_CONSTANT (t))
4401 return fold (t);
4403 r = cxx_eval_bare_aggregate (ctx, t, lval,
4404 non_constant_p, overflow_p);
4405 break;
4407 case VEC_INIT_EXPR:
4408 /* We can get this in a defaulted constructor for a class with a
4409 non-static data member of array type. Either the initializer will
4410 be NULL, meaning default-initialization, or it will be an lvalue
4411 or xvalue of the same type, meaning direct-initialization from the
4412 corresponding member. */
4413 r = cxx_eval_vec_init (ctx, t, lval,
4414 non_constant_p, overflow_p);
4415 break;
4417 case FMA_EXPR:
4418 case VEC_PERM_EXPR:
4419 r = cxx_eval_trinary_expression (ctx, t, lval,
4420 non_constant_p, overflow_p);
4421 break;
4423 case CONVERT_EXPR:
4424 case VIEW_CONVERT_EXPR:
4425 case NOP_EXPR:
4426 case UNARY_PLUS_EXPR:
4428 tree oldop = TREE_OPERAND (t, 0);
4430 tree op = cxx_eval_constant_expression (ctx, oldop,
4431 lval,
4432 non_constant_p, overflow_p);
4433 if (*non_constant_p)
4434 return t;
4435 tree type = TREE_TYPE (t);
4436 if (TREE_CODE (op) == PTRMEM_CST
4437 && !TYPE_PTRMEM_P (type))
4438 op = cplus_expand_constant (op);
4439 if (TREE_CODE (op) == PTRMEM_CST && tcode == NOP_EXPR)
4441 if (same_type_ignoring_top_level_qualifiers_p (type,
4442 TREE_TYPE (op))
4443 || can_convert_qual (type, op))
4444 return cp_fold_convert (type, op);
4445 else
4447 if (!ctx->quiet)
4448 error_at (EXPR_LOC_OR_LOC (t, input_location),
4449 "a reinterpret_cast is not a constant expression");
4450 *non_constant_p = true;
4451 return t;
4455 if (POINTER_TYPE_P (type) && TREE_CODE (op) == INTEGER_CST)
4457 if (integer_zerop (op))
4459 if (TREE_CODE (type) == REFERENCE_TYPE)
4461 if (!ctx->quiet)
4462 error_at (EXPR_LOC_OR_LOC (t, input_location),
4463 "dereferencing a null pointer");
4464 *non_constant_p = true;
4465 return t;
4467 else if (TREE_CODE (TREE_TYPE (op)) == POINTER_TYPE)
4469 tree from = TREE_TYPE (op);
4471 if (!can_convert (type, from, tf_none))
4473 if (!ctx->quiet)
4474 error_at (EXPR_LOC_OR_LOC (t, input_location),
4475 "conversion of %qT null pointer to %qT "
4476 "is not a constant expression",
4477 from, type);
4478 *non_constant_p = true;
4479 return t;
4483 else
4485 /* This detects for example:
4486 reinterpret_cast<void*>(sizeof 0)
4488 if (!ctx->quiet)
4489 error_at (EXPR_LOC_OR_LOC (t, input_location),
4490 "%<reinterpret_cast<%T>(%E)%> is not "
4491 "a constant expression",
4492 type, op);
4493 *non_constant_p = true;
4494 return t;
4497 if (op == oldop && tcode != UNARY_PLUS_EXPR)
4498 /* We didn't fold at the top so we could check for ptr-int
4499 conversion. */
4500 return fold (t);
4501 if (tcode == UNARY_PLUS_EXPR)
4502 r = fold_convert (TREE_TYPE (t), op);
4503 else
4504 r = fold_build1 (tcode, type, op);
4505 /* Conversion of an out-of-range value has implementation-defined
4506 behavior; the language considers it different from arithmetic
4507 overflow, which is undefined. */
4508 if (TREE_OVERFLOW_P (r) && !TREE_OVERFLOW_P (op))
4509 TREE_OVERFLOW (r) = false;
4511 break;
4513 case EMPTY_CLASS_EXPR:
4514 /* This is good enough for a function argument that might not get
4515 used, and they can't do anything with it, so just return it. */
4516 return t;
4518 case STATEMENT_LIST:
4519 new_ctx = *ctx;
4520 new_ctx.ctor = new_ctx.object = NULL_TREE;
4521 return cxx_eval_statement_list (&new_ctx, t,
4522 non_constant_p, overflow_p, jump_target);
4524 case BIND_EXPR:
4525 return cxx_eval_constant_expression (ctx, BIND_EXPR_BODY (t),
4526 lval,
4527 non_constant_p, overflow_p,
4528 jump_target);
4530 case PREINCREMENT_EXPR:
4531 case POSTINCREMENT_EXPR:
4532 case PREDECREMENT_EXPR:
4533 case POSTDECREMENT_EXPR:
4534 return cxx_eval_increment_expression (ctx, t,
4535 lval, non_constant_p, overflow_p);
4537 case LAMBDA_EXPR:
4538 case NEW_EXPR:
4539 case VEC_NEW_EXPR:
4540 case DELETE_EXPR:
4541 case VEC_DELETE_EXPR:
4542 case THROW_EXPR:
4543 case MODOP_EXPR:
4544 /* GCC internal stuff. */
4545 case VA_ARG_EXPR:
4546 case OBJ_TYPE_REF:
4547 case NON_DEPENDENT_EXPR:
4548 case BASELINK:
4549 case OFFSET_REF:
4550 if (!ctx->quiet)
4551 error_at (EXPR_LOC_OR_LOC (t, input_location),
4552 "expression %qE is not a constant expression", t);
4553 *non_constant_p = true;
4554 break;
4556 case PLACEHOLDER_EXPR:
4557 /* Use of the value or address of the current object. */
4558 if (tree ctor = lookup_placeholder (ctx, lval, TREE_TYPE (t)))
4559 return cxx_eval_constant_expression (ctx, ctor, lval,
4560 non_constant_p, overflow_p);
4561 /* A placeholder without a referent. We can get here when
4562 checking whether NSDMIs are noexcept, or in massage_init_elt;
4563 just say it's non-constant for now. */
4564 gcc_assert (ctx->quiet);
4565 *non_constant_p = true;
4566 break;
4568 case EXIT_EXPR:
4570 tree cond = TREE_OPERAND (t, 0);
4571 cond = cxx_eval_constant_expression (ctx, cond, /*lval*/false,
4572 non_constant_p, overflow_p);
4573 VERIFY_CONSTANT (cond);
4574 if (integer_nonzerop (cond))
4575 *jump_target = t;
4577 break;
4579 case GOTO_EXPR:
4580 *jump_target = TREE_OPERAND (t, 0);
4581 gcc_assert (breaks (jump_target) || continues (jump_target)
4582 /* Allow for jumping to a cdtor_label. */
4583 || returns (jump_target));
4584 break;
4586 case LOOP_EXPR:
4587 cxx_eval_loop_expr (ctx, t,
4588 non_constant_p, overflow_p, jump_target);
4589 break;
4591 case SWITCH_EXPR:
4592 cxx_eval_switch_expr (ctx, t,
4593 non_constant_p, overflow_p, jump_target);
4594 break;
4596 case REQUIRES_EXPR:
4597 /* It's possible to get a requires-expression in a constant
4598 expression. For example:
4600 template<typename T> concept bool C() {
4601 return requires (T t) { t; };
4604 template<typename T> requires !C<T>() void f(T);
4606 Normalization leaves f with the associated constraint
4607 '!requires (T t) { ... }' which is not transformed into
4608 a constraint. */
4609 if (!processing_template_decl)
4610 return evaluate_constraint_expression (t, NULL_TREE);
4611 else
4612 *non_constant_p = true;
4613 return t;
4615 case ANNOTATE_EXPR:
4616 gcc_assert (tree_to_uhwi (TREE_OPERAND (t, 1)) == annot_expr_ivdep_kind);
4617 r = cxx_eval_constant_expression (ctx, TREE_OPERAND (t, 0),
4618 lval,
4619 non_constant_p, overflow_p,
4620 jump_target);
4621 break;
4623 default:
4624 if (STATEMENT_CODE_P (TREE_CODE (t)))
4626 /* This function doesn't know how to deal with pre-genericize
4627 statements; this can only happen with statement-expressions,
4628 so for now just fail. */
4629 if (!ctx->quiet)
4630 error_at (EXPR_LOCATION (t),
4631 "statement is not a constant expression");
4633 else
4634 internal_error ("unexpected expression %qE of kind %s", t,
4635 get_tree_code_name (TREE_CODE (t)));
4636 *non_constant_p = true;
4637 break;
4640 if (r == error_mark_node)
4641 *non_constant_p = true;
4643 if (*non_constant_p)
4644 return t;
4645 else
4646 return r;
4649 static tree
4650 cxx_eval_outermost_constant_expr (tree t, bool allow_non_constant,
4651 bool strict = true, tree object = NULL_TREE)
4653 auto_timevar time (TV_CONSTEXPR);
4655 bool non_constant_p = false;
4656 bool overflow_p = false;
4657 hash_map<tree,tree> map;
4659 constexpr_ctx ctx = { NULL, &map, NULL, NULL, NULL, NULL,
4660 allow_non_constant, strict };
4662 tree type = initialized_type (t);
4663 tree r = t;
4664 if (AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type))
4666 /* In C++14 an NSDMI can participate in aggregate initialization,
4667 and can refer to the address of the object being initialized, so
4668 we need to pass in the relevant VAR_DECL if we want to do the
4669 evaluation in a single pass. The evaluation will dynamically
4670 update ctx.values for the VAR_DECL. We use the same strategy
4671 for C++11 constexpr constructors that refer to the object being
4672 initialized. */
4673 ctx.ctor = build_constructor (type, NULL);
4674 CONSTRUCTOR_NO_IMPLICIT_ZERO (ctx.ctor) = true;
4675 if (!object)
4677 if (TREE_CODE (t) == TARGET_EXPR)
4678 object = TARGET_EXPR_SLOT (t);
4679 else if (TREE_CODE (t) == AGGR_INIT_EXPR)
4680 object = AGGR_INIT_EXPR_SLOT (t);
4682 ctx.object = object;
4683 if (object)
4684 gcc_assert (same_type_ignoring_top_level_qualifiers_p
4685 (type, TREE_TYPE (object)));
4686 if (object && DECL_P (object))
4687 map.put (object, ctx.ctor);
4688 if (TREE_CODE (r) == TARGET_EXPR)
4689 /* Avoid creating another CONSTRUCTOR when we expand the
4690 TARGET_EXPR. */
4691 r = TARGET_EXPR_INITIAL (r);
4694 r = cxx_eval_constant_expression (&ctx, r,
4695 false, &non_constant_p, &overflow_p);
4697 verify_constant (r, allow_non_constant, &non_constant_p, &overflow_p);
4699 /* Mutable logic is a bit tricky: we want to allow initialization of
4700 constexpr variables with mutable members, but we can't copy those
4701 members to another constexpr variable. */
4702 if (TREE_CODE (r) == CONSTRUCTOR
4703 && CONSTRUCTOR_MUTABLE_POISON (r))
4705 if (!allow_non_constant)
4706 error ("%qE is not a constant expression because it refers to "
4707 "mutable subobjects of %qT", t, type);
4708 non_constant_p = true;
4711 if (TREE_CODE (r) == CONSTRUCTOR
4712 && CONSTRUCTOR_NO_IMPLICIT_ZERO (r))
4714 if (!allow_non_constant)
4715 error ("%qE is not a constant expression because it refers to "
4716 "an incompletely initialized variable", t);
4717 TREE_CONSTANT (r) = false;
4718 non_constant_p = true;
4721 /* Technically we should check this for all subexpressions, but that
4722 runs into problems with our internal representation of pointer
4723 subtraction and the 5.19 rules are still in flux. */
4724 if (CONVERT_EXPR_CODE_P (TREE_CODE (r))
4725 && ARITHMETIC_TYPE_P (TREE_TYPE (r))
4726 && TREE_CODE (TREE_OPERAND (r, 0)) == ADDR_EXPR)
4728 if (!allow_non_constant)
4729 error ("conversion from pointer type %qT "
4730 "to arithmetic type %qT in a constant expression",
4731 TREE_TYPE (TREE_OPERAND (r, 0)), TREE_TYPE (r));
4732 non_constant_p = true;
4735 if (!non_constant_p && overflow_p)
4736 non_constant_p = true;
4738 /* Unshare the result unless it's a CONSTRUCTOR in which case it's already
4739 unshared. */
4740 bool should_unshare = true;
4741 if (r == t || TREE_CODE (r) == CONSTRUCTOR)
4742 should_unshare = false;
4744 if (non_constant_p && !allow_non_constant)
4745 return error_mark_node;
4746 else if (non_constant_p && TREE_CONSTANT (r))
4748 /* This isn't actually constant, so unset TREE_CONSTANT. */
4749 if (EXPR_P (r))
4750 r = copy_node (r);
4751 else if (TREE_CODE (r) == CONSTRUCTOR)
4752 r = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (r), r);
4753 else
4754 r = build_nop (TREE_TYPE (r), r);
4755 TREE_CONSTANT (r) = false;
4757 else if (non_constant_p || r == t)
4758 return t;
4760 if (should_unshare)
4761 r = unshare_expr (r);
4763 if (TREE_CODE (r) == CONSTRUCTOR && CLASS_TYPE_P (TREE_TYPE (r)))
4765 if (TREE_CODE (t) == TARGET_EXPR
4766 && TARGET_EXPR_INITIAL (t) == r)
4767 return t;
4768 else
4770 r = get_target_expr (r);
4771 TREE_CONSTANT (r) = true;
4772 return r;
4775 else
4776 return r;
4779 /* Returns true if T is a valid subexpression of a constant expression,
4780 even if it isn't itself a constant expression. */
4782 bool
4783 is_sub_constant_expr (tree t)
4785 bool non_constant_p = false;
4786 bool overflow_p = false;
4787 hash_map <tree, tree> map;
4789 constexpr_ctx ctx = { NULL, &map, NULL, NULL, NULL, NULL, true, true };
4791 cxx_eval_constant_expression (&ctx, t, false, &non_constant_p,
4792 &overflow_p);
4793 return !non_constant_p && !overflow_p;
4796 /* If T represents a constant expression returns its reduced value.
4797 Otherwise return error_mark_node. If T is dependent, then
4798 return NULL. */
4800 tree
4801 cxx_constant_value (tree t, tree decl)
4803 return cxx_eval_outermost_constant_expr (t, false, true, decl);
4806 /* Helper routine for fold_simple function. Either return simplified
4807 expression T, otherwise NULL_TREE.
4808 In contrast to cp_fully_fold, and to maybe_constant_value, we try to fold
4809 even if we are within template-declaration. So be careful on call, as in
4810 such case types can be undefined. */
4812 static tree
4813 fold_simple_1 (tree t)
4815 tree op1;
4816 enum tree_code code = TREE_CODE (t);
4818 switch (code)
4820 case INTEGER_CST:
4821 case REAL_CST:
4822 case VECTOR_CST:
4823 case FIXED_CST:
4824 case COMPLEX_CST:
4825 return t;
4827 case SIZEOF_EXPR:
4828 return fold_sizeof_expr (t);
4830 case ABS_EXPR:
4831 case CONJ_EXPR:
4832 case REALPART_EXPR:
4833 case IMAGPART_EXPR:
4834 case NEGATE_EXPR:
4835 case BIT_NOT_EXPR:
4836 case TRUTH_NOT_EXPR:
4837 case NOP_EXPR:
4838 case VIEW_CONVERT_EXPR:
4839 case CONVERT_EXPR:
4840 case FLOAT_EXPR:
4841 case FIX_TRUNC_EXPR:
4842 case FIXED_CONVERT_EXPR:
4843 case ADDR_SPACE_CONVERT_EXPR:
4845 op1 = TREE_OPERAND (t, 0);
4847 t = const_unop (code, TREE_TYPE (t), op1);
4848 if (!t)
4849 return NULL_TREE;
4851 if (CONVERT_EXPR_CODE_P (code)
4852 && TREE_OVERFLOW_P (t) && !TREE_OVERFLOW_P (op1))
4853 TREE_OVERFLOW (t) = false;
4854 return t;
4856 default:
4857 return NULL_TREE;
4861 /* If T is a simple constant expression, returns its simplified value.
4862 Otherwise returns T. In contrast to maybe_constant_value do we
4863 simplify only few operations on constant-expressions, and we don't
4864 try to simplify constexpressions. */
4866 tree
4867 fold_simple (tree t)
4869 tree r = NULL_TREE;
4870 if (processing_template_decl)
4871 return t;
4873 r = fold_simple_1 (t);
4874 if (!r)
4875 r = t;
4877 return r;
4880 /* If T is a constant expression, returns its reduced value.
4881 Otherwise, if T does not have TREE_CONSTANT set, returns T.
4882 Otherwise, returns a version of T without TREE_CONSTANT. */
4884 static GTY((deletable)) hash_map<tree, tree> *cv_cache;
4886 tree
4887 maybe_constant_value (tree t, tree decl)
4889 tree r;
4891 if (!is_nondependent_constant_expression (t))
4893 if (TREE_OVERFLOW_P (t))
4895 t = build_nop (TREE_TYPE (t), t);
4896 TREE_CONSTANT (t) = false;
4898 return t;
4900 else if (CONSTANT_CLASS_P (t))
4901 /* No caching or evaluation needed. */
4902 return t;
4904 if (cv_cache == NULL)
4905 cv_cache = hash_map<tree, tree>::create_ggc (101);
4906 if (tree *cached = cv_cache->get (t))
4907 return *cached;
4909 r = cxx_eval_outermost_constant_expr (t, true, true, decl);
4910 gcc_checking_assert (r == t
4911 || CONVERT_EXPR_P (t)
4912 || TREE_CODE (t) == VIEW_CONVERT_EXPR
4913 || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
4914 || !cp_tree_equal (r, t));
4915 cv_cache->put (t, r);
4916 return r;
4919 /* Dispose of the whole CV_CACHE. */
4921 static void
4922 clear_cv_cache (void)
4924 if (cv_cache != NULL)
4925 cv_cache->empty ();
4928 /* Dispose of the whole CV_CACHE and FOLD_CACHE. */
4930 void
4931 clear_cv_and_fold_caches (void)
4933 clear_cv_cache ();
4934 clear_fold_cache ();
4937 /* Like maybe_constant_value but first fully instantiate the argument.
4939 Note: this is equivalent to instantiate_non_dependent_expr_sfinae
4940 (t, tf_none) followed by maybe_constant_value but is more efficient,
4941 because calls instantiation_dependent_expression_p and
4942 potential_constant_expression at most once. */
4944 tree
4945 fold_non_dependent_expr (tree t)
4947 if (t == NULL_TREE)
4948 return NULL_TREE;
4950 /* If we're in a template, but T isn't value dependent, simplify
4951 it. We're supposed to treat:
4953 template <typename T> void f(T[1 + 1]);
4954 template <typename T> void f(T[2]);
4956 as two declarations of the same function, for example. */
4957 if (processing_template_decl)
4959 if (is_nondependent_constant_expression (t))
4961 processing_template_decl_sentinel s;
4962 t = instantiate_non_dependent_expr_internal (t, tf_none);
4964 if (type_unknown_p (t)
4965 || BRACE_ENCLOSED_INITIALIZER_P (t))
4967 if (TREE_OVERFLOW_P (t))
4969 t = build_nop (TREE_TYPE (t), t);
4970 TREE_CONSTANT (t) = false;
4972 return t;
4975 tree r = cxx_eval_outermost_constant_expr (t, true, true, NULL_TREE);
4976 /* cp_tree_equal looks through NOPs, so allow them. */
4977 gcc_checking_assert (r == t
4978 || CONVERT_EXPR_P (t)
4979 || TREE_CODE (t) == VIEW_CONVERT_EXPR
4980 || (TREE_CONSTANT (t) && !TREE_CONSTANT (r))
4981 || !cp_tree_equal (r, t));
4982 return r;
4984 else if (TREE_OVERFLOW_P (t))
4986 t = build_nop (TREE_TYPE (t), t);
4987 TREE_CONSTANT (t) = false;
4989 return t;
4992 return maybe_constant_value (t);
4995 /* Like maybe_constant_value, but returns a CONSTRUCTOR directly, rather
4996 than wrapped in a TARGET_EXPR. */
4998 tree
4999 maybe_constant_init (tree t, tree decl)
5001 if (!t)
5002 return t;
5003 if (TREE_CODE (t) == EXPR_STMT)
5004 t = TREE_OPERAND (t, 0);
5005 if (TREE_CODE (t) == CONVERT_EXPR
5006 && VOID_TYPE_P (TREE_TYPE (t)))
5007 t = TREE_OPERAND (t, 0);
5008 if (TREE_CODE (t) == INIT_EXPR)
5009 t = TREE_OPERAND (t, 1);
5010 if (TREE_CODE (t) == TARGET_EXPR)
5011 t = TARGET_EXPR_INITIAL (t);
5012 if (!is_nondependent_static_init_expression (t))
5013 /* Don't try to evaluate it. */;
5014 else if (CONSTANT_CLASS_P (t))
5015 /* No evaluation needed. */;
5016 else
5017 t = cxx_eval_outermost_constant_expr (t, true, false, decl);
5018 if (TREE_CODE (t) == TARGET_EXPR)
5020 tree init = TARGET_EXPR_INITIAL (t);
5021 if (TREE_CODE (init) == CONSTRUCTOR)
5022 t = init;
5024 return t;
5027 #if 0
5028 /* FIXME see ADDR_EXPR section in potential_constant_expression_1. */
5029 /* Return true if the object referred to by REF has automatic or thread
5030 local storage. */
5032 enum { ck_ok, ck_bad, ck_unknown };
5033 static int
5034 check_automatic_or_tls (tree ref)
5036 machine_mode mode;
5037 HOST_WIDE_INT bitsize, bitpos;
5038 tree offset;
5039 int volatilep = 0, unsignedp = 0;
5040 tree decl = get_inner_reference (ref, &bitsize, &bitpos, &offset,
5041 &mode, &unsignedp, &volatilep, false);
5042 duration_kind dk;
5044 /* If there isn't a decl in the middle, we don't know the linkage here,
5045 and this isn't a constant expression anyway. */
5046 if (!DECL_P (decl))
5047 return ck_unknown;
5048 dk = decl_storage_duration (decl);
5049 return (dk == dk_auto || dk == dk_thread) ? ck_bad : ck_ok;
5051 #endif
5053 /* Return true if T denotes a potentially constant expression. Issue
5054 diagnostic as appropriate under control of FLAGS. If WANT_RVAL is true,
5055 an lvalue-rvalue conversion is implied. If NOW is true, we want to
5056 consider the expression in the current context, independent of constexpr
5057 substitution.
5059 C++0x [expr.const] used to say
5061 6 An expression is a potential constant expression if it is
5062 a constant expression where all occurrences of function
5063 parameters are replaced by arbitrary constant expressions
5064 of the appropriate type.
5066 2 A conditional expression is a constant expression unless it
5067 involves one of the following as a potentially evaluated
5068 subexpression (3.2), but subexpressions of logical AND (5.14),
5069 logical OR (5.15), and conditional (5.16) operations that are
5070 not evaluated are not considered. */
5072 static bool
5073 potential_constant_expression_1 (tree t, bool want_rval, bool strict, bool now,
5074 tsubst_flags_t flags)
5076 #define RECUR(T,RV) \
5077 potential_constant_expression_1 ((T), (RV), strict, now, flags)
5079 enum { any = false, rval = true };
5080 int i;
5081 tree tmp;
5083 if (t == error_mark_node)
5084 return false;
5085 if (t == NULL_TREE)
5086 return true;
5087 location_t loc = EXPR_LOC_OR_LOC (t, input_location);
5088 if (TREE_THIS_VOLATILE (t) && !DECL_P (t))
5090 if (flags & tf_error)
5091 error_at (loc, "expression %qE has side-effects", t);
5092 return false;
5094 if (CONSTANT_CLASS_P (t))
5095 return true;
5096 if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_TYPED)
5097 && TREE_TYPE (t) == error_mark_node)
5098 return false;
5100 switch (TREE_CODE (t))
5102 case FUNCTION_DECL:
5103 case BASELINK:
5104 case TEMPLATE_DECL:
5105 case OVERLOAD:
5106 case TEMPLATE_ID_EXPR:
5107 case LABEL_DECL:
5108 case LABEL_EXPR:
5109 case CASE_LABEL_EXPR:
5110 case CONST_DECL:
5111 case SIZEOF_EXPR:
5112 case ALIGNOF_EXPR:
5113 case OFFSETOF_EXPR:
5114 case NOEXCEPT_EXPR:
5115 case TEMPLATE_PARM_INDEX:
5116 case TRAIT_EXPR:
5117 case IDENTIFIER_NODE:
5118 case USERDEF_LITERAL:
5119 /* We can see a FIELD_DECL in a pointer-to-member expression. */
5120 case FIELD_DECL:
5121 case RESULT_DECL:
5122 case USING_DECL:
5123 case USING_STMT:
5124 case PLACEHOLDER_EXPR:
5125 case BREAK_STMT:
5126 case CONTINUE_STMT:
5127 case REQUIRES_EXPR:
5128 case STATIC_ASSERT:
5129 return true;
5131 case PARM_DECL:
5132 if (now)
5134 if (flags & tf_error)
5135 error ("%qE is not a constant expression", t);
5136 return false;
5138 return true;
5140 case AGGR_INIT_EXPR:
5141 case CALL_EXPR:
5142 /* -- an invocation of a function other than a constexpr function
5143 or a constexpr constructor. */
5145 tree fun = get_function_named_in_call (t);
5146 const int nargs = call_expr_nargs (t);
5147 i = 0;
5149 if (fun == NULL_TREE)
5151 /* Reset to allow the function to continue past the end
5152 of the block below. Otherwise return early. */
5153 bool bail = true;
5155 if (TREE_CODE (t) == CALL_EXPR
5156 && CALL_EXPR_FN (t) == NULL_TREE)
5157 switch (CALL_EXPR_IFN (t))
5159 /* These should be ignored, they are optimized away from
5160 constexpr functions. */
5161 case IFN_UBSAN_NULL:
5162 case IFN_UBSAN_BOUNDS:
5163 case IFN_UBSAN_VPTR:
5164 case IFN_FALLTHROUGH:
5165 return true;
5167 case IFN_ADD_OVERFLOW:
5168 case IFN_SUB_OVERFLOW:
5169 case IFN_MUL_OVERFLOW:
5170 case IFN_LAUNDER:
5171 bail = false;
5173 default:
5174 break;
5177 if (bail)
5179 /* fold_call_expr can't do anything with IFN calls. */
5180 if (flags & tf_error)
5181 error_at (loc, "call to internal function %qE", t);
5182 return false;
5186 if (fun && is_overloaded_fn (fun))
5188 if (TREE_CODE (fun) == FUNCTION_DECL)
5190 if (builtin_valid_in_constant_expr_p (fun))
5191 return true;
5192 if (!DECL_DECLARED_CONSTEXPR_P (fun)
5193 /* Allow any built-in function; if the expansion
5194 isn't constant, we'll deal with that then. */
5195 && !is_builtin_fn (fun))
5197 if (flags & tf_error)
5199 error_at (loc, "call to non-constexpr function %qD",
5200 fun);
5201 explain_invalid_constexpr_fn (fun);
5203 return false;
5205 /* A call to a non-static member function takes the address
5206 of the object as the first argument. But in a constant
5207 expression the address will be folded away, so look
5208 through it now. */
5209 if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fun)
5210 && !DECL_CONSTRUCTOR_P (fun))
5212 tree x = get_nth_callarg (t, 0);
5213 if (is_this_parameter (x))
5214 return true;
5215 /* Don't require an immediately constant value, as
5216 constexpr substitution might not use the value. */
5217 bool sub_now = false;
5218 if (!potential_constant_expression_1 (x, rval, strict,
5219 sub_now, flags))
5220 return false;
5221 i = 1;
5224 else
5226 if (!RECUR (fun, true))
5227 return false;
5228 fun = get_first_fn (fun);
5230 /* Skip initial arguments to base constructors. */
5231 if (DECL_BASE_CONSTRUCTOR_P (fun))
5232 i = num_artificial_parms_for (fun);
5233 fun = DECL_ORIGIN (fun);
5235 else if (fun)
5237 if (RECUR (fun, rval))
5238 /* Might end up being a constant function pointer. */;
5239 else
5240 return false;
5242 for (; i < nargs; ++i)
5244 tree x = get_nth_callarg (t, i);
5245 /* In a template, reference arguments haven't been converted to
5246 REFERENCE_TYPE and we might not even know if the parameter
5247 is a reference, so accept lvalue constants too. */
5248 bool rv = processing_template_decl ? any : rval;
5249 /* Don't require an immediately constant value, as constexpr
5250 substitution might not use the value of the argument. */
5251 bool sub_now = false;
5252 if (!potential_constant_expression_1 (x, rv, strict,
5253 sub_now, flags))
5254 return false;
5256 return true;
5259 case NON_LVALUE_EXPR:
5260 /* -- an lvalue-to-rvalue conversion (4.1) unless it is applied to
5261 -- an lvalue of integral type that refers to a non-volatile
5262 const variable or static data member initialized with
5263 constant expressions, or
5265 -- an lvalue of literal type that refers to non-volatile
5266 object defined with constexpr, or that refers to a
5267 sub-object of such an object; */
5268 return RECUR (TREE_OPERAND (t, 0), rval);
5270 case VAR_DECL:
5271 if (DECL_HAS_VALUE_EXPR_P (t))
5272 return RECUR (DECL_VALUE_EXPR (t), rval);
5273 if (want_rval
5274 && !var_in_maybe_constexpr_fn (t)
5275 && !type_dependent_expression_p (t)
5276 && !decl_maybe_constant_var_p (t)
5277 && (strict
5278 || !CP_TYPE_CONST_NON_VOLATILE_P (TREE_TYPE (t))
5279 || (DECL_INITIAL (t)
5280 && !DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t)))
5281 && COMPLETE_TYPE_P (TREE_TYPE (t))
5282 && !is_really_empty_class (TREE_TYPE (t)))
5284 if (flags & tf_error)
5285 non_const_var_error (t);
5286 return false;
5288 return true;
5290 case NOP_EXPR:
5291 case CONVERT_EXPR:
5292 case VIEW_CONVERT_EXPR:
5293 /* -- a reinterpret_cast. FIXME not implemented, and this rule
5294 may change to something more specific to type-punning (DR 1312). */
5296 tree from = TREE_OPERAND (t, 0);
5297 if (POINTER_TYPE_P (TREE_TYPE (t))
5298 && TREE_CODE (from) == INTEGER_CST
5299 && !integer_zerop (from))
5301 if (flags & tf_error)
5302 error_at (loc, "reinterpret_cast from integer to pointer");
5303 return false;
5305 return (RECUR (from, TREE_CODE (t) != VIEW_CONVERT_EXPR));
5308 case ADDRESSOF_EXPR:
5309 /* This is like ADDR_EXPR, except it won't form pointer-to-member. */
5310 t = TREE_OPERAND (t, 0);
5311 goto handle_addr_expr;
5313 case ADDR_EXPR:
5314 /* -- a unary operator & that is applied to an lvalue that
5315 designates an object with thread or automatic storage
5316 duration; */
5317 t = TREE_OPERAND (t, 0);
5319 if (TREE_CODE (t) == OFFSET_REF && PTRMEM_OK_P (t))
5320 /* A pointer-to-member constant. */
5321 return true;
5323 handle_addr_expr:
5324 #if 0
5325 /* FIXME adjust when issue 1197 is fully resolved. For now don't do
5326 any checking here, as we might dereference the pointer later. If
5327 we remove this code, also remove check_automatic_or_tls. */
5328 i = check_automatic_or_tls (t);
5329 if (i == ck_ok)
5330 return true;
5331 if (i == ck_bad)
5333 if (flags & tf_error)
5334 error ("address-of an object %qE with thread local or "
5335 "automatic storage is not a constant expression", t);
5336 return false;
5338 #endif
5339 return RECUR (t, any);
5341 case REALPART_EXPR:
5342 case IMAGPART_EXPR:
5343 case COMPONENT_REF:
5344 case BIT_FIELD_REF:
5345 case ARROW_EXPR:
5346 case OFFSET_REF:
5347 /* -- a class member access unless its postfix-expression is
5348 of literal type or of pointer to literal type. */
5349 /* This test would be redundant, as it follows from the
5350 postfix-expression being a potential constant expression. */
5351 if (type_unknown_p (t))
5352 return true;
5353 return RECUR (TREE_OPERAND (t, 0), want_rval);
5355 case EXPR_PACK_EXPANSION:
5356 return RECUR (PACK_EXPANSION_PATTERN (t), want_rval);
5358 case INDIRECT_REF:
5360 tree x = TREE_OPERAND (t, 0);
5361 STRIP_NOPS (x);
5362 if (is_this_parameter (x) && !is_capture_proxy (x))
5364 if (!var_in_maybe_constexpr_fn (x))
5366 if (flags & tf_error)
5367 error_at (loc, "use of %<this%> in a constant expression");
5368 return false;
5370 return true;
5372 return RECUR (x, rval);
5375 case STATEMENT_LIST:
5377 tree_stmt_iterator i;
5378 for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
5380 if (!RECUR (tsi_stmt (i), any))
5381 return false;
5383 return true;
5385 break;
5387 case MODIFY_EXPR:
5388 if (cxx_dialect < cxx14)
5389 goto fail;
5390 if (!RECUR (TREE_OPERAND (t, 0), any))
5391 return false;
5392 if (!RECUR (TREE_OPERAND (t, 1), rval))
5393 return false;
5394 return true;
5396 case MODOP_EXPR:
5397 if (cxx_dialect < cxx14)
5398 goto fail;
5399 if (!RECUR (TREE_OPERAND (t, 0), rval))
5400 return false;
5401 if (!RECUR (TREE_OPERAND (t, 2), rval))
5402 return false;
5403 return true;
5405 case DO_STMT:
5406 if (!RECUR (DO_COND (t), rval))
5407 return false;
5408 if (!RECUR (DO_BODY (t), any))
5409 return false;
5410 return true;
5412 case FOR_STMT:
5413 if (!RECUR (FOR_INIT_STMT (t), any))
5414 return false;
5415 if (!RECUR (FOR_COND (t), rval))
5416 return false;
5417 if (!RECUR (FOR_EXPR (t), any))
5418 return false;
5419 if (!RECUR (FOR_BODY (t), any))
5420 return false;
5421 return true;
5423 case RANGE_FOR_STMT:
5424 if (!RECUR (RANGE_FOR_EXPR (t), any))
5425 return false;
5426 if (!RECUR (RANGE_FOR_BODY (t), any))
5427 return false;
5428 return true;
5430 case WHILE_STMT:
5431 if (!RECUR (WHILE_COND (t), rval))
5432 return false;
5433 if (!RECUR (WHILE_BODY (t), any))
5434 return false;
5435 return true;
5437 case SWITCH_STMT:
5438 if (!RECUR (SWITCH_STMT_COND (t), rval))
5439 return false;
5440 /* FIXME we don't check SWITCH_STMT_BODY currently, because even
5441 unreachable labels would be checked. */
5442 return true;
5444 case STMT_EXPR:
5445 return RECUR (STMT_EXPR_STMT (t), rval);
5447 case LAMBDA_EXPR:
5448 case DYNAMIC_CAST_EXPR:
5449 case PSEUDO_DTOR_EXPR:
5450 case NEW_EXPR:
5451 case VEC_NEW_EXPR:
5452 case DELETE_EXPR:
5453 case VEC_DELETE_EXPR:
5454 case THROW_EXPR:
5455 case OMP_PARALLEL:
5456 case OMP_TASK:
5457 case OMP_FOR:
5458 case OMP_DISTRIBUTE:
5459 case OMP_TASKLOOP:
5460 case OMP_TEAMS:
5461 case OMP_TARGET_DATA:
5462 case OMP_TARGET:
5463 case OMP_SECTIONS:
5464 case OMP_ORDERED:
5465 case OMP_CRITICAL:
5466 case OMP_SINGLE:
5467 case OMP_SECTION:
5468 case OMP_MASTER:
5469 case OMP_TASKGROUP:
5470 case OMP_TARGET_UPDATE:
5471 case OMP_TARGET_ENTER_DATA:
5472 case OMP_TARGET_EXIT_DATA:
5473 case OMP_ATOMIC:
5474 case OMP_ATOMIC_READ:
5475 case OMP_ATOMIC_CAPTURE_OLD:
5476 case OMP_ATOMIC_CAPTURE_NEW:
5477 case OACC_PARALLEL:
5478 case OACC_KERNELS:
5479 case OACC_DATA:
5480 case OACC_HOST_DATA:
5481 case OACC_LOOP:
5482 case OACC_CACHE:
5483 case OACC_DECLARE:
5484 case OACC_ENTER_DATA:
5485 case OACC_EXIT_DATA:
5486 case OACC_UPDATE:
5487 case CILK_SIMD:
5488 case CILK_FOR:
5489 /* GCC internal stuff. */
5490 case VA_ARG_EXPR:
5491 case OBJ_TYPE_REF:
5492 case TRANSACTION_EXPR:
5493 case ASM_EXPR:
5494 case AT_ENCODE_EXPR:
5495 fail:
5496 if (flags & tf_error)
5497 error_at (loc, "expression %qE is not a constant expression", t);
5498 return false;
5500 case TYPEID_EXPR:
5501 /* -- a typeid expression whose operand is of polymorphic
5502 class type; */
5504 tree e = TREE_OPERAND (t, 0);
5505 if (!TYPE_P (e) && !type_dependent_expression_p (e)
5506 && TYPE_POLYMORPHIC_P (TREE_TYPE (e)))
5508 if (flags & tf_error)
5509 error_at (loc, "typeid-expression is not a constant expression "
5510 "because %qE is of polymorphic type", e);
5511 return false;
5513 return true;
5516 case MINUS_EXPR:
5517 want_rval = true;
5518 goto binary;
5520 case LT_EXPR:
5521 case LE_EXPR:
5522 case GT_EXPR:
5523 case GE_EXPR:
5524 case EQ_EXPR:
5525 case NE_EXPR:
5526 want_rval = true;
5527 goto binary;
5529 case PREINCREMENT_EXPR:
5530 case POSTINCREMENT_EXPR:
5531 case PREDECREMENT_EXPR:
5532 case POSTDECREMENT_EXPR:
5533 if (cxx_dialect < cxx14)
5534 goto fail;
5535 goto unary;
5537 case BIT_NOT_EXPR:
5538 /* A destructor. */
5539 if (TYPE_P (TREE_OPERAND (t, 0)))
5540 return true;
5541 /* fall through. */
5543 case CONJ_EXPR:
5544 case SAVE_EXPR:
5545 case FIX_TRUNC_EXPR:
5546 case FLOAT_EXPR:
5547 case NEGATE_EXPR:
5548 case ABS_EXPR:
5549 case TRUTH_NOT_EXPR:
5550 case FIXED_CONVERT_EXPR:
5551 case UNARY_PLUS_EXPR:
5552 case UNARY_LEFT_FOLD_EXPR:
5553 case UNARY_RIGHT_FOLD_EXPR:
5554 unary:
5555 return RECUR (TREE_OPERAND (t, 0), rval);
5557 case CAST_EXPR:
5558 case CONST_CAST_EXPR:
5559 case STATIC_CAST_EXPR:
5560 case REINTERPRET_CAST_EXPR:
5561 case IMPLICIT_CONV_EXPR:
5562 if (cxx_dialect < cxx11
5563 && !dependent_type_p (TREE_TYPE (t))
5564 && !INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t)))
5565 /* In C++98, a conversion to non-integral type can't be part of a
5566 constant expression. */
5568 if (flags & tf_error)
5569 error_at (loc,
5570 "cast to non-integral type %qT in a constant expression",
5571 TREE_TYPE (t));
5572 return false;
5575 return (RECUR (TREE_OPERAND (t, 0),
5576 TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE));
5578 case BIND_EXPR:
5579 return RECUR (BIND_EXPR_BODY (t), want_rval);
5581 case CLEANUP_POINT_EXPR:
5582 case MUST_NOT_THROW_EXPR:
5583 case TRY_CATCH_EXPR:
5584 case TRY_BLOCK:
5585 case EH_SPEC_BLOCK:
5586 case EXPR_STMT:
5587 case PAREN_EXPR:
5588 case NON_DEPENDENT_EXPR:
5589 /* For convenience. */
5590 case RETURN_EXPR:
5591 case LOOP_EXPR:
5592 case EXIT_EXPR:
5593 return RECUR (TREE_OPERAND (t, 0), want_rval);
5595 case DECL_EXPR:
5596 tmp = DECL_EXPR_DECL (t);
5597 if (VAR_P (tmp) && !DECL_ARTIFICIAL (tmp))
5599 if (TREE_STATIC (tmp))
5601 if (flags & tf_error)
5602 error_at (DECL_SOURCE_LOCATION (tmp), "%qD declared "
5603 "%<static%> in %<constexpr%> context", tmp);
5604 return false;
5606 else if (CP_DECL_THREAD_LOCAL_P (tmp))
5608 if (flags & tf_error)
5609 error_at (DECL_SOURCE_LOCATION (tmp), "%qD declared "
5610 "%<thread_local%> in %<constexpr%> context", tmp);
5611 return false;
5613 else if (!DECL_NONTRIVIALLY_INITIALIZED_P (tmp))
5615 if (flags & tf_error)
5616 error_at (DECL_SOURCE_LOCATION (tmp), "uninitialized "
5617 "variable %qD in %<constexpr%> context", tmp);
5618 return false;
5621 return RECUR (tmp, want_rval);
5623 case TRY_FINALLY_EXPR:
5624 return (RECUR (TREE_OPERAND (t, 0), want_rval)
5625 && RECUR (TREE_OPERAND (t, 1), any));
5627 case SCOPE_REF:
5628 return RECUR (TREE_OPERAND (t, 1), want_rval);
5630 case TARGET_EXPR:
5631 if (!literal_type_p (TREE_TYPE (t)))
5633 if (flags & tf_error)
5635 error_at (loc, "temporary of non-literal type %qT in a "
5636 "constant expression", TREE_TYPE (t));
5637 explain_non_literal_class (TREE_TYPE (t));
5639 return false;
5641 /* FALLTHRU */
5642 case INIT_EXPR:
5643 return RECUR (TREE_OPERAND (t, 1), rval);
5645 case CONSTRUCTOR:
5647 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (t);
5648 constructor_elt *ce;
5649 for (i = 0; vec_safe_iterate (v, i, &ce); ++i)
5650 if (!RECUR (ce->value, want_rval))
5651 return false;
5652 return true;
5655 case TREE_LIST:
5657 gcc_assert (TREE_PURPOSE (t) == NULL_TREE
5658 || DECL_P (TREE_PURPOSE (t)));
5659 if (!RECUR (TREE_VALUE (t), want_rval))
5660 return false;
5661 if (TREE_CHAIN (t) == NULL_TREE)
5662 return true;
5663 return RECUR (TREE_CHAIN (t), want_rval);
5666 case TRUNC_DIV_EXPR:
5667 case CEIL_DIV_EXPR:
5668 case FLOOR_DIV_EXPR:
5669 case ROUND_DIV_EXPR:
5670 case TRUNC_MOD_EXPR:
5671 case CEIL_MOD_EXPR:
5672 case ROUND_MOD_EXPR:
5674 tree denom = TREE_OPERAND (t, 1);
5675 if (!RECUR (denom, rval))
5676 return false;
5677 /* We can't call cxx_eval_outermost_constant_expr on an expression
5678 that hasn't been through instantiate_non_dependent_expr yet. */
5679 if (!processing_template_decl)
5680 denom = cxx_eval_outermost_constant_expr (denom, true);
5681 if (integer_zerop (denom))
5683 if (flags & tf_error)
5684 error ("division by zero is not a constant expression");
5685 return false;
5687 else
5689 want_rval = true;
5690 return RECUR (TREE_OPERAND (t, 0), want_rval);
5694 case COMPOUND_EXPR:
5696 /* check_return_expr sometimes wraps a TARGET_EXPR in a
5697 COMPOUND_EXPR; don't get confused. Also handle EMPTY_CLASS_EXPR
5698 introduced by build_call_a. */
5699 tree op0 = TREE_OPERAND (t, 0);
5700 tree op1 = TREE_OPERAND (t, 1);
5701 STRIP_NOPS (op1);
5702 if ((TREE_CODE (op0) == TARGET_EXPR && op1 == TARGET_EXPR_SLOT (op0))
5703 || TREE_CODE (op1) == EMPTY_CLASS_EXPR)
5704 return RECUR (op0, want_rval);
5705 else
5706 goto binary;
5709 /* If the first operand is the non-short-circuit constant, look at
5710 the second operand; otherwise we only care about the first one for
5711 potentiality. */
5712 case TRUTH_AND_EXPR:
5713 case TRUTH_ANDIF_EXPR:
5714 tmp = boolean_true_node;
5715 goto truth;
5716 case TRUTH_OR_EXPR:
5717 case TRUTH_ORIF_EXPR:
5718 tmp = boolean_false_node;
5719 truth:
5721 tree op = TREE_OPERAND (t, 0);
5722 if (!RECUR (op, rval))
5723 return false;
5724 if (!processing_template_decl)
5725 op = cxx_eval_outermost_constant_expr (op, true);
5726 if (tree_int_cst_equal (op, tmp))
5727 return RECUR (TREE_OPERAND (t, 1), rval);
5728 else
5729 return true;
5732 case PLUS_EXPR:
5733 case MULT_EXPR:
5734 case POINTER_PLUS_EXPR:
5735 case RDIV_EXPR:
5736 case EXACT_DIV_EXPR:
5737 case MIN_EXPR:
5738 case MAX_EXPR:
5739 case LSHIFT_EXPR:
5740 case RSHIFT_EXPR:
5741 case LROTATE_EXPR:
5742 case RROTATE_EXPR:
5743 case BIT_IOR_EXPR:
5744 case BIT_XOR_EXPR:
5745 case BIT_AND_EXPR:
5746 case TRUTH_XOR_EXPR:
5747 case UNORDERED_EXPR:
5748 case ORDERED_EXPR:
5749 case UNLT_EXPR:
5750 case UNLE_EXPR:
5751 case UNGT_EXPR:
5752 case UNGE_EXPR:
5753 case UNEQ_EXPR:
5754 case LTGT_EXPR:
5755 case RANGE_EXPR:
5756 case COMPLEX_EXPR:
5757 want_rval = true;
5758 /* Fall through. */
5759 case ARRAY_REF:
5760 case ARRAY_RANGE_REF:
5761 case MEMBER_REF:
5762 case DOTSTAR_EXPR:
5763 case MEM_REF:
5764 case BINARY_LEFT_FOLD_EXPR:
5765 case BINARY_RIGHT_FOLD_EXPR:
5766 binary:
5767 for (i = 0; i < 2; ++i)
5768 if (!RECUR (TREE_OPERAND (t, i), want_rval))
5769 return false;
5770 return true;
5772 case CILK_SYNC_STMT:
5773 case CILK_SPAWN_STMT:
5774 case ARRAY_NOTATION_REF:
5775 return false;
5777 case FMA_EXPR:
5778 case VEC_PERM_EXPR:
5779 for (i = 0; i < 3; ++i)
5780 if (!RECUR (TREE_OPERAND (t, i), true))
5781 return false;
5782 return true;
5784 case COND_EXPR:
5785 if (COND_EXPR_IS_VEC_DELETE (t))
5787 if (flags & tf_error)
5788 error_at (loc, "%<delete[]%> is not a constant expression");
5789 return false;
5791 /* Fall through. */
5792 case IF_STMT:
5793 case VEC_COND_EXPR:
5794 /* If the condition is a known constant, we know which of the legs we
5795 care about; otherwise we only require that the condition and
5796 either of the legs be potentially constant. */
5797 tmp = TREE_OPERAND (t, 0);
5798 if (!RECUR (tmp, rval))
5799 return false;
5800 if (!processing_template_decl)
5801 tmp = cxx_eval_outermost_constant_expr (tmp, true);
5802 if (integer_zerop (tmp))
5803 return RECUR (TREE_OPERAND (t, 2), want_rval);
5804 else if (TREE_CODE (tmp) == INTEGER_CST)
5805 return RECUR (TREE_OPERAND (t, 1), want_rval);
5806 for (i = 1; i < 3; ++i)
5807 if (potential_constant_expression_1 (TREE_OPERAND (t, i),
5808 want_rval, strict, now, tf_none))
5809 return true;
5810 if (flags & tf_error)
5811 error_at (loc, "expression %qE is not a constant expression", t);
5812 return false;
5814 case VEC_INIT_EXPR:
5815 if (VEC_INIT_EXPR_IS_CONSTEXPR (t))
5816 return true;
5817 if (flags & tf_error)
5819 error_at (loc, "non-constant array initialization");
5820 diagnose_non_constexpr_vec_init (t);
5822 return false;
5824 case TYPE_DECL:
5825 case TAG_DEFN:
5826 /* We can see these in statement-expressions. */
5827 return true;
5829 case CLEANUP_STMT:
5830 case EMPTY_CLASS_EXPR:
5831 case PREDICT_EXPR:
5832 return false;
5834 case GOTO_EXPR:
5836 tree *target = &TREE_OPERAND (t, 0);
5837 /* Gotos representing break and continue are OK. */
5838 if (breaks (target) || continues (target))
5839 return true;
5840 if (flags & tf_error)
5841 error_at (loc, "%<goto%> is not a constant expression");
5842 return false;
5845 case ANNOTATE_EXPR:
5846 gcc_assert (tree_to_uhwi (TREE_OPERAND (t, 1)) == annot_expr_ivdep_kind);
5847 return RECUR (TREE_OPERAND (t, 0), rval);
5849 default:
5850 if (objc_is_property_ref (t))
5851 return false;
5853 sorry ("unexpected AST of kind %s", get_tree_code_name (TREE_CODE (t)));
5854 gcc_unreachable ();
5855 return false;
5857 #undef RECUR
5860 /* The main entry point to the above. */
5862 bool
5863 potential_constant_expression (tree t)
5865 return potential_constant_expression_1 (t, false, true, false, tf_none);
5868 /* As above, but require a constant rvalue. */
5870 bool
5871 potential_rvalue_constant_expression (tree t)
5873 return potential_constant_expression_1 (t, true, true, false, tf_none);
5876 /* Like above, but complain about non-constant expressions. */
5878 bool
5879 require_potential_constant_expression (tree t)
5881 return potential_constant_expression_1 (t, false, true, false, tf_warning_or_error);
5884 /* Cross product of the above. */
5886 bool
5887 require_potential_rvalue_constant_expression (tree t)
5889 return potential_constant_expression_1 (t, true, true, false, tf_warning_or_error);
5892 /* Like potential_constant_expression, but don't consider possible constexpr
5893 substitution of the current function. That is, PARM_DECL qualifies under
5894 potential_constant_expression, but not here.
5896 This is basically what you can check when any actual constant values might
5897 be value-dependent. */
5899 bool
5900 is_constant_expression (tree t)
5902 return potential_constant_expression_1 (t, false, true, true, tf_none);
5905 /* Like above, but complain about non-constant expressions. */
5907 bool
5908 require_constant_expression (tree t)
5910 return potential_constant_expression_1 (t, false, true, true,
5911 tf_warning_or_error);
5914 /* Like is_constant_expression, but allow const variables that are not allowed
5915 under constexpr rules. */
5917 bool
5918 is_static_init_expression (tree t)
5920 return potential_constant_expression_1 (t, false, false, true, tf_none);
5923 /* Returns true if T is a potential constant expression that is not
5924 instantiation-dependent, and therefore a candidate for constant folding even
5925 in a template. */
5927 bool
5928 is_nondependent_constant_expression (tree t)
5930 return (!type_unknown_p (t)
5931 && !BRACE_ENCLOSED_INITIALIZER_P (t)
5932 && is_constant_expression (t)
5933 && !instantiation_dependent_expression_p (t));
5936 /* Returns true if T is a potential static initializer expression that is not
5937 instantiation-dependent. */
5939 bool
5940 is_nondependent_static_init_expression (tree t)
5942 return (!type_unknown_p (t)
5943 && !BRACE_ENCLOSED_INITIALIZER_P (t)
5944 && is_static_init_expression (t)
5945 && !instantiation_dependent_expression_p (t));
5948 /* Finalize constexpr processing after parsing. */
5950 void
5951 fini_constexpr (void)
5953 /* The contexpr call and fundef copies tables are no longer needed. */
5954 constexpr_call_table = NULL;
5955 fundef_copies_table = NULL;
5958 #include "gt-cp-constexpr.h"