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