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